JPEGXLLoader.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  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. };
  312. static ErrorOr<ToneMapping> read_tone_mapping(LittleEndianInputBitStream&)
  313. {
  314. TODO();
  315. }
  316. struct OpsinInverseMatrix {
  317. };
  318. static ErrorOr<OpsinInverseMatrix> read_opsin_inverse_matrix(LittleEndianInputBitStream&)
  319. {
  320. TODO();
  321. }
  322. struct ImageMetadata {
  323. u8 orientation { 1 };
  324. Optional<SizeHeader> intrinsic_size;
  325. Optional<PreviewHeader> preview;
  326. Optional<AnimationHeader> animation;
  327. BitDepth bit_depth;
  328. bool modular_16bit_buffers { true };
  329. u16 num_extra_channels {};
  330. Vector<ExtraChannelInfo, 4> ec_info;
  331. bool xyb_encoded { true };
  332. ColourEncoding colour_encoding;
  333. ToneMapping tone_mapping;
  334. Extensions extensions;
  335. bool default_m;
  336. OpsinInverseMatrix opsin_inverse_matrix;
  337. u8 cw_mask { 0 };
  338. Array<double, 15> up2_weight = s_d_up2;
  339. Array<double, 55> up4_weight = s_d_up4;
  340. Array<double, 210> up8_weight = s_d_up8;
  341. };
  342. static ErrorOr<ImageMetadata> read_metadata_header(LittleEndianInputBitStream& stream)
  343. {
  344. ImageMetadata metadata;
  345. bool const all_default = TRY(stream.read_bit());
  346. if (!all_default) {
  347. bool const extra_fields = TRY(stream.read_bit());
  348. if (extra_fields) {
  349. metadata.orientation = 1 + TRY(stream.read_bits(3));
  350. bool const have_intr_size = TRY(stream.read_bit());
  351. if (have_intr_size)
  352. metadata.intrinsic_size = TRY(read_size_header(stream));
  353. bool const have_preview = TRY(stream.read_bit());
  354. if (have_preview)
  355. TODO();
  356. bool const have_animation = TRY(stream.read_bit());
  357. if (have_animation)
  358. TODO();
  359. }
  360. metadata.bit_depth = TRY(read_bit_depth(stream));
  361. metadata.modular_16bit_buffers = TRY(stream.read_bit());
  362. metadata.num_extra_channels = U32(0, 1, 2 + TRY(stream.read_bits(4)), 1 + TRY(stream.read_bits(12)));
  363. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  364. metadata.ec_info.append(TRY(read_extra_channel_info(stream)));
  365. metadata.xyb_encoded = TRY(stream.read_bit());
  366. metadata.colour_encoding = TRY(read_colour_encoding(stream));
  367. if (extra_fields)
  368. metadata.tone_mapping = TRY(read_tone_mapping(stream));
  369. metadata.extensions = TRY(read_extensions(stream));
  370. }
  371. metadata.default_m = TRY(stream.read_bit());
  372. if (!metadata.default_m && metadata.xyb_encoded)
  373. metadata.opsin_inverse_matrix = TRY(read_opsin_inverse_matrix(stream));
  374. if (!metadata.default_m)
  375. metadata.cw_mask = TRY(stream.read_bits(3));
  376. if (metadata.cw_mask != 0)
  377. TODO();
  378. return metadata;
  379. }
  380. ///
  381. /// Table F.7 — BlendingInfo bundle
  382. struct BlendingInfo {
  383. enum class BlendMode {
  384. kReplace = 0,
  385. kAdd = 1,
  386. kBlend = 2,
  387. kMulAdd = 3,
  388. kMul = 4,
  389. };
  390. BlendMode mode {};
  391. u8 alpha_channel {};
  392. bool clamp { false };
  393. u8 source {};
  394. };
  395. static ErrorOr<BlendingInfo> read_blending_info(LittleEndianInputBitStream& stream, ImageMetadata const& metadata, bool full_frame)
  396. {
  397. BlendingInfo blending_info;
  398. blending_info.mode = static_cast<BlendingInfo::BlendMode>(U32(0, 1, 2, 3 + TRY(stream.read_bits(2))));
  399. bool const extra = metadata.num_extra_channels > 0;
  400. if (extra) {
  401. auto const blend_or_mul_add = blending_info.mode == BlendingInfo::BlendMode::kBlend
  402. || blending_info.mode == BlendingInfo::BlendMode::kMulAdd;
  403. if (blend_or_mul_add)
  404. blending_info.alpha_channel = U32(0, 1, 2, 3 + TRY(stream.read_bits(3)));
  405. if (blend_or_mul_add || blending_info.mode == BlendingInfo::BlendMode::kMul)
  406. blending_info.clamp = TRY(stream.read_bit());
  407. }
  408. if (blending_info.mode != BlendingInfo::BlendMode::kReplace
  409. || !full_frame) {
  410. blending_info.source = TRY(stream.read_bits(2));
  411. }
  412. return blending_info;
  413. }
  414. ///
  415. /// J.1 - General
  416. struct RestorationFilter {
  417. bool gab { true };
  418. u8 epf_iters { 2 };
  419. Extensions extensions;
  420. };
  421. static ErrorOr<RestorationFilter> read_restoration_filter(LittleEndianInputBitStream& stream)
  422. {
  423. RestorationFilter restoration_filter;
  424. auto const all_defaults = TRY(stream.read_bit());
  425. if (!all_defaults) {
  426. restoration_filter.gab = TRY(stream.read_bit());
  427. if (restoration_filter.gab) {
  428. TODO();
  429. }
  430. restoration_filter.epf_iters = TRY(stream.read_bits(2));
  431. if (restoration_filter.epf_iters != 0) {
  432. TODO();
  433. }
  434. restoration_filter.extensions = TRY(read_extensions(stream));
  435. }
  436. return restoration_filter;
  437. }
  438. ///
  439. /// Table F.6 — Passes bundle
  440. struct Passes {
  441. u8 num_passes { 1 };
  442. };
  443. static ErrorOr<Passes> read_passes(LittleEndianInputBitStream& stream)
  444. {
  445. Passes passes;
  446. passes.num_passes = U32(1, 2, 3, 4 + TRY(stream.read_bits(3)));
  447. if (passes.num_passes != 1) {
  448. TODO();
  449. }
  450. return passes;
  451. }
  452. ///
  453. /// F.2 - FrameHeader
  454. struct FrameHeader {
  455. enum class FrameType {
  456. kRegularFrame = 0,
  457. kLFFrame = 1,
  458. kReferenceOnly = 2,
  459. kSkipProgressive = 3,
  460. };
  461. enum class Encoding {
  462. kVarDCT = 0,
  463. kModular = 1,
  464. };
  465. enum class Flags {
  466. None = 0,
  467. kNoise = 1,
  468. kPatches = 1 << 1,
  469. kSplines = 1 << 4,
  470. kUseLfFrame = 1 << 5,
  471. kSkipAdaptiveLFSmoothing = 1 << 7,
  472. };
  473. FrameType frame_type { FrameType::kRegularFrame };
  474. Encoding encoding { Encoding::kVarDCT };
  475. Flags flags { Flags::None };
  476. bool do_YCbCr { false };
  477. Array<u8, 3> jpeg_upsampling {};
  478. u8 upsampling {};
  479. Vector<u8> ec_upsampling {};
  480. u8 group_size_shift { 1 };
  481. Passes passes {};
  482. u8 lf_level {};
  483. bool have_crop { false };
  484. BlendingInfo blending_info {};
  485. u32 duration {};
  486. bool is_last { true };
  487. u8 save_as_reference {};
  488. bool save_before_ct {};
  489. String name {};
  490. RestorationFilter restoration_filter {};
  491. Extensions extensions {};
  492. };
  493. static int operator&(FrameHeader::Flags first, FrameHeader::Flags second)
  494. {
  495. return static_cast<int>(first) & static_cast<int>(second);
  496. }
  497. static ErrorOr<FrameHeader> read_frame_header(LittleEndianInputBitStream& stream, ImageMetadata const& metadata)
  498. {
  499. FrameHeader frame_header;
  500. bool const all_default = TRY(stream.read_bit());
  501. if (!all_default) {
  502. frame_header.frame_type = static_cast<FrameHeader::FrameType>(TRY(stream.read_bits(2)));
  503. frame_header.encoding = static_cast<FrameHeader::Encoding>(TRY(stream.read_bits(1)));
  504. frame_header.flags = static_cast<FrameHeader::Flags>(TRY(U64(stream)));
  505. if (!metadata.xyb_encoded)
  506. frame_header.do_YCbCr = TRY(stream.read_bit());
  507. if (!(frame_header.flags & FrameHeader::Flags::kUseLfFrame)) {
  508. if (frame_header.do_YCbCr) {
  509. frame_header.jpeg_upsampling[0] = TRY(stream.read_bits(2));
  510. frame_header.jpeg_upsampling[1] = TRY(stream.read_bits(2));
  511. frame_header.jpeg_upsampling[2] = TRY(stream.read_bits(2));
  512. }
  513. frame_header.upsampling = U32(1, 2, 4, 8);
  514. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  515. TODO();
  516. }
  517. if (frame_header.encoding == FrameHeader::Encoding::kModular)
  518. frame_header.group_size_shift = TRY(stream.read_bits(2));
  519. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  520. TODO();
  521. if (frame_header.frame_type != FrameHeader::FrameType::kReferenceOnly)
  522. frame_header.passes = TRY(read_passes(stream));
  523. if (frame_header.frame_type == FrameHeader::FrameType::kLFFrame)
  524. TODO();
  525. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame)
  526. frame_header.have_crop = TRY(stream.read_bit());
  527. if (frame_header.have_crop)
  528. TODO();
  529. bool const normal_frame = frame_header.frame_type == FrameHeader::FrameType::kRegularFrame
  530. || frame_header.frame_type == FrameHeader::FrameType::kSkipProgressive;
  531. // FIXME: also consider "cropped" image of the dimension of the frame
  532. VERIFY(!frame_header.have_crop);
  533. bool const full_frame = !frame_header.have_crop;
  534. if (normal_frame) {
  535. frame_header.blending_info = TRY(read_blending_info(stream, metadata, full_frame));
  536. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  537. TODO();
  538. if (metadata.animation.has_value())
  539. TODO();
  540. frame_header.is_last = TRY(stream.read_bit());
  541. }
  542. // FIXME: Ensure that is_last has the correct default value
  543. VERIFY(normal_frame);
  544. auto const resets_canvas = full_frame && frame_header.blending_info.mode == BlendingInfo::BlendMode::kReplace;
  545. 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;
  546. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame) {
  547. if (!frame_header.is_last)
  548. TODO();
  549. }
  550. frame_header.save_before_ct = !normal_frame;
  551. if (frame_header.frame_type == FrameHeader::FrameType::kReferenceOnly || (resets_canvas && can_reference))
  552. frame_header.save_before_ct = TRY(stream.read_bit());
  553. frame_header.name = TRY(read_string(stream));
  554. frame_header.restoration_filter = TRY(read_restoration_filter(stream));
  555. frame_header.extensions = TRY(read_extensions(stream));
  556. }
  557. return frame_header;
  558. }
  559. ///
  560. /// F.3 TOC
  561. struct TOC {
  562. FixedArray<u32> entries;
  563. FixedArray<u32> group_offsets;
  564. };
  565. static u64 num_toc_entries(FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  566. {
  567. // F.3.1 - General
  568. if (num_groups == 1 && frame_header.passes.num_passes == 1)
  569. return 1;
  570. return 1 + num_lf_groups + 1 + num_groups * frame_header.passes.num_passes;
  571. }
  572. static ErrorOr<TOC> read_toc(LittleEndianInputBitStream& stream, FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  573. {
  574. TOC toc;
  575. bool const permuted_toc = TRY(stream.read_bit());
  576. if (permuted_toc) {
  577. // Read permutations
  578. TODO();
  579. }
  580. // F.3.3 - Decoding TOC
  581. stream.align_to_byte_boundary();
  582. auto const toc_entries = num_toc_entries(frame_header, num_groups, num_lf_groups);
  583. toc.entries = TRY(FixedArray<u32>::create(toc_entries));
  584. toc.group_offsets = TRY(FixedArray<u32>::create(toc_entries));
  585. for (u32 i {}; i < toc_entries; ++i) {
  586. auto const new_entry = U32(
  587. TRY(stream.read_bits(10)),
  588. 1024 + TRY(stream.read_bits(14)),
  589. 17408 + TRY(stream.read_bits(22)),
  590. 4211712 + TRY(stream.read_bits(30)));
  591. toc.entries[i] = new_entry;
  592. toc.group_offsets[i] = (i == 0 ? 0 : toc.group_offsets[i - 1]) + new_entry;
  593. }
  594. if (permuted_toc)
  595. TODO();
  596. stream.align_to_byte_boundary();
  597. return toc;
  598. }
  599. ///
  600. /// G.1.2 - LF channel dequantization weights
  601. struct LfChannelDequantization {
  602. float m_x_lf_unscaled { 4096 };
  603. float m_y_lf_unscaled { 512 };
  604. float m_b_lf_unscaled { 256 };
  605. };
  606. static ErrorOr<LfChannelDequantization> read_lf_channel_dequantization(LittleEndianInputBitStream& stream)
  607. {
  608. LfChannelDequantization lf_channel_dequantization;
  609. auto const all_default = TRY(stream.read_bit());
  610. if (!all_default) {
  611. TODO();
  612. }
  613. return lf_channel_dequantization;
  614. }
  615. ///
  616. /// C - Entropy decoding
  617. class EntropyDecoder {
  618. using BrotliCanonicalCode = Compress::Brotli::CanonicalCode;
  619. public:
  620. static ErrorOr<EntropyDecoder> create(LittleEndianInputBitStream& stream, u8 initial_num_distrib)
  621. {
  622. EntropyDecoder entropy_decoder;
  623. // C.2 - Distribution decoding
  624. entropy_decoder.m_lz77_enabled = TRY(stream.read_bit());
  625. if (entropy_decoder.m_lz77_enabled) {
  626. TODO();
  627. }
  628. TRY(entropy_decoder.read_pre_clustered_distributions(stream, initial_num_distrib));
  629. bool const use_prefix_code = TRY(stream.read_bit());
  630. if (!use_prefix_code)
  631. entropy_decoder.m_log_alphabet_size = 5 + TRY(stream.read_bits(2));
  632. for (auto& config : entropy_decoder.m_configs)
  633. config = TRY(entropy_decoder.read_config(stream));
  634. Vector<u16> counts;
  635. TRY(counts.try_resize(entropy_decoder.m_configs.size()));
  636. TRY(entropy_decoder.m_distributions.try_resize(entropy_decoder.m_configs.size()));
  637. if (use_prefix_code) {
  638. for (auto& count : counts) {
  639. if (TRY(stream.read_bit())) {
  640. auto const n = TRY(stream.read_bits(4));
  641. count = 1 + (1 << n) + TRY(stream.read_bits(n));
  642. } else {
  643. count = 1;
  644. }
  645. }
  646. // After reading the counts, the decoder reads each D[i] (implicitly
  647. // described by a prefix code) as specified in C.2.4, with alphabet_size = count[i].
  648. for (u32 i {}; i < entropy_decoder.m_distributions.size(); ++i) {
  649. // The alphabet size mentioned in the [Brotli] RFC is explicitly specified as parameter alphabet_size
  650. // when the histogram is being decoded, except in the special case of alphabet_size == 1, where no
  651. // histogram is read, and all decoded symbols are zero without reading any bits at all.
  652. if (counts[i] != 1) {
  653. entropy_decoder.m_distributions[i] = TRY(BrotliCanonicalCode::read_prefix_code(stream, counts[i]));
  654. } else {
  655. entropy_decoder.m_distributions[i] = BrotliCanonicalCode { { 1 }, { 0 } };
  656. }
  657. }
  658. } else {
  659. TODO();
  660. }
  661. return entropy_decoder;
  662. }
  663. ErrorOr<u32> decode_hybrid_uint(LittleEndianInputBitStream& stream, u16 context)
  664. {
  665. // C.3.3 - Hybrid integer decoding
  666. if (m_lz77_enabled)
  667. TODO();
  668. // Read symbol from entropy coded stream using D[clusters[ctx]]
  669. auto const token = TRY(m_distributions[m_clusters[context]].read_symbol(stream));
  670. auto r = TRY(read_uint(stream, m_configs[m_clusters[context]], token));
  671. return r;
  672. }
  673. private:
  674. struct HybridUint {
  675. u32 split_exponent {};
  676. u32 split {};
  677. u32 msb_in_token {};
  678. u32 lsb_in_token {};
  679. };
  680. static ErrorOr<u32> read_uint(LittleEndianInputBitStream& stream, HybridUint const& config, u32 token)
  681. {
  682. if (token < config.split)
  683. return token;
  684. auto const n = config.split_exponent
  685. - config.msb_in_token
  686. - config.lsb_in_token
  687. + ((token - config.split) >> (config.msb_in_token + config.lsb_in_token));
  688. VERIFY(n < 32);
  689. u32 const low_bits = token & ((1 << config.lsb_in_token) - 1);
  690. token = token >> config.lsb_in_token;
  691. token &= (1 << config.msb_in_token) - 1;
  692. token |= (1 << config.msb_in_token);
  693. auto const result = ((token << n | TRY(stream.read_bits(n))) << config.lsb_in_token) | low_bits;
  694. VERIFY(result < (1ul << 32));
  695. return result;
  696. }
  697. ErrorOr<void> read_pre_clustered_distributions(LittleEndianInputBitStream& stream, u8 num_distrib)
  698. {
  699. // C.2.2 Distribution clustering
  700. if (num_distrib == 1)
  701. TODO();
  702. TRY(m_clusters.try_resize(num_distrib));
  703. bool const is_simple = TRY(stream.read_bit());
  704. u16 num_clusters = 0;
  705. if (is_simple) {
  706. u8 const nbits = TRY(stream.read_bits(2));
  707. for (u8 i {}; i < num_distrib; ++i) {
  708. m_clusters[i] = TRY(stream.read_bits(nbits));
  709. if (m_clusters[i] >= num_clusters)
  710. num_clusters = m_clusters[i] + 1;
  711. }
  712. } else {
  713. TODO();
  714. }
  715. TRY(m_configs.try_resize(num_clusters));
  716. return {};
  717. }
  718. ErrorOr<HybridUint> read_config(LittleEndianInputBitStream& stream) const
  719. {
  720. // C.2.3 - Hybrid integer configuration
  721. HybridUint config {};
  722. config.split_exponent = TRY(stream.read_bits(ceil(log2(m_log_alphabet_size + 1))));
  723. if (config.split_exponent != m_log_alphabet_size) {
  724. auto nbits = ceil(log2(config.split_exponent + 1));
  725. config.msb_in_token = TRY(stream.read_bits(nbits));
  726. nbits = ceil(log2(config.split_exponent - config.msb_in_token + 1));
  727. config.lsb_in_token = TRY(stream.read_bits(nbits));
  728. } else {
  729. config.msb_in_token = 0;
  730. config.lsb_in_token = 0;
  731. }
  732. config.split = 1 << config.split_exponent;
  733. return config;
  734. }
  735. bool m_lz77_enabled {};
  736. Vector<u32> m_clusters;
  737. Vector<HybridUint> m_configs;
  738. u8 m_log_alphabet_size { 15 };
  739. Vector<BrotliCanonicalCode> m_distributions; // D in the spec
  740. };
  741. ///
  742. /// H.4.2 - MA tree decoding
  743. class MATree {
  744. public:
  745. struct LeafNode {
  746. u8 ctx {};
  747. u8 predictor {};
  748. i32 offset {};
  749. u32 multiplier {};
  750. };
  751. static ErrorOr<MATree> decode(LittleEndianInputBitStream& stream, Optional<EntropyDecoder>& decoder)
  752. {
  753. // G.1.3 - GlobalModular
  754. MATree tree;
  755. // 1 / 2 Read the 6 pre-clustered distributions
  756. auto const num_distrib = 6;
  757. if (!decoder.has_value())
  758. decoder = TRY(EntropyDecoder::create(stream, num_distrib));
  759. // 2 / 2 Decode the tree
  760. u64 ctx_id = 0;
  761. u64 nodes_left = 1;
  762. tree.m_tree.clear();
  763. while (nodes_left > 0) {
  764. nodes_left--;
  765. i32 const property = TRY(decoder->decode_hybrid_uint(stream, 1)) - 1;
  766. if (property >= 0) {
  767. DecisionNode decision_node;
  768. decision_node.property = property;
  769. decision_node.value = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 0)));
  770. decision_node.left_child = tree.m_tree.size() + nodes_left + 1;
  771. decision_node.right_child = tree.m_tree.size() + nodes_left + 2;
  772. tree.m_tree.empend(decision_node);
  773. nodes_left += 2;
  774. } else {
  775. LeafNode leaf_node;
  776. leaf_node.ctx = ctx_id++;
  777. leaf_node.predictor = TRY(decoder->decode_hybrid_uint(stream, 2));
  778. leaf_node.offset = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 3)));
  779. auto const mul_log = TRY(decoder->decode_hybrid_uint(stream, 4));
  780. auto const mul_bits = TRY(decoder->decode_hybrid_uint(stream, 5));
  781. leaf_node.multiplier = (mul_bits + 1) << mul_log;
  782. tree.m_tree.empend(leaf_node);
  783. }
  784. }
  785. // Finally, the decoder reads (tree.size() + 1) / 2 pre-clustered distributions D as specified in C.1.
  786. auto const num_pre_clustered_distributions = (tree.m_tree.size() + 1) / 2;
  787. decoder = TRY(decoder->create(stream, num_pre_clustered_distributions));
  788. return tree;
  789. }
  790. LeafNode get_leaf(Vector<i32> const& properties) const
  791. {
  792. // To find the MA leaf node, the MA tree is traversed, starting at the root node tree[0]
  793. // and for each decision node d, testing if property[d.property] > d.value, proceeding to
  794. // the node tree[d.left_child] if the test evaluates to true and to the node tree[d.right_child]
  795. // otherwise, until a leaf node is reached.
  796. DecisionNode node { m_tree[0].get<DecisionNode>() };
  797. while (true) {
  798. auto const next_node = [this, &properties, &node]() {
  799. // Note: The behavior when trying to access a non-existing property is taken from jxl-oxide
  800. if (node.property < properties.size() && properties[node.property] > node.value)
  801. return m_tree[node.left_child];
  802. return m_tree[node.right_child];
  803. }();
  804. if (next_node.has<LeafNode>())
  805. return next_node.get<LeafNode>();
  806. node = next_node.get<DecisionNode>();
  807. }
  808. }
  809. private:
  810. struct DecisionNode {
  811. u64 property {};
  812. i64 value {};
  813. u64 left_child {};
  814. u64 right_child {};
  815. };
  816. Vector<Variant<DecisionNode, LeafNode>> m_tree;
  817. };
  818. ///
  819. /// H.5 - Self-correcting predictor
  820. struct WPHeader {
  821. u8 wp_p1 { 16 };
  822. u8 wp_p2 { 10 };
  823. u8 wp_p3a { 7 };
  824. u8 wp_p3b { 7 };
  825. u8 wp_p3c { 7 };
  826. u8 wp_p3d { 0 };
  827. u8 wp_p3e { 0 };
  828. u8 wp_w0 { 13 };
  829. u8 wp_w1 { 12 };
  830. u8 wp_w2 { 12 };
  831. u8 wp_w3 { 12 };
  832. };
  833. static ErrorOr<WPHeader> read_self_correcting_predictor(LittleEndianInputBitStream& stream)
  834. {
  835. WPHeader self_correcting_predictor {};
  836. bool const default_wp = TRY(stream.read_bit());
  837. if (!default_wp) {
  838. TODO();
  839. }
  840. return self_correcting_predictor;
  841. }
  842. ///
  843. ///
  844. struct TransformInfo {
  845. enum class TransformId {
  846. kRCT = 0,
  847. kPalette = 1,
  848. kSqueeze = 2,
  849. };
  850. TransformId tr {};
  851. u32 begin_c {};
  852. u32 rct_type {};
  853. };
  854. static ErrorOr<TransformInfo> read_transform_info(LittleEndianInputBitStream& stream)
  855. {
  856. TransformInfo transform_info;
  857. transform_info.tr = static_cast<TransformInfo::TransformId>(TRY(stream.read_bits(2)));
  858. if (transform_info.tr != TransformInfo::TransformId::kSqueeze) {
  859. transform_info.begin_c = U32(
  860. TRY(stream.read_bits(3)),
  861. 8 + TRY(stream.read_bits(3)),
  862. 72 + TRY(stream.read_bits(10)),
  863. 1096 + TRY(stream.read_bits(13)));
  864. }
  865. if (transform_info.tr == TransformInfo::TransformId::kRCT) {
  866. transform_info.rct_type = U32(
  867. 6,
  868. TRY(stream.read_bits(2)),
  869. 2 + TRY(stream.read_bits(4)),
  870. 10 + TRY(stream.read_bits(6)));
  871. }
  872. if (transform_info.tr != TransformInfo::TransformId::kRCT)
  873. TODO();
  874. return transform_info;
  875. }
  876. ///
  877. /// Local abstractions to store the decoded image
  878. class Channel {
  879. public:
  880. static ErrorOr<Channel> create(u32 width, u32 height)
  881. {
  882. Channel channel;
  883. channel.m_width = width;
  884. channel.m_height = height;
  885. TRY(channel.m_pixels.try_resize(channel.m_width * channel.m_height));
  886. return channel;
  887. }
  888. i32 get(u32 x, u32 y) const
  889. {
  890. return m_pixels[x * m_width + y];
  891. }
  892. void set(u32 x, u32 y, i32 value)
  893. {
  894. m_pixels[x * m_width + y] = value;
  895. }
  896. u32 width() const
  897. {
  898. return m_width;
  899. }
  900. u32 height() const
  901. {
  902. return m_height;
  903. }
  904. u32 hshift() const
  905. {
  906. return m_hshift;
  907. }
  908. u32 vshift() const
  909. {
  910. return m_vshift;
  911. }
  912. bool decoded() const
  913. {
  914. return m_decoded;
  915. }
  916. void set_decoded(bool decoded)
  917. {
  918. m_decoded = decoded;
  919. }
  920. private:
  921. u32 m_width {};
  922. u32 m_height {};
  923. u32 m_hshift {};
  924. u32 m_vshift {};
  925. bool m_decoded { false };
  926. Vector<i32> m_pixels {};
  927. };
  928. class Image {
  929. public:
  930. static ErrorOr<Image> create(IntSize size)
  931. {
  932. Image image {};
  933. // FIXME: Don't assume three channels and a fixed size
  934. TRY(image.m_channels.try_append(TRY(Channel::create(size.width(), size.height()))));
  935. TRY(image.m_channels.try_append(TRY(Channel::create(size.width(), size.height()))));
  936. TRY(image.m_channels.try_append(TRY(Channel::create(size.width(), size.height()))));
  937. return image;
  938. }
  939. ErrorOr<NonnullRefPtr<Bitmap>> to_bitmap(u8 bits_per_sample) const
  940. {
  941. // FIXME: which channel size should we use?
  942. auto const width = m_channels[0].width();
  943. auto const height = m_channels[0].height();
  944. auto bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { width, height }));
  945. // FIXME: This assumes a raw image with RGB channels, other cases are possible
  946. VERIFY(bits_per_sample >= 8);
  947. for (u32 y {}; y < height; ++y) {
  948. for (u32 x {}; x < width; ++x) {
  949. auto const to_u8 = [&, bits_per_sample](i32 sample) -> u8 {
  950. // FIXME: Don't truncate the result to 8 bits
  951. static constexpr auto maximum_supported_bit_depth = 8;
  952. if (bits_per_sample > maximum_supported_bit_depth)
  953. sample >>= (bits_per_sample - maximum_supported_bit_depth);
  954. return clamp(sample + .5, 0, (1 << maximum_supported_bit_depth) - 1);
  955. };
  956. Color const color {
  957. to_u8(m_channels[0].get(x, y)),
  958. to_u8(m_channels[1].get(x, y)),
  959. to_u8(m_channels[2].get(x, y)),
  960. };
  961. bitmap->set_pixel(x, y, color);
  962. }
  963. }
  964. return bitmap;
  965. }
  966. Vector<Channel>& channels()
  967. {
  968. return m_channels;
  969. }
  970. private:
  971. Vector<Channel> m_channels;
  972. };
  973. ///
  974. /// H.2 - Image decoding
  975. struct ModularHeader {
  976. bool use_global_tree {};
  977. WPHeader wp_params {};
  978. Vector<TransformInfo> transform {};
  979. };
  980. static ErrorOr<Vector<i32>> get_properties(Vector<Channel> const& channels, u16 i, u32 x, u32 y)
  981. {
  982. Vector<i32> properties;
  983. // Table H.4 - Property definitions
  984. TRY(properties.try_append(i));
  985. // FIXME: Handle other cases than GlobalModular
  986. TRY(properties.try_append(0));
  987. TRY(properties.try_append(y));
  988. TRY(properties.try_append(x));
  989. i32 const W = x > 0 ? channels[i].get(x - 1, y) : (y > 0 ? channels[i].get(x, y - 1) : 0);
  990. i32 const N = y > 0 ? channels[i].get(x, y - 1) : W;
  991. i32 const NW = x > 0 && y > 0 ? channels[i].get(x - 1, y - 1) : W;
  992. i32 const NE = x + 1 < channels[i].width() && y > 0 ? channels[i].get(x + 1, y - 1) : N;
  993. i32 const NN = y > 1 ? channels[i].get(x, y - 2) : N;
  994. i32 const WW = x > 1 ? channels[i].get(x - 2, y) : W;
  995. TRY(properties.try_append(abs(N)));
  996. TRY(properties.try_append(abs(W)));
  997. TRY(properties.try_append(N));
  998. TRY(properties.try_append(W));
  999. // x > 0 ? W - /* (the value of property 9 at position (x - 1, y)) */ : W
  1000. i32 x_1 = x - 1;
  1001. i32 const W_x_1 = x_1 > 0 ? channels[i].get(x_1 - 1, y) : (x_1 >= 0 && y > 0 ? channels[i].get(x_1, y - 1) : 0);
  1002. i32 const N_x_1 = x_1 >= 0 && y > 0 ? channels[i].get(x_1, y - 1) : W_x_1;
  1003. i32 const NW_x_1 = x_1 > 0 && y > 0 ? channels[i].get(x_1 - 1, y - 1) : W_x_1;
  1004. TRY(properties.try_append(W_x_1 + N_x_1 - NW_x_1));
  1005. TRY(properties.try_append(W + N - NW));
  1006. TRY(properties.try_append(W - NW));
  1007. TRY(properties.try_append(NW - N));
  1008. TRY(properties.try_append(N - NE));
  1009. TRY(properties.try_append(N - NN));
  1010. TRY(properties.try_append(W - WW));
  1011. // FIXME: Correctly compute max_error
  1012. TRY(properties.try_append(0));
  1013. for (i16 j = i - 1; j >= 0; j--) {
  1014. if (channels[j].width() != channels[i].width())
  1015. continue;
  1016. if (channels[j].height() != channels[i].height())
  1017. continue;
  1018. if (channels[j].hshift() != channels[i].hshift())
  1019. continue;
  1020. if (channels[j].vshift() != channels[i].vshift())
  1021. continue;
  1022. auto rC = channels[j].get(x, y);
  1023. auto rW = (x > 0 ? channels[j].get(x - 1, y) : 0);
  1024. auto rN = (y > 0 ? channels[j].get(x, y - 1) : rW);
  1025. auto rNW = (x > 0 && y > 0 ? channels[j].get(x - 1, y - 1) : rW);
  1026. auto rG = clamp(rW + rN - rNW, min(rW, rN), max(rW, rN));
  1027. TRY(properties.try_append(abs(rC)));
  1028. TRY(properties.try_append(rC));
  1029. TRY(properties.try_append(abs(rC - rG)));
  1030. TRY(properties.try_append(rC - rG));
  1031. }
  1032. return properties;
  1033. }
  1034. static i32 prediction(Channel const& channel, u32 x, u32 y, u32 predictor)
  1035. {
  1036. i32 const W = x > 0 ? channel.get(x - 1, y) : (y > 0 ? channel.get(x, y - 1) : 0);
  1037. i32 const N = y > 0 ? channel.get(x, y - 1) : W;
  1038. i32 const NW = x > 0 && y > 0 ? channel.get(x - 1, y - 1) : W;
  1039. i32 const NE = x + 1 < channel.width() && y > 0 ? channel.get(x + 1, y - 1) : N;
  1040. i32 const NN = y > 1 ? channel.get(x, y - 2) : N;
  1041. i32 const NEE = x + 2 < channel.width() and y > 0 ? channel.get(x + 2, y - 1) : NE;
  1042. i32 const WW = x > 1 ? channel.get(x - 2, y) : W;
  1043. switch (predictor) {
  1044. case 0:
  1045. return 0;
  1046. case 1:
  1047. return W;
  1048. case 2:
  1049. return N;
  1050. case 3:
  1051. return (W + N) / 2;
  1052. case 4:
  1053. return abs(N - NW) < abs(W - NW) ? W : N;
  1054. case 5:
  1055. return clamp(W + N - NW, min(W, N), max(W, N));
  1056. case 6:
  1057. TODO();
  1058. return (0 + 3) >> 3;
  1059. case 7:
  1060. return NE;
  1061. case 8:
  1062. return NW;
  1063. case 9:
  1064. return WW;
  1065. case 10:
  1066. return (W + NW) / 2;
  1067. case 11:
  1068. return (N + NW) / 2;
  1069. case 12:
  1070. return (N + NE) / 2;
  1071. case 13:
  1072. return (6 * N - 2 * NN + 7 * W + WW + NEE + 3 * NE + 8) / 16;
  1073. }
  1074. VERIFY_NOT_REACHED();
  1075. }
  1076. static ErrorOr<ModularHeader> read_modular_header(LittleEndianInputBitStream& stream,
  1077. Image& image,
  1078. Optional<EntropyDecoder>& decoder,
  1079. MATree const& global_tree,
  1080. u16 num_channels)
  1081. {
  1082. ModularHeader modular_header;
  1083. modular_header.use_global_tree = TRY(stream.read_bit());
  1084. modular_header.wp_params = TRY(read_self_correcting_predictor(stream));
  1085. auto const nb_transforms = U32(0, 1, 2 + TRY(stream.read_bits(4)), 18 + TRY(stream.read_bits(8)));
  1086. TRY(modular_header.transform.try_resize(nb_transforms));
  1087. for (u32 i {}; i < nb_transforms; ++i)
  1088. modular_header.transform[i] = TRY(read_transform_info(stream));
  1089. Optional<MATree> local_tree;
  1090. if (!modular_header.use_global_tree)
  1091. TODO();
  1092. // The decoder then starts an entropy-coded stream (C.1) and decodes the data for each channel
  1093. // (in ascending order of index) as specified in H.3, skipping any channels having width or height
  1094. // zero. Finally, the inverse transformations are applied (from last to first) as described in H.6.
  1095. auto const& tree = local_tree.has_value() ? *local_tree : global_tree;
  1096. for (u16 i {}; i < num_channels; ++i) {
  1097. for (u32 y {}; y < image.channels()[i].height(); y++) {
  1098. for (u32 x {}; x < image.channels()[i].width(); x++) {
  1099. auto const properties = TRY(get_properties(image.channels(), i, x, y));
  1100. auto const leaf_node = tree.get_leaf(properties);
  1101. auto diff = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, leaf_node.ctx)));
  1102. diff = (diff * leaf_node.multiplier) + leaf_node.offset;
  1103. auto const total = diff + prediction(image.channels()[i], x, y, leaf_node.predictor);
  1104. image.channels()[i].set(x, y, total);
  1105. }
  1106. }
  1107. image.channels()[i].set_decoded(true);
  1108. }
  1109. return modular_header;
  1110. }
  1111. ///
  1112. /// G.1.2 - LF channel dequantization weights
  1113. struct GlobalModular {
  1114. MATree ma_tree;
  1115. ModularHeader modular_header;
  1116. };
  1117. static ErrorOr<GlobalModular> read_global_modular(LittleEndianInputBitStream& stream,
  1118. Image& image,
  1119. FrameHeader const& frame_header,
  1120. ImageMetadata const& metadata,
  1121. Optional<EntropyDecoder>& entropy_decoder)
  1122. {
  1123. GlobalModular global_modular;
  1124. auto const decode_ma_tree = TRY(stream.read_bit());
  1125. if (decode_ma_tree)
  1126. global_modular.ma_tree = TRY(MATree::decode(stream, entropy_decoder));
  1127. // The decoder then decodes a modular sub-bitstream (Annex H), where
  1128. // the number of channels is computed as follows:
  1129. auto num_channels = metadata.num_extra_channels;
  1130. if (frame_header.encoding == FrameHeader::Encoding::kModular) {
  1131. if (!frame_header.do_YCbCr && !metadata.xyb_encoded
  1132. && metadata.colour_encoding.colour_space == ColourEncoding::ColourSpace::kGrey) {
  1133. num_channels += 1;
  1134. } else {
  1135. num_channels += 3;
  1136. }
  1137. }
  1138. // FIXME: Ensure this spec comment:
  1139. // However, the decoder only decodes the first nb_meta_channels channels and any further channels
  1140. // that have a width and height that are both at most group_dim. At that point, it stops decoding.
  1141. // No inverse transforms are applied yet.
  1142. global_modular.modular_header = TRY(read_modular_header(stream, image, entropy_decoder, global_modular.ma_tree, num_channels));
  1143. return global_modular;
  1144. }
  1145. ///
  1146. /// G.1 - LfGlobal
  1147. struct LfGlobal {
  1148. LfChannelDequantization lf_dequant;
  1149. GlobalModular gmodular;
  1150. };
  1151. static ErrorOr<LfGlobal> read_lf_global(LittleEndianInputBitStream& stream,
  1152. Image& image,
  1153. FrameHeader const& frame_header,
  1154. ImageMetadata const& metadata,
  1155. Optional<EntropyDecoder>& entropy_decoder)
  1156. {
  1157. LfGlobal lf_global;
  1158. if (frame_header.flags != FrameHeader::Flags::None)
  1159. TODO();
  1160. lf_global.lf_dequant = TRY(read_lf_channel_dequantization(stream));
  1161. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  1162. TODO();
  1163. lf_global.gmodular = TRY(read_global_modular(stream, image, frame_header, metadata, entropy_decoder));
  1164. return lf_global;
  1165. }
  1166. ///
  1167. /// G.2 - LfGroup
  1168. static ErrorOr<void> read_lf_group(LittleEndianInputBitStream&,
  1169. Image& image,
  1170. FrameHeader const& frame_header)
  1171. {
  1172. // LF coefficients
  1173. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1174. TODO();
  1175. }
  1176. // ModularLfGroup
  1177. for (auto const& channel : image.channels()) {
  1178. if (channel.decoded())
  1179. continue;
  1180. if (channel.hshift() < 3 || channel.vshift() < 3)
  1181. continue;
  1182. // This code actually only detect that we need to read a null image
  1183. // so a no-op. It should be fully rewritten when we add proper support
  1184. // for LfGroup.
  1185. TODO();
  1186. }
  1187. // HF metadata
  1188. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1189. TODO();
  1190. }
  1191. return {};
  1192. }
  1193. ///
  1194. /// H.6 - Transformations
  1195. static void apply_rct(Image& image, TransformInfo const& transformation)
  1196. {
  1197. auto& channels = image.channels();
  1198. for (u32 y {}; y < channels[transformation.begin_c].height(); y++) {
  1199. for (u32 x {}; x < channels[transformation.begin_c].width(); x++) {
  1200. auto a = channels[transformation.begin_c + 0].get(x, y);
  1201. auto b = channels[transformation.begin_c + 1].get(x, y);
  1202. auto c = channels[transformation.begin_c + 2].get(x, y);
  1203. i32 d {};
  1204. i32 e {};
  1205. i32 f {};
  1206. auto const permutation = transformation.rct_type / 7;
  1207. auto const type = transformation.rct_type % 7;
  1208. if (type == 6) { // YCgCo
  1209. auto const tmp = a - (c >> 1);
  1210. e = c + tmp;
  1211. f = tmp - (b >> 1);
  1212. d = f + b;
  1213. } else {
  1214. if (type & 1)
  1215. c = c + a;
  1216. if ((type >> 1) == 1)
  1217. b = b + a;
  1218. if ((type >> 1) == 2)
  1219. b = b + ((a + c) >> 1);
  1220. d = a;
  1221. e = b;
  1222. f = c;
  1223. }
  1224. Array<i32, 3> v {};
  1225. v[permutation % 3] = d;
  1226. v[(permutation + 1 + (permutation / 3)) % 3] = e;
  1227. v[(permutation + 2 - (permutation / 3)) % 3] = f;
  1228. channels[transformation.begin_c + 0].set(x, y, v[0]);
  1229. channels[transformation.begin_c + 1].set(x, y, v[1]);
  1230. channels[transformation.begin_c + 2].set(x, y, v[2]);
  1231. }
  1232. }
  1233. }
  1234. static void apply_transformation(Image& image, TransformInfo const& transformation)
  1235. {
  1236. switch (transformation.tr) {
  1237. case TransformInfo::TransformId::kRCT:
  1238. apply_rct(image, transformation);
  1239. break;
  1240. case TransformInfo::TransformId::kPalette:
  1241. case TransformInfo::TransformId::kSqueeze:
  1242. TODO();
  1243. default:
  1244. VERIFY_NOT_REACHED();
  1245. }
  1246. }
  1247. ///
  1248. /// G.3.2 - PassGroup
  1249. static ErrorOr<void> read_pass_group(LittleEndianInputBitStream& stream,
  1250. Image& image,
  1251. FrameHeader const& frame_header,
  1252. u32 group_dim)
  1253. {
  1254. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1255. (void)stream;
  1256. TODO();
  1257. }
  1258. auto& channels = image.channels();
  1259. for (u16 i {}; i < channels.size(); ++i) {
  1260. // Skip meta-channels
  1261. // FIXME: Also test if the channel has already been decoded
  1262. // See: nb_meta_channels in the spec
  1263. bool const is_meta_channel = channels[i].width() <= group_dim
  1264. || channels[i].height() <= group_dim
  1265. || channels[i].hshift() >= 3
  1266. || channels[i].vshift() >= 3;
  1267. if (!is_meta_channel)
  1268. TODO();
  1269. }
  1270. return {};
  1271. }
  1272. ///
  1273. /// Table F.1 — Frame bundle
  1274. struct Frame {
  1275. FrameHeader frame_header;
  1276. TOC toc;
  1277. LfGlobal lf_global;
  1278. u64 width {};
  1279. u64 height {};
  1280. u64 num_groups {};
  1281. u64 num_lf_groups {};
  1282. };
  1283. static ErrorOr<Frame> read_frame(LittleEndianInputBitStream& stream,
  1284. Image& image,
  1285. SizeHeader const& size_header,
  1286. ImageMetadata const& metadata,
  1287. Optional<EntropyDecoder>& entropy_decoder)
  1288. {
  1289. // F.1 - General
  1290. // Each Frame is byte-aligned by invoking ZeroPadToByte() (B.2.7)
  1291. stream.align_to_byte_boundary();
  1292. Frame frame;
  1293. frame.frame_header = TRY(read_frame_header(stream, metadata));
  1294. if (!frame.frame_header.have_crop) {
  1295. frame.width = size_header.width;
  1296. frame.height = size_header.height;
  1297. } else {
  1298. TODO();
  1299. }
  1300. if (frame.frame_header.upsampling > 1) {
  1301. frame.width = ceil(static_cast<double>(frame.width) / frame.frame_header.upsampling);
  1302. frame.height = ceil(static_cast<double>(frame.height) / frame.frame_header.upsampling);
  1303. }
  1304. if (frame.frame_header.lf_level > 0)
  1305. TODO();
  1306. // F.2 - FrameHeader
  1307. auto const group_dim = 128 << frame.frame_header.group_size_shift;
  1308. auto const frame_width = static_cast<double>(frame.width);
  1309. auto const frame_height = static_cast<double>(frame.height);
  1310. frame.num_groups = ceil(frame_width / group_dim) * ceil(frame_height / group_dim);
  1311. frame.num_lf_groups = ceil(frame_width / (group_dim * 8)) * ceil(frame_height / (group_dim * 8));
  1312. frame.toc = TRY(read_toc(stream, frame.frame_header, frame.num_groups, frame.num_lf_groups));
  1313. image = TRY(Image::create({ frame.width, frame.height }));
  1314. frame.lf_global = TRY(read_lf_global(stream, image, frame.frame_header, metadata, entropy_decoder));
  1315. for (u32 i {}; i < frame.num_lf_groups; ++i)
  1316. TRY(read_lf_group(stream, image, frame.frame_header));
  1317. if (frame.frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1318. TODO();
  1319. }
  1320. auto const num_pass_group = frame.num_groups * frame.frame_header.passes.num_passes;
  1321. auto const& transform_infos = frame.lf_global.gmodular.modular_header.transform;
  1322. for (u64 i {}; i < num_pass_group; ++i)
  1323. TRY(read_pass_group(stream, image, frame.frame_header, group_dim));
  1324. // G.4.2 - Modular group data
  1325. // When all modular groups are decoded, the inverse transforms are applied to
  1326. // the at that point fully decoded GlobalModular image, as specified in H.6.
  1327. for (auto const& transformation : transform_infos.in_reverse())
  1328. apply_transformation(image, transformation);
  1329. return frame;
  1330. }
  1331. ///
  1332. /// 5.2 - Mirroring
  1333. static u32 mirror_1d(i32 coord, u32 size)
  1334. {
  1335. if (coord < 0)
  1336. return mirror_1d(-coord - 1, size);
  1337. else if (static_cast<u32>(coord) >= size)
  1338. return mirror_1d(2 * size - 1 - coord, size);
  1339. else
  1340. return coord;
  1341. }
  1342. ///
  1343. /// K - Image features
  1344. static ErrorOr<void> apply_upsampling(Image& image, ImageMetadata const& metadata, Frame const& frame)
  1345. {
  1346. Optional<u32> ec_max;
  1347. for (auto upsampling : frame.frame_header.ec_upsampling) {
  1348. if (!ec_max.has_value() || upsampling > *ec_max)
  1349. ec_max = upsampling;
  1350. }
  1351. if (frame.frame_header.upsampling > 1 || ec_max.value_or(0) > 1) {
  1352. if (ec_max.value_or(0) > 2)
  1353. TODO();
  1354. auto const k = frame.frame_header.upsampling;
  1355. auto weight = [k, &metadata](u8 index) -> double {
  1356. if (k == 2)
  1357. return metadata.up2_weight[index];
  1358. if (k == 4)
  1359. return metadata.up4_weight[index];
  1360. return metadata.up8_weight[index];
  1361. };
  1362. // FIXME: Use ec_upsampling for extra-channels
  1363. for (auto& channel : image.channels()) {
  1364. auto upsampled = TRY(Channel::create(k * channel.width(), k * channel.height()));
  1365. // Loop over the original image
  1366. for (u32 y {}; y < channel.height(); y++) {
  1367. for (u32 x {}; x < channel.width(); x++) {
  1368. // Loop over the upsampling factor
  1369. for (u8 kx {}; kx < k; ++kx) {
  1370. for (u8 ky {}; ky < k; ++ky) {
  1371. double sum {};
  1372. // Loop over the W window
  1373. double W_min = NumericLimits<double>::max();
  1374. double W_max = -NumericLimits<double>::max();
  1375. for (u8 ix {}; ix < 5; ++ix) {
  1376. for (u8 iy {}; iy < 5; ++iy) {
  1377. auto const j = (ky < k / 2) ? (iy + 5 * ky) : ((4 - iy) + 5 * (k - 1 - ky));
  1378. auto const i = (kx < k / 2) ? (ix + 5 * kx) : ((4 - ix) + 5 * (k - 1 - kx));
  1379. auto const minimum = min(i, j);
  1380. auto const maximum = max(i, j);
  1381. auto const index = 5 * k * minimum / 2 - minimum * (minimum - 1) / 2 + maximum - minimum;
  1382. auto const origin_sample_x = mirror_1d(x + ix - 2, channel.width());
  1383. auto const origin_sample_y = mirror_1d(y + iy - 2, channel.height());
  1384. auto const origin_sample = channel.get(origin_sample_x, origin_sample_y);
  1385. W_min = min(W_min, origin_sample);
  1386. W_max = max(W_max, origin_sample);
  1387. sum += origin_sample * weight(index);
  1388. }
  1389. }
  1390. // The resulting sample is clamped to the range [a, b] where a and b are
  1391. // the minimum and maximum of the samples in W.
  1392. sum = clamp(sum, W_min, W_max);
  1393. upsampled.set(x * k + kx, y * k + ky, sum);
  1394. }
  1395. }
  1396. }
  1397. }
  1398. channel = move(upsampled);
  1399. }
  1400. }
  1401. return {};
  1402. }
  1403. static ErrorOr<void> apply_image_features(Image& image, ImageMetadata const& metadata, Frame const& frame)
  1404. {
  1405. TRY(apply_upsampling(image, metadata, frame));
  1406. if (frame.frame_header.flags != FrameHeader::Flags::None)
  1407. TODO();
  1408. return {};
  1409. }
  1410. ///
  1411. class JPEGXLLoadingContext {
  1412. public:
  1413. JPEGXLLoadingContext(NonnullOwnPtr<Stream> stream)
  1414. : m_stream(move(stream))
  1415. {
  1416. }
  1417. ErrorOr<void> decode_image_header()
  1418. {
  1419. constexpr auto JPEGXL_SIGNATURE = 0xFF0A;
  1420. auto const signature = TRY(m_stream.read_value<BigEndian<u16>>());
  1421. if (signature != JPEGXL_SIGNATURE)
  1422. return Error::from_string_literal("Unrecognized signature");
  1423. m_header = TRY(read_size_header(m_stream));
  1424. m_metadata = TRY(read_metadata_header(m_stream));
  1425. m_state = State::HeaderDecoded;
  1426. return {};
  1427. }
  1428. ErrorOr<void> decode_frame()
  1429. {
  1430. Image image {};
  1431. auto const frame = TRY(read_frame(m_stream, image, m_header, m_metadata, m_entropy_decoder));
  1432. if (frame.frame_header.restoration_filter.gab || frame.frame_header.restoration_filter.epf_iters != 0)
  1433. TODO();
  1434. TRY(apply_image_features(image, m_metadata, frame));
  1435. // FIXME: Do a proper color transformation with metadata.colour_encoding
  1436. if (m_metadata.xyb_encoded || frame.frame_header.do_YCbCr)
  1437. TODO();
  1438. m_bitmap = TRY(image.to_bitmap(m_metadata.bit_depth.bits_per_sample));
  1439. return {};
  1440. }
  1441. ErrorOr<void> decode()
  1442. {
  1443. auto result = [this]() -> ErrorOr<void> {
  1444. // A.1 - Codestream structure
  1445. // The header is already decoded in JPEGXLImageDecoderPlugin::create()
  1446. if (m_metadata.colour_encoding.want_icc)
  1447. TODO();
  1448. if (m_metadata.preview.has_value())
  1449. TODO();
  1450. TRY(decode_frame());
  1451. return {};
  1452. }();
  1453. m_state = result.is_error() ? State::Error : State::FrameDecoded;
  1454. return result;
  1455. }
  1456. enum class State {
  1457. NotDecoded = 0,
  1458. Error,
  1459. HeaderDecoded,
  1460. FrameDecoded,
  1461. };
  1462. State state() const
  1463. {
  1464. return m_state;
  1465. }
  1466. IntSize size() const
  1467. {
  1468. return { m_header.width, m_header.height };
  1469. }
  1470. RefPtr<Bitmap> bitmap() const
  1471. {
  1472. return m_bitmap;
  1473. }
  1474. private:
  1475. State m_state { State::NotDecoded };
  1476. LittleEndianInputBitStream m_stream;
  1477. RefPtr<Gfx::Bitmap> m_bitmap;
  1478. Optional<EntropyDecoder> m_entropy_decoder {};
  1479. SizeHeader m_header;
  1480. ImageMetadata m_metadata;
  1481. FrameHeader m_frame_header;
  1482. TOC m_toc;
  1483. };
  1484. JPEGXLImageDecoderPlugin::JPEGXLImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  1485. {
  1486. m_context = make<JPEGXLLoadingContext>(move(stream));
  1487. }
  1488. JPEGXLImageDecoderPlugin::~JPEGXLImageDecoderPlugin() = default;
  1489. IntSize JPEGXLImageDecoderPlugin::size()
  1490. {
  1491. return m_context->size();
  1492. }
  1493. bool JPEGXLImageDecoderPlugin::sniff(ReadonlyBytes data)
  1494. {
  1495. return data.size() > 2
  1496. && data.data()[0] == 0xFF
  1497. && data.data()[1] == 0x0A;
  1498. }
  1499. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGXLImageDecoderPlugin::create(ReadonlyBytes data)
  1500. {
  1501. auto stream = TRY(try_make<FixedMemoryStream>(data));
  1502. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEGXLImageDecoderPlugin(move(stream))));
  1503. TRY(plugin->m_context->decode_image_header());
  1504. return plugin;
  1505. }
  1506. bool JPEGXLImageDecoderPlugin::is_animated()
  1507. {
  1508. return false;
  1509. }
  1510. size_t JPEGXLImageDecoderPlugin::loop_count()
  1511. {
  1512. return 0;
  1513. }
  1514. size_t JPEGXLImageDecoderPlugin::frame_count()
  1515. {
  1516. return 1;
  1517. }
  1518. size_t JPEGXLImageDecoderPlugin::first_animated_frame_index()
  1519. {
  1520. return 0;
  1521. }
  1522. ErrorOr<ImageFrameDescriptor> JPEGXLImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1523. {
  1524. if (index > 0)
  1525. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Invalid frame index");
  1526. if (m_context->state() == JPEGXLLoadingContext::State::Error)
  1527. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Decoding failed");
  1528. if (m_context->state() < JPEGXLLoadingContext::State::FrameDecoded)
  1529. TRY(m_context->decode());
  1530. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  1531. }
  1532. ErrorOr<Optional<ReadonlyBytes>> JPEGXLImageDecoderPlugin::icc_data()
  1533. {
  1534. return OptionalNone {};
  1535. }
  1536. }