JPEGXLLoader.cpp 80 KB

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