JPEGXLLoader.cpp 80 KB

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