JPEGXLLoader.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  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. i32 x0 {};
  557. i32 y0 {};
  558. u32 width {};
  559. u32 height {};
  560. BlendingInfo blending_info {};
  561. FixedArray<BlendingInfo> ec_blending_info {};
  562. u32 duration {};
  563. bool is_last { true };
  564. u8 save_as_reference {};
  565. bool save_before_ct {};
  566. String name {};
  567. RestorationFilter restoration_filter {};
  568. Extensions extensions {};
  569. };
  570. static int operator&(FrameHeader::Flags first, FrameHeader::Flags second)
  571. {
  572. return static_cast<int>(first) & static_cast<int>(second);
  573. }
  574. static ErrorOr<FrameHeader> read_frame_header(LittleEndianInputBitStream& stream,
  575. SizeHeader size_header,
  576. ImageMetadata const& metadata)
  577. {
  578. FrameHeader frame_header;
  579. bool const all_default = TRY(stream.read_bit());
  580. if (!all_default) {
  581. frame_header.frame_type = static_cast<FrameHeader::FrameType>(TRY(stream.read_bits(2)));
  582. frame_header.encoding = static_cast<FrameHeader::Encoding>(TRY(stream.read_bits(1)));
  583. frame_header.flags = static_cast<FrameHeader::Flags>(TRY(U64(stream)));
  584. if (!metadata.xyb_encoded)
  585. frame_header.do_YCbCr = TRY(stream.read_bit());
  586. if (!(frame_header.flags & FrameHeader::Flags::kUseLfFrame)) {
  587. if (frame_header.do_YCbCr) {
  588. frame_header.jpeg_upsampling[0] = TRY(stream.read_bits(2));
  589. frame_header.jpeg_upsampling[1] = TRY(stream.read_bits(2));
  590. frame_header.jpeg_upsampling[2] = TRY(stream.read_bits(2));
  591. }
  592. frame_header.upsampling = U32(1, 2, 4, 8);
  593. frame_header.ec_upsampling = TRY(FixedArray<u8>::create(metadata.num_extra_channels));
  594. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  595. frame_header.ec_upsampling[i] = U32(1, 2, 4, 8);
  596. }
  597. if (frame_header.encoding == FrameHeader::Encoding::kModular)
  598. frame_header.group_size_shift = TRY(stream.read_bits(2));
  599. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  600. TODO();
  601. if (frame_header.frame_type != FrameHeader::FrameType::kReferenceOnly)
  602. frame_header.passes = TRY(read_passes(stream));
  603. if (frame_header.frame_type == FrameHeader::FrameType::kLFFrame)
  604. TODO();
  605. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame)
  606. frame_header.have_crop = TRY(stream.read_bit());
  607. if (frame_header.have_crop) {
  608. auto const read_crop_dimension = [&]() -> ErrorOr<u32> {
  609. return U32(TRY(stream.read_bits(8)), 256 + TRY(stream.read_bits(11)), 2304 + TRY(stream.read_bits(14)), 18688 + TRY(stream.read_bits(30)));
  610. };
  611. if (frame_header.frame_type != FrameHeader::FrameType::kReferenceOnly) {
  612. frame_header.x0 = unpack_signed(TRY(read_crop_dimension()));
  613. frame_header.y0 = unpack_signed(TRY(read_crop_dimension()));
  614. }
  615. frame_header.width = TRY(read_crop_dimension());
  616. frame_header.height = TRY(read_crop_dimension());
  617. }
  618. bool const normal_frame = frame_header.frame_type == FrameHeader::FrameType::kRegularFrame
  619. || frame_header.frame_type == FrameHeader::FrameType::kSkipProgressive;
  620. // Let full_frame be true if and only if have_crop is false or if the frame area given
  621. // by width and height and offsets x0 and y0 completely covers the image area.
  622. bool const cover_image_area = frame_header.x0 <= 0 && frame_header.y0 <= 0
  623. && (frame_header.width + frame_header.x0 >= size_header.width)
  624. && (frame_header.height + frame_header.y0 == size_header.height);
  625. bool const full_frame = !frame_header.have_crop || cover_image_area;
  626. if (normal_frame) {
  627. frame_header.blending_info = TRY(read_blending_info(stream, metadata, full_frame));
  628. frame_header.ec_blending_info = TRY(FixedArray<BlendingInfo>::create(metadata.num_extra_channels));
  629. for (u16 i {}; i < metadata.num_extra_channels; ++i)
  630. frame_header.ec_blending_info[i] = TRY(read_blending_info(stream, metadata, full_frame));
  631. if (metadata.animation.has_value())
  632. TODO();
  633. frame_header.is_last = TRY(stream.read_bit());
  634. }
  635. // FIXME: Ensure that is_last has the correct default value
  636. VERIFY(normal_frame);
  637. auto const resets_canvas = full_frame && frame_header.blending_info.mode == BlendingInfo::BlendMode::kReplace;
  638. 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;
  639. if (frame_header.frame_type != FrameHeader::FrameType::kLFFrame) {
  640. if (!frame_header.is_last)
  641. TODO();
  642. }
  643. frame_header.save_before_ct = !normal_frame;
  644. if (frame_header.frame_type == FrameHeader::FrameType::kReferenceOnly || (resets_canvas && can_reference))
  645. frame_header.save_before_ct = TRY(stream.read_bit());
  646. frame_header.name = TRY(read_string(stream));
  647. frame_header.restoration_filter = TRY(read_restoration_filter(stream));
  648. frame_header.extensions = TRY(read_extensions(stream));
  649. }
  650. return frame_header;
  651. }
  652. ///
  653. /// F.3 TOC
  654. struct TOC {
  655. FixedArray<u32> entries;
  656. FixedArray<u32> group_offsets;
  657. };
  658. static u64 num_toc_entries(FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  659. {
  660. // F.3.1 - General
  661. if (num_groups == 1 && frame_header.passes.num_passes == 1)
  662. return 1;
  663. return 1 + num_lf_groups + 1 + num_groups * frame_header.passes.num_passes;
  664. }
  665. static ErrorOr<TOC> read_toc(LittleEndianInputBitStream& stream, FrameHeader const& frame_header, u64 num_groups, u64 num_lf_groups)
  666. {
  667. TOC toc;
  668. bool const permuted_toc = TRY(stream.read_bit());
  669. if (permuted_toc) {
  670. // Read permutations
  671. TODO();
  672. }
  673. // F.3.3 - Decoding TOC
  674. stream.align_to_byte_boundary();
  675. auto const toc_entries = num_toc_entries(frame_header, num_groups, num_lf_groups);
  676. toc.entries = TRY(FixedArray<u32>::create(toc_entries));
  677. toc.group_offsets = TRY(FixedArray<u32>::create(toc_entries));
  678. for (u32 i {}; i < toc_entries; ++i) {
  679. auto const new_entry = U32(
  680. TRY(stream.read_bits(10)),
  681. 1024 + TRY(stream.read_bits(14)),
  682. 17408 + TRY(stream.read_bits(22)),
  683. 4211712 + TRY(stream.read_bits(30)));
  684. toc.entries[i] = new_entry;
  685. toc.group_offsets[i] = (i == 0 ? 0 : toc.group_offsets[i - 1]) + new_entry;
  686. }
  687. if (permuted_toc)
  688. TODO();
  689. stream.align_to_byte_boundary();
  690. return toc;
  691. }
  692. ///
  693. /// G.1.2 - LF channel dequantization weights
  694. struct LfChannelDequantization {
  695. float m_x_lf_unscaled { 4096 };
  696. float m_y_lf_unscaled { 512 };
  697. float m_b_lf_unscaled { 256 };
  698. };
  699. static ErrorOr<LfChannelDequantization> read_lf_channel_dequantization(LittleEndianInputBitStream& stream)
  700. {
  701. LfChannelDequantization lf_channel_dequantization;
  702. auto const all_default = TRY(stream.read_bit());
  703. if (!all_default) {
  704. TODO();
  705. }
  706. return lf_channel_dequantization;
  707. }
  708. ///
  709. /// C - Entropy decoding
  710. class ANSHistogram {
  711. public:
  712. static ErrorOr<ANSHistogram> read_histogram(LittleEndianInputBitStream& stream, u8 log_alphabet_size)
  713. {
  714. ANSHistogram histogram;
  715. auto const alphabet_size = TRY(histogram.read_ans_distribution(stream, log_alphabet_size));
  716. // C.2.6 - Alias mapping
  717. histogram.m_log_bucket_size = 12 - log_alphabet_size;
  718. histogram.m_bucket_size = 1 << histogram.m_log_bucket_size;
  719. auto const table_size = 1 << log_alphabet_size;
  720. Optional<u64> index_of_unique_symbol {};
  721. for (u64 i {}; i < histogram.m_distribution.size(); ++i) {
  722. if (histogram.m_distribution[i] == 1 << 12)
  723. index_of_unique_symbol = i;
  724. }
  725. TRY(histogram.m_symbols.try_resize(table_size));
  726. TRY(histogram.m_offsets.try_resize(table_size));
  727. TRY(histogram.m_cutoffs.try_resize(table_size));
  728. if (index_of_unique_symbol.has_value()) {
  729. auto const s = *index_of_unique_symbol;
  730. for (i32 i = 0; i < table_size; i++) {
  731. histogram.m_symbols[i] = s;
  732. histogram.m_offsets[i] = histogram.m_bucket_size * i;
  733. histogram.m_cutoffs[i] = 0;
  734. }
  735. return histogram;
  736. }
  737. Vector<u16> overfull;
  738. Vector<u16> underfull;
  739. for (u16 i {}; i < alphabet_size; i++) {
  740. histogram.m_cutoffs[i] = histogram.m_distribution[i];
  741. histogram.m_symbols[i] = i;
  742. if (histogram.m_cutoffs[i] > histogram.m_bucket_size)
  743. TRY(overfull.try_append(i));
  744. else if (histogram.m_cutoffs[i] < histogram.m_bucket_size)
  745. TRY(underfull.try_append(i));
  746. }
  747. for (u16 i = alphabet_size; i < table_size; i++) {
  748. histogram.m_cutoffs[i] = 0;
  749. TRY(underfull.try_append(i));
  750. }
  751. while (overfull.size() > 0) {
  752. VERIFY(underfull.size() > 0);
  753. auto const o = overfull.take_last();
  754. auto const u = underfull.take_last();
  755. auto const by = histogram.m_bucket_size - histogram.m_cutoffs[u];
  756. histogram.m_cutoffs[o] -= by;
  757. histogram.m_symbols[u] = o;
  758. histogram.m_offsets[u] = histogram.m_cutoffs[o];
  759. if (histogram.m_cutoffs[o] < histogram.m_bucket_size)
  760. TRY(underfull.try_append(o));
  761. else if (histogram.m_cutoffs[o] > histogram.m_bucket_size)
  762. TRY(overfull.try_append(o));
  763. }
  764. for (u16 i {}; i < table_size; i++) {
  765. if (histogram.m_cutoffs[i] == histogram.m_bucket_size) {
  766. histogram.m_symbols[i] = i;
  767. histogram.m_offsets[i] = 0;
  768. histogram.m_cutoffs[i] = 0;
  769. } else {
  770. histogram.m_offsets[i] -= histogram.m_cutoffs[i];
  771. }
  772. }
  773. return histogram;
  774. }
  775. ErrorOr<u16> read_symbol(LittleEndianInputBitStream& stream, Optional<u32>& state) const
  776. {
  777. if (!state.has_value())
  778. state = TRY(stream.read_bits(32));
  779. auto const index = *state & 0xFFF;
  780. auto const symbol_and_offset = alias_mapping(index);
  781. state = m_distribution[symbol_and_offset.symbol] * (*state >> 12) + symbol_and_offset.offset;
  782. if (*state < (1 << 16))
  783. state = (*state << 16) | TRY(stream.read_bits(16));
  784. return symbol_and_offset.symbol;
  785. }
  786. private:
  787. static ErrorOr<u8> U8(LittleEndianInputBitStream& stream)
  788. {
  789. if (TRY(stream.read_bit()) == 0)
  790. return 0;
  791. auto const n = TRY(stream.read_bits(3));
  792. return TRY(stream.read_bits(n)) + (1 << n);
  793. }
  794. struct SymbolAndOffset {
  795. u16 symbol {};
  796. u16 offset {};
  797. };
  798. SymbolAndOffset alias_mapping(u32 x) const
  799. {
  800. // C.2.6 - Alias mapping
  801. auto const i = x >> m_log_bucket_size;
  802. auto const pos = x & (m_bucket_size - 1);
  803. u16 const symbol = pos >= m_cutoffs[i] ? m_symbols[i] : i;
  804. u16 const offset = pos >= m_cutoffs[i] ? m_offsets[i] + pos : pos;
  805. return { symbol, offset };
  806. }
  807. static ErrorOr<u16> read_with_prefix(LittleEndianInputBitStream& stream)
  808. {
  809. auto const prefix = TRY(stream.read_bits(3));
  810. switch (prefix) {
  811. case 0:
  812. return 10;
  813. case 1:
  814. for (auto const possibility : { 4, 0, 11, 13 }) {
  815. if (TRY(stream.read_bit()))
  816. return possibility;
  817. }
  818. return 12;
  819. case 2:
  820. return 7;
  821. case 3:
  822. return TRY(stream.read_bit()) ? 1 : 3;
  823. case 4:
  824. return 6;
  825. case 5:
  826. return 8;
  827. case 6:
  828. return 9;
  829. case 7:
  830. return TRY(stream.read_bit()) ? 2 : 5;
  831. default:
  832. VERIFY_NOT_REACHED();
  833. }
  834. }
  835. ErrorOr<u16> read_ans_distribution(LittleEndianInputBitStream& stream, u8 log_alphabet_size)
  836. {
  837. // C.2.5 ANS distribution decoding
  838. auto const table_size = 1 << log_alphabet_size;
  839. m_distribution = TRY(FixedArray<i32>::create(table_size));
  840. if (TRY(stream.read_bit())) {
  841. u16 alphabet_size {};
  842. if (TRY(stream.read_bit())) {
  843. auto const v1 = TRY(U8(stream));
  844. auto const v2 = TRY(U8(stream));
  845. VERIFY(v1 != v2);
  846. m_distribution[v1] = TRY(stream.read_bits(12));
  847. m_distribution[v2] = (1 << 12) - m_distribution[v1];
  848. alphabet_size = 1 + max(v1, v2);
  849. } else {
  850. auto const x = TRY(U8(stream));
  851. m_distribution[x] = 1 << 12;
  852. alphabet_size = 1 + x;
  853. }
  854. return alphabet_size;
  855. }
  856. if (TRY(stream.read_bit())) {
  857. auto const alphabet_size = TRY(U8(stream)) + 1;
  858. for (u16 i = 0; i < alphabet_size; i++)
  859. m_distribution[i] = (1 << 12) / alphabet_size;
  860. for (u16 i = 0; i < ((1 << 12) % alphabet_size); i++)
  861. m_distribution[i]++;
  862. return alphabet_size;
  863. }
  864. u8 len = 0;
  865. while (len < 3) {
  866. if (TRY(stream.read_bit()))
  867. len++;
  868. else
  869. break;
  870. }
  871. u8 const shift = TRY(stream.read_bits(len)) + (1 << len) - 1;
  872. VERIFY(shift <= 13);
  873. auto const alphabet_size = TRY(U8(stream)) + 3;
  874. i32 omit_log = -1;
  875. i32 omit_pos = -1;
  876. auto same = TRY(FixedArray<i32>::create(alphabet_size));
  877. auto logcounts = TRY(FixedArray<i32>::create(alphabet_size));
  878. u8 rle {};
  879. for (u16 i = 0; i < alphabet_size; i++) {
  880. logcounts[i] = TRY(read_with_prefix(stream));
  881. if (logcounts[i] == 13) {
  882. rle = TRY(U8(stream));
  883. same[i] = rle + 5;
  884. i += rle + 3;
  885. continue;
  886. }
  887. if (logcounts[i] > omit_log) {
  888. omit_log = logcounts[i];
  889. omit_pos = i;
  890. }
  891. }
  892. VERIFY(m_distribution[omit_pos] >= 0);
  893. VERIFY(omit_pos + 1 >= alphabet_size || logcounts[omit_pos + 1] != 13);
  894. i32 prev = 0;
  895. i32 numsame = 0;
  896. i64 total_count {};
  897. for (u16 i = 0; i < alphabet_size; i++) {
  898. if (same[i] != 0) {
  899. numsame = same[i] - 1;
  900. prev = i > 0 ? m_distribution[i - 1] : 0;
  901. }
  902. if (numsame > 0) {
  903. m_distribution[i] = prev;
  904. numsame--;
  905. } else {
  906. auto const code = logcounts[i];
  907. if (i == omit_pos || code == 0)
  908. continue;
  909. if (code == 1) {
  910. m_distribution[i] = 1;
  911. } else {
  912. auto const bitcount = min(max(0, shift - ((12 - code + 1) >> 1)), code - 1);
  913. m_distribution[i] = (1 << (code - 1)) + (TRY(stream.read_bits(bitcount)) << (code - 1 - bitcount));
  914. }
  915. }
  916. total_count += m_distribution[i];
  917. }
  918. m_distribution[omit_pos] = (1 << 12) - total_count;
  919. VERIFY(m_distribution[omit_pos] >= 0);
  920. return alphabet_size;
  921. }
  922. Vector<u16> m_symbols;
  923. Vector<u16> m_offsets;
  924. Vector<u16> m_cutoffs;
  925. FixedArray<i32> m_distribution;
  926. u16 m_log_bucket_size {};
  927. u16 m_bucket_size {};
  928. };
  929. struct LZ77 {
  930. bool lz77_enabled {};
  931. u32 min_symbol {};
  932. u32 min_length {};
  933. };
  934. static ErrorOr<LZ77> read_lz77(LittleEndianInputBitStream& stream)
  935. {
  936. LZ77 lz77;
  937. lz77.lz77_enabled = TRY(stream.read_bit());
  938. if (lz77.lz77_enabled) {
  939. lz77.min_symbol = U32(224, 512, 4096, 8 + TRY(stream.read_bits(15)));
  940. lz77.min_length = U32(3, 4, 5 + TRY(stream.read_bits(2)), 9 + TRY(stream.read_bits(8)));
  941. }
  942. return lz77;
  943. }
  944. class EntropyDecoder {
  945. AK_MAKE_NONCOPYABLE(EntropyDecoder);
  946. AK_MAKE_DEFAULT_MOVABLE(EntropyDecoder);
  947. public:
  948. EntropyDecoder() = default;
  949. ~EntropyDecoder()
  950. {
  951. if (m_state.has_value() && *m_state != 0x130000)
  952. dbgln("JPEGXLLoader: ANS decoder left in invalid state");
  953. }
  954. static ErrorOr<EntropyDecoder> create(LittleEndianInputBitStream& stream, u32 initial_num_distrib)
  955. {
  956. EntropyDecoder entropy_decoder;
  957. // C.2 - Distribution decoding
  958. entropy_decoder.m_lz77 = TRY(read_lz77(stream));
  959. if (entropy_decoder.m_lz77.lz77_enabled) {
  960. entropy_decoder.m_lz_dist_ctx = initial_num_distrib++;
  961. entropy_decoder.m_lz_len_conf = TRY(read_config(stream, 8));
  962. entropy_decoder.m_lz77_window = TRY(FixedArray<u32>::create(1 << 20));
  963. }
  964. TRY(entropy_decoder.read_pre_clustered_distributions(stream, initial_num_distrib));
  965. bool const use_prefix_code = TRY(stream.read_bit());
  966. if (!use_prefix_code)
  967. entropy_decoder.m_log_alphabet_size = 5 + TRY(stream.read_bits(2));
  968. for (auto& config : entropy_decoder.m_configs)
  969. config = TRY(read_config(stream, entropy_decoder.m_log_alphabet_size));
  970. if (use_prefix_code) {
  971. entropy_decoder.m_distributions = Vector<BrotliCanonicalCode> {};
  972. auto& distributions = entropy_decoder.m_distributions.get<Vector<BrotliCanonicalCode>>();
  973. TRY(distributions.try_resize(entropy_decoder.m_configs.size()));
  974. Vector<u16> counts;
  975. TRY(counts.try_resize(entropy_decoder.m_configs.size()));
  976. for (auto& count : counts) {
  977. if (TRY(stream.read_bit())) {
  978. auto const n = TRY(stream.read_bits(4));
  979. count = 1 + (1 << n) + TRY(stream.read_bits(n));
  980. } else {
  981. count = 1;
  982. }
  983. }
  984. // After reading the counts, the decoder reads each D[i] (implicitly
  985. // described by a prefix code) as specified in C.2.4, with alphabet_size = count[i].
  986. for (u32 i {}; i < distributions.size(); ++i) {
  987. // The alphabet size mentioned in the [Brotli] RFC is explicitly specified as parameter alphabet_size
  988. // when the histogram is being decoded, except in the special case of alphabet_size == 1, where no
  989. // histogram is read, and all decoded symbols are zero without reading any bits at all.
  990. if (counts[i] != 1)
  991. distributions[i] = TRY(BrotliCanonicalCode::read_prefix_code(stream, counts[i]));
  992. else
  993. distributions[i] = BrotliCanonicalCode { { 1 }, { 0 } };
  994. }
  995. } else {
  996. entropy_decoder.m_distributions = Vector<ANSHistogram> {};
  997. auto& distributions = entropy_decoder.m_distributions.get<Vector<ANSHistogram>>();
  998. TRY(distributions.try_ensure_capacity(entropy_decoder.m_configs.size()));
  999. for (u32 i = 0; i < entropy_decoder.m_configs.size(); ++i)
  1000. distributions.empend(TRY(ANSHistogram::read_histogram(stream, entropy_decoder.m_log_alphabet_size)));
  1001. }
  1002. return entropy_decoder;
  1003. }
  1004. ErrorOr<u32> decode_hybrid_uint(LittleEndianInputBitStream& stream, u32 context)
  1005. {
  1006. // C.3.3 - Hybrid integer decoding
  1007. static constexpr Array<Array<i8, 2>, 120> kSpecialDistances = {
  1008. Array<i8, 2> { 0, 1 }, { 1, 0 }, { 1, 1 }, { -1, 1 }, { 0, 2 }, { 2, 0 }, { 1, 2 }, { -1, 2 }, { 2, 1 }, { -2, 1 }, { 2, 2 },
  1009. { -2, 2 }, { 0, 3 }, { 3, 0 }, { 1, 3 }, { -1, 3 }, { 3, 1 }, { -3, 1 }, { 2, 3 }, { -2, 3 }, { 3, 2 },
  1010. { -3, 2 }, { 0, 4 }, { 4, 0 }, { 1, 4 }, { -1, 4 }, { 4, 1 }, { -4, 1 }, { 3, 3 }, { -3, 3 }, { 2, 4 },
  1011. { -2, 4 }, { 4, 2 }, { -4, 2 }, { 0, 5 }, { 3, 4 }, { -3, 4 }, { 4, 3 }, { -4, 3 }, { 5, 0 }, { 1, 5 },
  1012. { -1, 5 }, { 5, 1 }, { -5, 1 }, { 2, 5 }, { -2, 5 }, { 5, 2 }, { -5, 2 }, { 4, 4 }, { -4, 4 }, { 3, 5 },
  1013. { -3, 5 }, { 5, 3 }, { -5, 3 }, { 0, 6 }, { 6, 0 }, { 1, 6 }, { -1, 6 }, { 6, 1 }, { -6, 1 }, { 2, 6 },
  1014. { -2, 6 }, { 6, 2 }, { -6, 2 }, { 4, 5 }, { -4, 5 }, { 5, 4 }, { -5, 4 }, { 3, 6 }, { -3, 6 }, { 6, 3 },
  1015. { -6, 3 }, { 0, 7 }, { 7, 0 }, { 1, 7 }, { -1, 7 }, { 5, 5 }, { -5, 5 }, { 7, 1 }, { -7, 1 }, { 4, 6 },
  1016. { -4, 6 }, { 6, 4 }, { -6, 4 }, { 2, 7 }, { -2, 7 }, { 7, 2 }, { -7, 2 }, { 3, 7 }, { -3, 7 }, { 7, 3 },
  1017. { -7, 3 }, { 5, 6 }, { -5, 6 }, { 6, 5 }, { -6, 5 }, { 8, 0 }, { 4, 7 }, { -4, 7 }, { 7, 4 }, { -7, 4 },
  1018. { 8, 1 }, { 8, 2 }, { 6, 6 }, { -6, 6 }, { 8, 3 }, { 5, 7 }, { -5, 7 }, { 7, 5 }, { -7, 5 }, { 8, 4 }, { 6, 7 },
  1019. { -6, 7 }, { 7, 6 }, { -7, 6 }, { 8, 5 }, { 7, 7 }, { -7, 7 }, { 8, 6 }, { 8, 7 }
  1020. };
  1021. u32 r {};
  1022. if (m_lz77_num_to_copy > 0) {
  1023. r = m_lz77_window[(m_lz77_copy_pos++) & 0xFFFFF];
  1024. m_lz77_num_to_copy--;
  1025. } else {
  1026. // Read symbol from entropy coded stream using D[clusters[ctx]]
  1027. auto token = TRY(read_symbol(stream, context));
  1028. if (m_lz77.lz77_enabled && token >= m_lz77.min_symbol) {
  1029. m_lz77_num_to_copy = TRY(read_uint(stream, m_lz_len_conf, token - m_lz77.min_symbol)) + m_lz77.min_length;
  1030. // Read symbol using D[clusters[lz_dist_ctx]]
  1031. token = TRY(read_symbol(stream, m_lz_dist_ctx));
  1032. auto distance = TRY(read_uint(stream, m_configs[m_clusters[m_lz_dist_ctx]], token));
  1033. if (m_dist_multiplier == 0) {
  1034. distance++;
  1035. } else if (distance < 120) {
  1036. auto const offset = kSpecialDistances[distance][0];
  1037. distance = offset + m_dist_multiplier * kSpecialDistances[distance][1];
  1038. if (distance < 1)
  1039. distance = 1;
  1040. } else {
  1041. distance -= 119;
  1042. }
  1043. distance = min(distance, min(m_lz77_num_decoded, 1 << 20));
  1044. m_lz77_copy_pos = m_lz77_num_decoded - distance;
  1045. return decode_hybrid_uint(stream, m_clusters[context]);
  1046. }
  1047. r = TRY(read_uint(stream, m_configs[m_clusters[context]], token));
  1048. }
  1049. if (m_lz77.lz77_enabled)
  1050. m_lz77_window[(m_lz77_num_decoded++) & 0xFFFFF] = r;
  1051. return r;
  1052. }
  1053. void set_dist_multiplier(u32 dist_multiplier)
  1054. {
  1055. m_dist_multiplier = dist_multiplier;
  1056. }
  1057. private:
  1058. using BrotliCanonicalCode = Compress::Brotli::CanonicalCode;
  1059. struct HybridUint {
  1060. u32 split_exponent {};
  1061. u32 split {};
  1062. u32 msb_in_token {};
  1063. u32 lsb_in_token {};
  1064. };
  1065. static ErrorOr<u32> read_uint(LittleEndianInputBitStream& stream, HybridUint const& config, u32 token)
  1066. {
  1067. if (token < config.split)
  1068. return token;
  1069. auto const n = config.split_exponent
  1070. - config.msb_in_token
  1071. - config.lsb_in_token
  1072. + ((token - config.split) >> (config.msb_in_token + config.lsb_in_token));
  1073. VERIFY(n < 32);
  1074. u32 const low_bits = token & ((1 << config.lsb_in_token) - 1);
  1075. token = token >> config.lsb_in_token;
  1076. token &= (1 << config.msb_in_token) - 1;
  1077. token |= (1 << config.msb_in_token);
  1078. auto const result = ((token << n | TRY(stream.read_bits(n))) << config.lsb_in_token) | low_bits;
  1079. VERIFY(result < (1ull << 32));
  1080. return result;
  1081. }
  1082. static ErrorOr<HybridUint> read_config(LittleEndianInputBitStream& stream, u8 log_alphabet_size)
  1083. {
  1084. // C.2.3 - Hybrid integer configuration
  1085. HybridUint config {};
  1086. config.split_exponent = TRY(stream.read_bits(ceil(log2(log_alphabet_size + 1))));
  1087. if (config.split_exponent != log_alphabet_size) {
  1088. auto nbits = ceil(log2(config.split_exponent + 1));
  1089. config.msb_in_token = TRY(stream.read_bits(nbits));
  1090. nbits = ceil(log2(config.split_exponent - config.msb_in_token + 1));
  1091. config.lsb_in_token = TRY(stream.read_bits(nbits));
  1092. } else {
  1093. config.msb_in_token = 0;
  1094. config.lsb_in_token = 0;
  1095. }
  1096. config.split = 1 << config.split_exponent;
  1097. return config;
  1098. }
  1099. ErrorOr<u32> read_symbol(LittleEndianInputBitStream& stream, u32 context)
  1100. {
  1101. u32 token {};
  1102. TRY(m_distributions.visit(
  1103. [&](Vector<BrotliCanonicalCode> const& distributions) -> ErrorOr<void> {
  1104. token = TRY(distributions[m_clusters[context]].read_symbol(stream));
  1105. return {};
  1106. },
  1107. [&](Vector<ANSHistogram> const& distributions) -> ErrorOr<void> {
  1108. token = TRY(distributions[m_clusters[context]].read_symbol(stream, m_state));
  1109. return {};
  1110. }));
  1111. return token;
  1112. }
  1113. ErrorOr<void> read_pre_clustered_distributions(LittleEndianInputBitStream& stream, u32 num_distrib)
  1114. {
  1115. // C.2.2 Distribution clustering
  1116. if (num_distrib == 1) {
  1117. // If num_dist == 1, then num_clusters = 1 and clusters[0] = 0, and the remainder of this subclause is skipped.
  1118. m_clusters = { 0 };
  1119. TRY(m_configs.try_resize(1));
  1120. return {};
  1121. };
  1122. TRY(m_clusters.try_resize(num_distrib));
  1123. bool const is_simple = TRY(stream.read_bit());
  1124. u16 num_clusters = 0;
  1125. auto const read_clusters = [&](auto&& reader) -> ErrorOr<void> {
  1126. for (u32 i {}; i < num_distrib; ++i) {
  1127. m_clusters[i] = TRY(reader());
  1128. if (m_clusters[i] >= num_clusters)
  1129. num_clusters = m_clusters[i] + 1;
  1130. }
  1131. return {};
  1132. };
  1133. if (is_simple) {
  1134. u8 const nbits = TRY(stream.read_bits(2));
  1135. TRY(read_clusters([nbits, &stream]() { return stream.read_bits(nbits); }));
  1136. } else {
  1137. auto const use_mtf = TRY(stream.read_bit());
  1138. if (num_distrib == 2)
  1139. TODO();
  1140. auto decoder = TRY(EntropyDecoder::create(stream, 1));
  1141. TRY(read_clusters([&]() { return decoder.decode_hybrid_uint(stream, 0); }));
  1142. if (use_mtf)
  1143. TODO();
  1144. }
  1145. TRY(m_configs.try_resize(num_clusters));
  1146. return {};
  1147. }
  1148. LZ77 m_lz77 {};
  1149. u32 m_lz_dist_ctx {};
  1150. HybridUint m_lz_len_conf {};
  1151. FixedArray<u32> m_lz77_window {};
  1152. u32 m_lz77_num_to_copy {};
  1153. u32 m_lz77_copy_pos {};
  1154. u32 m_lz77_num_decoded {};
  1155. u32 m_dist_multiplier {};
  1156. Vector<u32> m_clusters;
  1157. Vector<HybridUint> m_configs;
  1158. u8 m_log_alphabet_size { 15 };
  1159. Variant<Vector<BrotliCanonicalCode>, Vector<ANSHistogram>> m_distributions { Vector<BrotliCanonicalCode> {} }; // D in the spec
  1160. Optional<u32> m_state {};
  1161. };
  1162. ///
  1163. /// H.4.2 - MA tree decoding
  1164. class MATree {
  1165. public:
  1166. struct LeafNode {
  1167. u32 ctx {};
  1168. u8 predictor {};
  1169. i32 offset {};
  1170. u32 multiplier {};
  1171. };
  1172. static ErrorOr<MATree> decode(LittleEndianInputBitStream& stream, Optional<EntropyDecoder>& decoder)
  1173. {
  1174. // G.1.3 - GlobalModular
  1175. MATree tree;
  1176. // 1 / 2 Read the 6 pre-clustered distributions
  1177. auto const num_distrib = 6;
  1178. if (!decoder.has_value())
  1179. decoder = TRY(EntropyDecoder::create(stream, num_distrib));
  1180. // 2 / 2 Decode the tree
  1181. u64 ctx_id = 0;
  1182. u64 nodes_left = 1;
  1183. tree.m_tree.clear();
  1184. while (nodes_left > 0) {
  1185. nodes_left--;
  1186. i32 const property = TRY(decoder->decode_hybrid_uint(stream, 1)) - 1;
  1187. if (property >= 0) {
  1188. DecisionNode decision_node;
  1189. decision_node.property = property;
  1190. decision_node.value = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 0)));
  1191. decision_node.left_child = tree.m_tree.size() + nodes_left + 1;
  1192. decision_node.right_child = tree.m_tree.size() + nodes_left + 2;
  1193. tree.m_tree.empend(decision_node);
  1194. nodes_left += 2;
  1195. } else {
  1196. LeafNode leaf_node;
  1197. leaf_node.ctx = ctx_id++;
  1198. leaf_node.predictor = TRY(decoder->decode_hybrid_uint(stream, 2));
  1199. leaf_node.offset = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, 3)));
  1200. auto const mul_log = TRY(decoder->decode_hybrid_uint(stream, 4));
  1201. auto const mul_bits = TRY(decoder->decode_hybrid_uint(stream, 5));
  1202. leaf_node.multiplier = (mul_bits + 1) << mul_log;
  1203. tree.m_tree.empend(leaf_node);
  1204. }
  1205. }
  1206. // Finally, the decoder reads (tree.size() + 1) / 2 pre-clustered distributions D as specified in C.1.
  1207. auto const num_pre_clustered_distributions = (tree.m_tree.size() + 1) / 2;
  1208. decoder = TRY(decoder->create(stream, num_pre_clustered_distributions));
  1209. return tree;
  1210. }
  1211. LeafNode get_leaf(Vector<i32> const& properties) const
  1212. {
  1213. // To find the MA leaf node, the MA tree is traversed, starting at the root node tree[0]
  1214. // and for each decision node d, testing if property[d.property] > d.value, proceeding to
  1215. // the node tree[d.left_child] if the test evaluates to true and to the node tree[d.right_child]
  1216. // otherwise, until a leaf node is reached.
  1217. DecisionNode node { m_tree[0].get<DecisionNode>() };
  1218. while (true) {
  1219. auto const next_node = [this, &properties, &node]() {
  1220. // Note: The behavior when trying to access a non-existing property is taken from jxl-oxide
  1221. if (node.property < properties.size() && properties[node.property] > node.value)
  1222. return m_tree[node.left_child];
  1223. return m_tree[node.right_child];
  1224. }();
  1225. if (next_node.has<LeafNode>())
  1226. return next_node.get<LeafNode>();
  1227. node = next_node.get<DecisionNode>();
  1228. }
  1229. }
  1230. private:
  1231. struct DecisionNode {
  1232. u64 property {};
  1233. i64 value {};
  1234. u64 left_child {};
  1235. u64 right_child {};
  1236. };
  1237. Vector<Variant<DecisionNode, LeafNode>> m_tree;
  1238. };
  1239. ///
  1240. /// H.5 - Self-correcting predictor
  1241. struct WPHeader {
  1242. u8 wp_p1 { 16 };
  1243. u8 wp_p2 { 10 };
  1244. u8 wp_p3a { 7 };
  1245. u8 wp_p3b { 7 };
  1246. u8 wp_p3c { 7 };
  1247. u8 wp_p3d { 0 };
  1248. u8 wp_p3e { 0 };
  1249. Array<u8, 4> wp_w { 13, 12, 12, 12 };
  1250. };
  1251. static ErrorOr<WPHeader> read_self_correcting_predictor(LittleEndianInputBitStream& stream)
  1252. {
  1253. WPHeader self_correcting_predictor {};
  1254. bool const default_wp = TRY(stream.read_bit());
  1255. if (!default_wp) {
  1256. TODO();
  1257. }
  1258. return self_correcting_predictor;
  1259. }
  1260. ///
  1261. ///
  1262. struct TransformInfo {
  1263. enum class TransformId {
  1264. kRCT = 0,
  1265. kPalette = 1,
  1266. kSqueeze = 2,
  1267. };
  1268. TransformId tr {};
  1269. u32 begin_c {};
  1270. u32 rct_type {};
  1271. };
  1272. static ErrorOr<TransformInfo> read_transform_info(LittleEndianInputBitStream& stream)
  1273. {
  1274. TransformInfo transform_info;
  1275. transform_info.tr = static_cast<TransformInfo::TransformId>(TRY(stream.read_bits(2)));
  1276. if (transform_info.tr != TransformInfo::TransformId::kSqueeze) {
  1277. transform_info.begin_c = U32(
  1278. TRY(stream.read_bits(3)),
  1279. 8 + TRY(stream.read_bits(3)),
  1280. 72 + TRY(stream.read_bits(10)),
  1281. 1096 + TRY(stream.read_bits(13)));
  1282. }
  1283. if (transform_info.tr == TransformInfo::TransformId::kRCT) {
  1284. transform_info.rct_type = U32(
  1285. 6,
  1286. TRY(stream.read_bits(2)),
  1287. 2 + TRY(stream.read_bits(4)),
  1288. 10 + TRY(stream.read_bits(6)));
  1289. }
  1290. if (transform_info.tr != TransformInfo::TransformId::kRCT)
  1291. TODO();
  1292. return transform_info;
  1293. }
  1294. ///
  1295. /// Local abstractions to store the decoded image
  1296. class Channel {
  1297. public:
  1298. static ErrorOr<Channel> create(u32 width, u32 height)
  1299. {
  1300. Channel channel;
  1301. channel.m_width = width;
  1302. channel.m_height = height;
  1303. TRY(channel.m_pixels.try_resize(channel.m_width * channel.m_height));
  1304. return channel;
  1305. }
  1306. i32 get(u32 x, u32 y) const
  1307. {
  1308. return m_pixels[y * m_width + x];
  1309. }
  1310. void set(u32 x, u32 y, i32 value)
  1311. {
  1312. m_pixels[y * m_width + x] = value;
  1313. }
  1314. u32 width() const
  1315. {
  1316. return m_width;
  1317. }
  1318. u32 height() const
  1319. {
  1320. return m_height;
  1321. }
  1322. u32 hshift() const
  1323. {
  1324. return m_hshift;
  1325. }
  1326. u32 vshift() const
  1327. {
  1328. return m_vshift;
  1329. }
  1330. bool decoded() const
  1331. {
  1332. return m_decoded;
  1333. }
  1334. void set_decoded(bool decoded)
  1335. {
  1336. m_decoded = decoded;
  1337. }
  1338. private:
  1339. u32 m_width {};
  1340. u32 m_height {};
  1341. u32 m_hshift {};
  1342. u32 m_vshift {};
  1343. bool m_decoded { false };
  1344. Vector<i32> m_pixels {};
  1345. };
  1346. class Image {
  1347. public:
  1348. static ErrorOr<Image> create(IntSize size, ImageMetadata const& metadata)
  1349. {
  1350. Image image {};
  1351. for (u16 i = 0; i < metadata.number_of_channels(); ++i) {
  1352. if (i < metadata.number_of_color_channels()) {
  1353. TRY(image.m_channels.try_append(TRY(Channel::create(size.width(), size.height()))));
  1354. } else {
  1355. auto const dim_shift = metadata.ec_info[i - metadata.number_of_color_channels()].dim_shift;
  1356. TRY(image.m_channels.try_append(TRY(Channel::create(size.width() >> dim_shift, size.height() >> dim_shift))));
  1357. }
  1358. }
  1359. return image;
  1360. }
  1361. void blend_into(Image& image, FrameHeader const& frame_header) const
  1362. {
  1363. // FIXME: We should use ec_blending_info when appropriate
  1364. if (frame_header.blending_info.mode != BlendingInfo::BlendMode::kReplace)
  1365. TODO();
  1366. for (u16 i = 0; i < m_channels.size(); ++i) {
  1367. auto const& input_channel = m_channels[i];
  1368. auto& output_channel = image.channels()[i];
  1369. for (u32 y = 0; y < input_channel.height(); ++y) {
  1370. auto const corrected_y = static_cast<i64>(y) + frame_header.y0;
  1371. if (corrected_y < 0)
  1372. continue;
  1373. if (corrected_y >= output_channel.height())
  1374. break;
  1375. for (u32 x = 0; x < input_channel.width(); ++x) {
  1376. auto const corrected_x = static_cast<i64>(x) + frame_header.x0;
  1377. if (corrected_x < 0)
  1378. continue;
  1379. if (corrected_x >= output_channel.width())
  1380. break;
  1381. output_channel.set(corrected_x, corrected_y, input_channel.get(x, y));
  1382. }
  1383. }
  1384. };
  1385. }
  1386. ErrorOr<NonnullRefPtr<Bitmap>> to_bitmap(ImageMetadata& metadata) const
  1387. {
  1388. // FIXME: which channel size should we use?
  1389. auto const width = m_channels[0].width();
  1390. auto const height = m_channels[0].height();
  1391. auto const orientation = static_cast<TIFF::Orientation>(metadata.orientation);
  1392. auto oriented_bitmap = TRY(ExifOrientedBitmap::create(orientation, { width, height }, BitmapFormat::BGRA8888));
  1393. auto const alpha_channel = metadata.alpha_channel();
  1394. auto const bits_per_sample = metadata.bit_depth.bits_per_sample;
  1395. VERIFY(bits_per_sample >= 8);
  1396. for (u32 y {}; y < height; ++y) {
  1397. for (u32 x {}; x < width; ++x) {
  1398. auto const to_u8 = [&, bits_per_sample](i32 sample) -> u8 {
  1399. // FIXME: Don't truncate the result to 8 bits
  1400. static constexpr auto maximum_supported_bit_depth = 8;
  1401. if (bits_per_sample > maximum_supported_bit_depth)
  1402. sample >>= (bits_per_sample - maximum_supported_bit_depth);
  1403. return clamp(sample + .5, 0, (1 << maximum_supported_bit_depth) - 1);
  1404. };
  1405. auto const color = [&]() -> Color {
  1406. if (!alpha_channel.has_value()) {
  1407. return { to_u8(m_channels[0].get(x, y)),
  1408. to_u8(m_channels[1].get(x, y)),
  1409. to_u8(m_channels[2].get(x, y)) };
  1410. }
  1411. return {
  1412. to_u8(m_channels[0].get(x, y)),
  1413. to_u8(m_channels[1].get(x, y)),
  1414. to_u8(m_channels[2].get(x, y)),
  1415. to_u8(m_channels[*alpha_channel].get(x, y)),
  1416. };
  1417. }();
  1418. oriented_bitmap.set_pixel(x, y, color.value());
  1419. }
  1420. }
  1421. return oriented_bitmap.bitmap();
  1422. }
  1423. Vector<Channel>& channels()
  1424. {
  1425. return m_channels;
  1426. }
  1427. private:
  1428. Vector<Channel> m_channels;
  1429. };
  1430. ///
  1431. /// H.5 - Self-correcting predictor
  1432. struct Neighborhood {
  1433. i32 N {};
  1434. i32 NW {};
  1435. i32 NE {};
  1436. i32 W {};
  1437. i32 NN {};
  1438. i32 WW {};
  1439. i32 NEE {};
  1440. };
  1441. class SelfCorrectingData {
  1442. public:
  1443. struct Predictions {
  1444. i32 prediction {};
  1445. Array<i32, 4> subpred {};
  1446. i32 max_error {};
  1447. i32 true_err {};
  1448. Array<i32, 4> err {};
  1449. };
  1450. static ErrorOr<SelfCorrectingData> create(WPHeader const& wp_params, u32 width)
  1451. {
  1452. SelfCorrectingData self_correcting_data { wp_params };
  1453. self_correcting_data.m_width = width;
  1454. self_correcting_data.m_previous = TRY(FixedArray<Predictions>::create(width));
  1455. self_correcting_data.m_current_row = TRY(FixedArray<Predictions>::create(width));
  1456. self_correcting_data.m_next_row = TRY(FixedArray<Predictions>::create(width));
  1457. return self_correcting_data;
  1458. }
  1459. void register_next_row()
  1460. {
  1461. auto tmp = move(m_previous);
  1462. m_previous = move(m_current_row);
  1463. m_current_row = move(m_next_row);
  1464. // We reuse m_previous to avoid an allocation, no values are kept
  1465. // everything will be overridden.
  1466. m_next_row = move(tmp);
  1467. m_current_row_index++;
  1468. }
  1469. Predictions compute_predictions(Neighborhood const& neighborhood, u32 x)
  1470. {
  1471. auto& current_predictions = m_next_row[x];
  1472. auto const N3 = neighborhood.N << 3;
  1473. auto const NW3 = neighborhood.NW << 3;
  1474. auto const NE3 = neighborhood.NE << 3;
  1475. auto const W3 = neighborhood.W << 3;
  1476. auto const NN3 = neighborhood.NN << 3;
  1477. auto const predictions_W = predictions_for(x, Direction::West);
  1478. auto const predictions_N = predictions_for(x, Direction::North);
  1479. auto const predictions_NE = predictions_for(x, Direction::NorthEast);
  1480. auto const predictions_NW = predictions_for(x, Direction::NorthWest);
  1481. auto const predictions_WW = predictions_for(x, Direction::WestWest);
  1482. current_predictions.subpred[0] = W3 + NE3 - N3;
  1483. current_predictions.subpred[1] = N3 - (((predictions_W.true_err + predictions_N.true_err + predictions_NE.true_err) * wp_params.wp_p1) >> 5);
  1484. current_predictions.subpred[2] = W3 - (((predictions_W.true_err + predictions_N.true_err + predictions_NW.true_err) * wp_params.wp_p2) >> 5);
  1485. 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);
  1486. auto const error2weight = [](i32 err_sum, u8 maxweight) -> i32 {
  1487. i32 shift = floor(log2(err_sum + 1)) - 5;
  1488. if (shift < 0)
  1489. shift = 0;
  1490. return 4 + ((static_cast<u64>(maxweight) * ((1 << 24) / ((err_sum >> shift) + 1))) >> shift);
  1491. };
  1492. Array<i32, 4> weight {};
  1493. for (u8 i = 0; i < weight.size(); ++i) {
  1494. auto err_sum = predictions_N.err[i] + predictions_W.err[i] + predictions_NW.err[i] + predictions_WW.err[i] + predictions_NE.err[i];
  1495. if (x == m_width - 1)
  1496. err_sum += predictions_W.err[i];
  1497. weight[i] = error2weight(err_sum, wp_params.wp_w[i]);
  1498. }
  1499. auto sum_weights = weight[0] + weight[1] + weight[2] + weight[3];
  1500. i32 const log_weight = floor(log2(sum_weights)) + 1;
  1501. for (u8 i = 0; i < 4; i++)
  1502. weight[i] = weight[i] >> (log_weight - 5);
  1503. sum_weights = weight[0] + weight[1] + weight[2] + weight[3];
  1504. auto s = (sum_weights >> 1) - 1;
  1505. for (u8 i = 0; i < 4; i++)
  1506. s += current_predictions.subpred[i] * weight[i];
  1507. current_predictions.prediction = static_cast<u64>(s) * ((1 << 24) / sum_weights) >> 24;
  1508. // if true_err_N, true_err_W and true_err_NW don't have the same sign
  1509. if (((predictions_N.true_err ^ predictions_W.true_err) | (predictions_N.true_err ^ predictions_NW.true_err)) <= 0) {
  1510. current_predictions.prediction = clamp(current_predictions.prediction, min(W3, min(N3, NE3)), max(W3, max(N3, NE3)));
  1511. }
  1512. auto& max_error = current_predictions.max_error;
  1513. max_error = predictions_W.true_err;
  1514. if (abs(predictions_N.true_err) > abs(max_error))
  1515. max_error = predictions_N.true_err;
  1516. if (abs(predictions_NW.true_err) > abs(max_error))
  1517. max_error = predictions_NW.true_err;
  1518. if (abs(predictions_NE.true_err) > abs(max_error))
  1519. max_error = predictions_NE.true_err;
  1520. return current_predictions;
  1521. }
  1522. // H.5.1 - General
  1523. void compute_errors(u32 x, i32 true_value)
  1524. {
  1525. auto& current_predictions = m_next_row[x];
  1526. current_predictions.true_err = current_predictions.prediction - (true_value << 3);
  1527. for (u8 i = 0; i < 4; ++i)
  1528. current_predictions.err[i] = (abs(current_predictions.subpred[i] - (true_value << 3)) + 3) >> 3;
  1529. }
  1530. private:
  1531. SelfCorrectingData(WPHeader const& wp)
  1532. : wp_params(wp)
  1533. {
  1534. }
  1535. enum class Direction {
  1536. North,
  1537. NorthWest,
  1538. NorthEast,
  1539. West,
  1540. NorthNorth,
  1541. WestWest
  1542. };
  1543. Predictions predictions_for(u32 x, Direction direction) const
  1544. {
  1545. // H.5.2 - Prediction
  1546. auto const north = [&]() {
  1547. return m_current_row_index < 1 ? Predictions {} : m_current_row[x];
  1548. };
  1549. switch (direction) {
  1550. case Direction::North:
  1551. return north();
  1552. case Direction::NorthWest:
  1553. return x < 1 ? north() : m_current_row[x - 1];
  1554. case Direction::NorthEast:
  1555. return x + 1 >= m_current_row.size() ? north() : m_current_row[x + 1];
  1556. case Direction::West:
  1557. return x < 1 ? Predictions {} : m_next_row[x - 1];
  1558. case Direction::NorthNorth:
  1559. return m_current_row_index < 2 ? Predictions {} : m_previous[x];
  1560. case Direction::WestWest:
  1561. return x < 2 ? Predictions {} : m_next_row[x - 2];
  1562. }
  1563. VERIFY_NOT_REACHED();
  1564. }
  1565. WPHeader const& wp_params {};
  1566. u32 m_width {};
  1567. u32 m_current_row_index {};
  1568. FixedArray<Predictions> m_previous {};
  1569. FixedArray<Predictions> m_current_row {};
  1570. FixedArray<Predictions> m_next_row {};
  1571. };
  1572. ///
  1573. /// H.2 - Image decoding
  1574. struct ModularHeader {
  1575. bool use_global_tree {};
  1576. WPHeader wp_params {};
  1577. Vector<TransformInfo> transform {};
  1578. };
  1579. static ErrorOr<Vector<i32>> get_properties(Vector<Channel> const& channels, u16 i, u32 x, u32 y, i32 max_error)
  1580. {
  1581. Vector<i32> properties;
  1582. // Table H.4 - Property definitions
  1583. TRY(properties.try_append(i));
  1584. // FIXME: Handle other cases than GlobalModular
  1585. TRY(properties.try_append(0));
  1586. TRY(properties.try_append(y));
  1587. TRY(properties.try_append(x));
  1588. i32 const W = x > 0 ? channels[i].get(x - 1, y) : (y > 0 ? channels[i].get(x, y - 1) : 0);
  1589. i32 const N = y > 0 ? channels[i].get(x, y - 1) : W;
  1590. i32 const NW = x > 0 && y > 0 ? channels[i].get(x - 1, y - 1) : W;
  1591. i32 const NE = x + 1 < channels[i].width() && y > 0 ? channels[i].get(x + 1, y - 1) : N;
  1592. i32 const NN = y > 1 ? channels[i].get(x, y - 2) : N;
  1593. i32 const WW = x > 1 ? channels[i].get(x - 2, y) : W;
  1594. TRY(properties.try_append(abs(N)));
  1595. TRY(properties.try_append(abs(W)));
  1596. TRY(properties.try_append(N));
  1597. TRY(properties.try_append(W));
  1598. // x > 0 ? W - /* (the value of property 9 at position (x - 1, y)) */ : W
  1599. if (x > 0) {
  1600. auto const x_1 = x - 1;
  1601. 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);
  1602. i32 const N_x_1 = y > 0 ? channels[i].get(x_1, y - 1) : W_x_1;
  1603. i32 const NW_x_1 = x_1 > 0 && y > 0 ? channels[i].get(x_1 - 1, y - 1) : W_x_1;
  1604. TRY(properties.try_append(W - (W_x_1 + N_x_1 - NW_x_1)));
  1605. } else {
  1606. TRY(properties.try_append(W));
  1607. }
  1608. TRY(properties.try_append(W + N - NW));
  1609. TRY(properties.try_append(W - NW));
  1610. TRY(properties.try_append(NW - N));
  1611. TRY(properties.try_append(N - NE));
  1612. TRY(properties.try_append(N - NN));
  1613. TRY(properties.try_append(W - WW));
  1614. TRY(properties.try_append(max_error));
  1615. for (i16 j = i - 1; j >= 0; j--) {
  1616. if (channels[j].width() != channels[i].width())
  1617. continue;
  1618. if (channels[j].height() != channels[i].height())
  1619. continue;
  1620. if (channels[j].hshift() != channels[i].hshift())
  1621. continue;
  1622. if (channels[j].vshift() != channels[i].vshift())
  1623. continue;
  1624. auto rC = channels[j].get(x, y);
  1625. auto rW = (x > 0 ? channels[j].get(x - 1, y) : 0);
  1626. auto rN = (y > 0 ? channels[j].get(x, y - 1) : rW);
  1627. auto rNW = (x > 0 && y > 0 ? channels[j].get(x - 1, y - 1) : rW);
  1628. auto rG = clamp(rW + rN - rNW, min(rW, rN), max(rW, rN));
  1629. TRY(properties.try_append(abs(rC)));
  1630. TRY(properties.try_append(rC));
  1631. TRY(properties.try_append(abs(rC - rG)));
  1632. TRY(properties.try_append(rC - rG));
  1633. }
  1634. return properties;
  1635. }
  1636. static i32 prediction(Neighborhood const& neighborhood, i32 self_correcting, u32 predictor)
  1637. {
  1638. switch (predictor) {
  1639. case 0:
  1640. return 0;
  1641. case 1:
  1642. return neighborhood.W;
  1643. case 2:
  1644. return neighborhood.N;
  1645. case 3:
  1646. return (neighborhood.W + neighborhood.N) / 2;
  1647. case 4:
  1648. return abs(neighborhood.N - neighborhood.NW) < abs(neighborhood.W - neighborhood.NW) ? neighborhood.W : neighborhood.N;
  1649. case 5:
  1650. return clamp(neighborhood.W + neighborhood.N - neighborhood.NW, min(neighborhood.W, neighborhood.N), max(neighborhood.W, neighborhood.N));
  1651. case 6:
  1652. return (self_correcting + 3) >> 3;
  1653. case 7:
  1654. return neighborhood.NE;
  1655. case 8:
  1656. return neighborhood.NW;
  1657. case 9:
  1658. return neighborhood.WW;
  1659. case 10:
  1660. return (neighborhood.W + neighborhood.NW) / 2;
  1661. case 11:
  1662. return (neighborhood.N + neighborhood.NW) / 2;
  1663. case 12:
  1664. return (neighborhood.N + neighborhood.NE) / 2;
  1665. case 13:
  1666. return (6 * neighborhood.N - 2 * neighborhood.NN + 7 * neighborhood.W + neighborhood.WW + neighborhood.NEE + 3 * neighborhood.NE + 8) / 16;
  1667. }
  1668. VERIFY_NOT_REACHED();
  1669. }
  1670. static Neighborhood retrieve_neighborhood(Channel const& channel, u32 x, u32 y)
  1671. {
  1672. i32 const W = x > 0 ? channel.get(x - 1, y) : (y > 0 ? channel.get(x, y - 1) : 0);
  1673. i32 const N = y > 0 ? channel.get(x, y - 1) : W;
  1674. i32 const NW = x > 0 && y > 0 ? channel.get(x - 1, y - 1) : W;
  1675. i32 const NE = x + 1 < channel.width() && y > 0 ? channel.get(x + 1, y - 1) : N;
  1676. i32 const NN = y > 1 ? channel.get(x, y - 2) : N;
  1677. i32 const WW = x > 1 ? channel.get(x - 2, y) : W;
  1678. i32 const NEE = x + 2 < channel.width() && y > 0 ? channel.get(x + 2, y - 1) : NE;
  1679. Neighborhood const neighborhood {
  1680. .N = N,
  1681. .NW = NW,
  1682. .NE = NE,
  1683. .W = W,
  1684. .NN = NN,
  1685. .WW = WW,
  1686. .NEE = NEE,
  1687. };
  1688. return neighborhood;
  1689. }
  1690. static ErrorOr<ModularHeader> read_modular_header(LittleEndianInputBitStream& stream,
  1691. Image& image,
  1692. ImageMetadata const& metadata,
  1693. Optional<EntropyDecoder>& decoder,
  1694. MATree const& global_tree,
  1695. u16 num_channels)
  1696. {
  1697. ModularHeader modular_header;
  1698. modular_header.use_global_tree = TRY(stream.read_bit());
  1699. modular_header.wp_params = TRY(read_self_correcting_predictor(stream));
  1700. auto const nb_transforms = U32(0, 1, 2 + TRY(stream.read_bits(4)), 18 + TRY(stream.read_bits(8)));
  1701. TRY(modular_header.transform.try_resize(nb_transforms));
  1702. for (u32 i {}; i < nb_transforms; ++i)
  1703. modular_header.transform[i] = TRY(read_transform_info(stream));
  1704. Optional<MATree> local_tree;
  1705. if (!modular_header.use_global_tree)
  1706. TODO();
  1707. // where dist_multiplier is set to the largest channel width amongst all channels
  1708. // that are to be decoded, excluding the meta-channels.
  1709. auto const dist_multiplier = [&]() {
  1710. u32 dist_multiplier {};
  1711. // FIXME: This should start at nb_meta_channels not 0
  1712. for (u16 i = 0; i < metadata.number_of_channels(); ++i) {
  1713. if (image.channels()[i].width() > dist_multiplier)
  1714. dist_multiplier = image.channels()[i].width();
  1715. }
  1716. return dist_multiplier;
  1717. }();
  1718. decoder->set_dist_multiplier(dist_multiplier);
  1719. // The decoder then starts an entropy-coded stream (C.1) and decodes the data for each channel
  1720. // (in ascending order of index) as specified in H.3, skipping any channels having width or height
  1721. // zero. Finally, the inverse transformations are applied (from last to first) as described in H.6.
  1722. auto const& tree = local_tree.has_value() ? *local_tree : global_tree;
  1723. for (u16 i {}; i < num_channels; ++i) {
  1724. auto self_correcting_data = TRY(SelfCorrectingData::create(modular_header.wp_params, image.channels()[i].width()));
  1725. for (u32 y {}; y < image.channels()[i].height(); y++) {
  1726. for (u32 x {}; x < image.channels()[i].width(); x++) {
  1727. auto const neighborhood = retrieve_neighborhood(image.channels()[i], x, y);
  1728. auto const self_prediction = self_correcting_data.compute_predictions(neighborhood, x);
  1729. auto const properties = TRY(get_properties(image.channels(), i, x, y, self_prediction.max_error));
  1730. auto const leaf_node = tree.get_leaf(properties);
  1731. auto diff = unpack_signed(TRY(decoder->decode_hybrid_uint(stream, leaf_node.ctx)));
  1732. diff = (diff * leaf_node.multiplier) + leaf_node.offset;
  1733. auto const total = diff + prediction(neighborhood, self_prediction.prediction, leaf_node.predictor);
  1734. self_correcting_data.compute_errors(x, total);
  1735. image.channels()[i].set(x, y, total);
  1736. }
  1737. self_correcting_data.register_next_row();
  1738. }
  1739. image.channels()[i].set_decoded(true);
  1740. }
  1741. return modular_header;
  1742. }
  1743. ///
  1744. /// G.1.2 - LF channel dequantization weights
  1745. struct GlobalModular {
  1746. MATree ma_tree;
  1747. ModularHeader modular_header;
  1748. };
  1749. static ErrorOr<GlobalModular> read_global_modular(LittleEndianInputBitStream& stream,
  1750. Image& image,
  1751. FrameHeader const& frame_header,
  1752. ImageMetadata const& metadata,
  1753. Optional<EntropyDecoder>& entropy_decoder)
  1754. {
  1755. GlobalModular global_modular;
  1756. auto const decode_ma_tree = TRY(stream.read_bit());
  1757. if (decode_ma_tree)
  1758. global_modular.ma_tree = TRY(MATree::decode(stream, entropy_decoder));
  1759. // The decoder then decodes a modular sub-bitstream (Annex H), where
  1760. // the number of channels is computed as follows:
  1761. auto num_channels = metadata.num_extra_channels;
  1762. if (frame_header.encoding == FrameHeader::Encoding::kModular) {
  1763. if (!frame_header.do_YCbCr && !metadata.xyb_encoded
  1764. && metadata.colour_encoding.colour_space == ColourEncoding::ColourSpace::kGrey) {
  1765. num_channels += 1;
  1766. } else {
  1767. num_channels += 3;
  1768. }
  1769. }
  1770. // FIXME: Ensure this spec comment:
  1771. // However, the decoder only decodes the first nb_meta_channels channels and any further channels
  1772. // that have a width and height that are both at most group_dim. At that point, it stops decoding.
  1773. // No inverse transforms are applied yet.
  1774. global_modular.modular_header = TRY(read_modular_header(stream, image, metadata, entropy_decoder, global_modular.ma_tree, num_channels));
  1775. return global_modular;
  1776. }
  1777. ///
  1778. /// G.1 - LfGlobal
  1779. struct LfGlobal {
  1780. LfChannelDequantization lf_dequant;
  1781. GlobalModular gmodular;
  1782. };
  1783. static ErrorOr<LfGlobal> read_lf_global(LittleEndianInputBitStream& stream,
  1784. Image& image,
  1785. FrameHeader const& frame_header,
  1786. ImageMetadata const& metadata,
  1787. Optional<EntropyDecoder>& entropy_decoder)
  1788. {
  1789. LfGlobal lf_global;
  1790. if (frame_header.flags != FrameHeader::Flags::None)
  1791. TODO();
  1792. lf_global.lf_dequant = TRY(read_lf_channel_dequantization(stream));
  1793. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT)
  1794. TODO();
  1795. lf_global.gmodular = TRY(read_global_modular(stream, image, frame_header, metadata, entropy_decoder));
  1796. return lf_global;
  1797. }
  1798. ///
  1799. /// G.2 - LfGroup
  1800. static ErrorOr<void> read_lf_group(LittleEndianInputBitStream&,
  1801. Image& image,
  1802. FrameHeader const& frame_header)
  1803. {
  1804. // LF coefficients
  1805. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1806. TODO();
  1807. }
  1808. // ModularLfGroup
  1809. for (auto const& channel : image.channels()) {
  1810. if (channel.decoded())
  1811. continue;
  1812. if (channel.hshift() < 3 || channel.vshift() < 3)
  1813. continue;
  1814. // This code actually only detect that we need to read a null image
  1815. // so a no-op. It should be fully rewritten when we add proper support
  1816. // for LfGroup.
  1817. TODO();
  1818. }
  1819. // HF metadata
  1820. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1821. TODO();
  1822. }
  1823. return {};
  1824. }
  1825. ///
  1826. /// H.6 - Transformations
  1827. static void apply_rct(Image& image, TransformInfo const& transformation)
  1828. {
  1829. auto& channels = image.channels();
  1830. for (u32 y {}; y < channels[transformation.begin_c].height(); y++) {
  1831. for (u32 x {}; x < channels[transformation.begin_c].width(); x++) {
  1832. auto a = channels[transformation.begin_c + 0].get(x, y);
  1833. auto b = channels[transformation.begin_c + 1].get(x, y);
  1834. auto c = channels[transformation.begin_c + 2].get(x, y);
  1835. i32 d {};
  1836. i32 e {};
  1837. i32 f {};
  1838. auto const permutation = transformation.rct_type / 7;
  1839. auto const type = transformation.rct_type % 7;
  1840. if (type == 6) { // YCgCo
  1841. auto const tmp = a - (c >> 1);
  1842. e = c + tmp;
  1843. f = tmp - (b >> 1);
  1844. d = f + b;
  1845. } else {
  1846. if (type & 1)
  1847. c = c + a;
  1848. if ((type >> 1) == 1)
  1849. b = b + a;
  1850. if ((type >> 1) == 2)
  1851. b = b + ((a + c) >> 1);
  1852. d = a;
  1853. e = b;
  1854. f = c;
  1855. }
  1856. Array<i32, 3> v {};
  1857. v[permutation % 3] = d;
  1858. v[(permutation + 1 + (permutation / 3)) % 3] = e;
  1859. v[(permutation + 2 - (permutation / 3)) % 3] = f;
  1860. channels[transformation.begin_c + 0].set(x, y, v[0]);
  1861. channels[transformation.begin_c + 1].set(x, y, v[1]);
  1862. channels[transformation.begin_c + 2].set(x, y, v[2]);
  1863. }
  1864. }
  1865. }
  1866. static void apply_transformation(Image& image, TransformInfo const& transformation)
  1867. {
  1868. switch (transformation.tr) {
  1869. case TransformInfo::TransformId::kRCT:
  1870. apply_rct(image, transformation);
  1871. break;
  1872. case TransformInfo::TransformId::kPalette:
  1873. case TransformInfo::TransformId::kSqueeze:
  1874. TODO();
  1875. default:
  1876. VERIFY_NOT_REACHED();
  1877. }
  1878. }
  1879. ///
  1880. /// G.3.2 - PassGroup
  1881. static ErrorOr<void> read_pass_group(LittleEndianInputBitStream& stream,
  1882. Image& image,
  1883. FrameHeader const& frame_header,
  1884. u32 group_dim)
  1885. {
  1886. if (frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1887. (void)stream;
  1888. TODO();
  1889. }
  1890. auto& channels = image.channels();
  1891. for (u16 i {}; i < channels.size(); ++i) {
  1892. // Skip meta-channels
  1893. // FIXME: Also test if the channel has already been decoded
  1894. // See: nb_meta_channels in the spec
  1895. bool const is_meta_channel = channels[i].width() <= group_dim
  1896. || channels[i].height() <= group_dim
  1897. || channels[i].hshift() >= 3
  1898. || channels[i].vshift() >= 3;
  1899. if (!is_meta_channel)
  1900. TODO();
  1901. }
  1902. return {};
  1903. }
  1904. ///
  1905. /// Table F.1 — Frame bundle
  1906. struct Frame {
  1907. FrameHeader frame_header;
  1908. TOC toc;
  1909. LfGlobal lf_global;
  1910. u64 width {};
  1911. u64 height {};
  1912. u64 num_groups {};
  1913. u64 num_lf_groups {};
  1914. Image image {};
  1915. };
  1916. static ErrorOr<Frame> read_frame(LittleEndianInputBitStream& stream,
  1917. SizeHeader const& size_header,
  1918. ImageMetadata const& metadata,
  1919. Optional<EntropyDecoder>& entropy_decoder)
  1920. {
  1921. // F.1 - General
  1922. // Each Frame is byte-aligned by invoking ZeroPadToByte() (B.2.7)
  1923. stream.align_to_byte_boundary();
  1924. Frame frame;
  1925. frame.frame_header = TRY(read_frame_header(stream, size_header, metadata));
  1926. if (!frame.frame_header.have_crop) {
  1927. frame.width = size_header.width;
  1928. frame.height = size_header.height;
  1929. } else {
  1930. frame.width = frame.frame_header.width;
  1931. frame.height = frame.frame_header.height;
  1932. }
  1933. if (frame.frame_header.upsampling > 1) {
  1934. frame.width = ceil(static_cast<double>(frame.width) / frame.frame_header.upsampling);
  1935. frame.height = ceil(static_cast<double>(frame.height) / frame.frame_header.upsampling);
  1936. }
  1937. if (frame.frame_header.lf_level > 0)
  1938. TODO();
  1939. // F.2 - FrameHeader
  1940. auto const group_dim = 128 << frame.frame_header.group_size_shift;
  1941. auto const frame_width = static_cast<double>(frame.width);
  1942. auto const frame_height = static_cast<double>(frame.height);
  1943. frame.num_groups = ceil(frame_width / group_dim) * ceil(frame_height / group_dim);
  1944. frame.num_lf_groups = ceil(frame_width / (group_dim * 8)) * ceil(frame_height / (group_dim * 8));
  1945. frame.toc = TRY(read_toc(stream, frame.frame_header, frame.num_groups, frame.num_lf_groups));
  1946. frame.image = TRY(Image::create({ frame.width, frame.height }, metadata));
  1947. frame.lf_global = TRY(read_lf_global(stream, frame.image, frame.frame_header, metadata, entropy_decoder));
  1948. for (u32 i {}; i < frame.num_lf_groups; ++i)
  1949. TRY(read_lf_group(stream, frame.image, frame.frame_header));
  1950. if (frame.frame_header.encoding == FrameHeader::Encoding::kVarDCT) {
  1951. TODO();
  1952. }
  1953. auto const num_pass_group = frame.num_groups * frame.frame_header.passes.num_passes;
  1954. auto const& transform_infos = frame.lf_global.gmodular.modular_header.transform;
  1955. for (u64 i {}; i < num_pass_group; ++i)
  1956. TRY(read_pass_group(stream, frame.image, frame.frame_header, group_dim));
  1957. // G.4.2 - Modular group data
  1958. // When all modular groups are decoded, the inverse transforms are applied to
  1959. // the at that point fully decoded GlobalModular image, as specified in H.6.
  1960. for (auto const& transformation : transform_infos.in_reverse())
  1961. apply_transformation(frame.image, transformation);
  1962. return frame;
  1963. }
  1964. ///
  1965. /// 5.2 - Mirroring
  1966. static u32 mirror_1d(i32 coord, u32 size)
  1967. {
  1968. if (coord < 0)
  1969. return mirror_1d(-coord - 1, size);
  1970. else if (static_cast<u32>(coord) >= size)
  1971. return mirror_1d(2 * size - 1 - coord, size);
  1972. else
  1973. return coord;
  1974. }
  1975. ///
  1976. /// K - Image features
  1977. static ErrorOr<void> apply_upsampling(Frame& frame, ImageMetadata const& metadata)
  1978. {
  1979. Optional<u32> ec_max;
  1980. for (auto upsampling : frame.frame_header.ec_upsampling) {
  1981. if (!ec_max.has_value() || upsampling > *ec_max)
  1982. ec_max = upsampling;
  1983. }
  1984. if (frame.frame_header.upsampling > 1 || ec_max.value_or(0) > 1) {
  1985. if (ec_max.value_or(0) > 2)
  1986. TODO();
  1987. auto const k = frame.frame_header.upsampling;
  1988. auto weight = [k, &metadata](u8 index) -> double {
  1989. if (k == 2)
  1990. return metadata.up2_weight[index];
  1991. if (k == 4)
  1992. return metadata.up4_weight[index];
  1993. return metadata.up8_weight[index];
  1994. };
  1995. // FIXME: Use ec_upsampling for extra-channels
  1996. for (auto& channel : frame.image.channels()) {
  1997. auto upsampled = TRY(Channel::create(k * channel.width(), k * channel.height()));
  1998. // Loop over the original image
  1999. for (u32 y {}; y < channel.height(); y++) {
  2000. for (u32 x {}; x < channel.width(); x++) {
  2001. // Loop over the upsampling factor
  2002. for (u8 kx {}; kx < k; ++kx) {
  2003. for (u8 ky {}; ky < k; ++ky) {
  2004. double sum {};
  2005. // Loop over the W window
  2006. double W_min = NumericLimits<double>::max();
  2007. double W_max = -NumericLimits<double>::max();
  2008. for (u8 ix {}; ix < 5; ++ix) {
  2009. for (u8 iy {}; iy < 5; ++iy) {
  2010. auto const j = (ky < k / 2) ? (iy + 5 * ky) : ((4 - iy) + 5 * (k - 1 - ky));
  2011. auto const i = (kx < k / 2) ? (ix + 5 * kx) : ((4 - ix) + 5 * (k - 1 - kx));
  2012. auto const minimum = min(i, j);
  2013. auto const maximum = max(i, j);
  2014. auto const index = 5 * k * minimum / 2 - minimum * (minimum - 1) / 2 + maximum - minimum;
  2015. auto const origin_sample_x = mirror_1d(x + ix - 2, channel.width());
  2016. auto const origin_sample_y = mirror_1d(y + iy - 2, channel.height());
  2017. auto const origin_sample = channel.get(origin_sample_x, origin_sample_y);
  2018. W_min = min(W_min, origin_sample);
  2019. W_max = max(W_max, origin_sample);
  2020. sum += origin_sample * weight(index);
  2021. }
  2022. }
  2023. // The resulting sample is clamped to the range [a, b] where a and b are
  2024. // the minimum and maximum of the samples in W.
  2025. sum = clamp(sum, W_min, W_max);
  2026. upsampled.set(x * k + kx, y * k + ky, sum);
  2027. }
  2028. }
  2029. }
  2030. }
  2031. channel = move(upsampled);
  2032. }
  2033. }
  2034. return {};
  2035. }
  2036. static ErrorOr<void> apply_image_features(Frame& frame, ImageMetadata const& metadata)
  2037. {
  2038. TRY(apply_upsampling(frame, metadata));
  2039. if (frame.frame_header.flags != FrameHeader::Flags::None)
  2040. TODO();
  2041. return {};
  2042. }
  2043. ///
  2044. /// L.2 - XYB + L.3 - YCbCr
  2045. static void ycbcr_to_rgb(Image& image, u8 bits_per_sample)
  2046. {
  2047. auto& channels = image.channels();
  2048. VERIFY(channels.size() >= 3);
  2049. VERIFY(channels[0].width() == channels[1].width() && channels[1].width() == channels[2].width());
  2050. VERIFY(channels[0].height() == channels[1].height() && channels[1].height() == channels[2].height());
  2051. auto const half_range_offset = (1 << bits_per_sample) / 2;
  2052. for (u32 y = 0; y < channels[0].height(); ++y) {
  2053. for (u32 x = 0; x < channels[0].width(); ++x) {
  2054. auto const cb = channels[0].get(x, y);
  2055. auto const luma = channels[1].get(x, y);
  2056. auto const cr = channels[2].get(x, y);
  2057. channels[0].set(x, y, luma + half_range_offset + 1.402 * cr);
  2058. channels[1].set(x, y, luma + half_range_offset - 0.344136 * cb - 0.714136 * cr);
  2059. channels[2].set(x, y, luma + half_range_offset + 1.772 * cb);
  2060. }
  2061. }
  2062. }
  2063. static void apply_colour_transformation(Frame& frame, ImageMetadata const& metadata)
  2064. {
  2065. if (frame.frame_header.do_YCbCr)
  2066. ycbcr_to_rgb(frame.image, metadata.bit_depth.bits_per_sample);
  2067. if (metadata.xyb_encoded) {
  2068. TODO();
  2069. } else {
  2070. // FIXME: Do a proper color transformation with metadata.colour_encoding
  2071. }
  2072. }
  2073. ///
  2074. /// L.4 - Extra channel rendering
  2075. static ErrorOr<void> render_extra_channels(Image&, ImageMetadata const& metadata)
  2076. {
  2077. for (u16 i = metadata.number_of_color_channels(); i < metadata.number_of_channels(); ++i) {
  2078. auto const ec_index = i - metadata.number_of_color_channels();
  2079. if (metadata.ec_info[ec_index].dim_shift != 0)
  2080. TODO();
  2081. }
  2082. return {};
  2083. }
  2084. ///
  2085. class JPEGXLLoadingContext {
  2086. public:
  2087. JPEGXLLoadingContext(NonnullOwnPtr<Stream> stream)
  2088. : m_stream(move(stream))
  2089. {
  2090. }
  2091. ErrorOr<void> decode_image_header()
  2092. {
  2093. constexpr auto JPEGXL_SIGNATURE = 0xFF0A;
  2094. auto const signature = TRY(m_stream.read_value<BigEndian<u16>>());
  2095. if (signature != JPEGXL_SIGNATURE)
  2096. return Error::from_string_literal("Unrecognized signature");
  2097. m_header = TRY(read_size_header(m_stream));
  2098. m_metadata = TRY(read_metadata_header(m_stream));
  2099. m_state = State::HeaderDecoded;
  2100. return {};
  2101. }
  2102. ErrorOr<void> decode_frame()
  2103. {
  2104. auto frame = TRY(read_frame(m_stream, m_header, m_metadata, m_entropy_decoder));
  2105. if (frame.frame_header.restoration_filter.gab || frame.frame_header.restoration_filter.epf_iters != 0)
  2106. TODO();
  2107. TRY(apply_image_features(frame, m_metadata));
  2108. apply_colour_transformation(frame, m_metadata);
  2109. TRY(render_extra_channels(frame.image, m_metadata));
  2110. if (!m_image.has_value())
  2111. m_image = TRY(Image::create({ m_header.width, m_header.height }, m_metadata));
  2112. frame.image.blend_into(*m_image, frame.frame_header);
  2113. return {};
  2114. }
  2115. ErrorOr<void> decode()
  2116. {
  2117. auto result = [this]() -> ErrorOr<void> {
  2118. // A.1 - Codestream structure
  2119. // The header is already decoded in JPEGXLImageDecoderPlugin::create()
  2120. if (m_metadata.colour_encoding.want_icc)
  2121. TODO();
  2122. if (m_metadata.preview.has_value())
  2123. TODO();
  2124. TRY(decode_frame());
  2125. m_bitmap = TRY(m_image->to_bitmap(m_metadata));
  2126. m_image.clear();
  2127. return {};
  2128. }();
  2129. m_state = result.is_error() ? State::Error : State::FrameDecoded;
  2130. return result;
  2131. }
  2132. enum class State {
  2133. NotDecoded = 0,
  2134. Error,
  2135. HeaderDecoded,
  2136. FrameDecoded,
  2137. };
  2138. State state() const
  2139. {
  2140. return m_state;
  2141. }
  2142. IntSize size() const
  2143. {
  2144. return { m_header.width, m_header.height };
  2145. }
  2146. RefPtr<Bitmap> bitmap() const
  2147. {
  2148. return m_bitmap;
  2149. }
  2150. private:
  2151. State m_state { State::NotDecoded };
  2152. LittleEndianInputBitStream m_stream;
  2153. RefPtr<Gfx::Bitmap> m_bitmap;
  2154. // JPEG XL images can be composed of multiples sub-images, this variable is an internal
  2155. // representation of this blending before the final rendering (in m_bitmap)
  2156. Optional<Image> m_image;
  2157. Optional<EntropyDecoder> m_entropy_decoder {};
  2158. SizeHeader m_header;
  2159. ImageMetadata m_metadata;
  2160. };
  2161. JPEGXLImageDecoderPlugin::JPEGXLImageDecoderPlugin(NonnullOwnPtr<FixedMemoryStream> stream)
  2162. {
  2163. m_context = make<JPEGXLLoadingContext>(move(stream));
  2164. }
  2165. JPEGXLImageDecoderPlugin::~JPEGXLImageDecoderPlugin() = default;
  2166. IntSize JPEGXLImageDecoderPlugin::size()
  2167. {
  2168. return m_context->size();
  2169. }
  2170. bool JPEGXLImageDecoderPlugin::sniff(ReadonlyBytes data)
  2171. {
  2172. return data.size() > 2
  2173. && data.data()[0] == 0xFF
  2174. && data.data()[1] == 0x0A;
  2175. }
  2176. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGXLImageDecoderPlugin::create(ReadonlyBytes data)
  2177. {
  2178. auto stream = TRY(try_make<FixedMemoryStream>(data));
  2179. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEGXLImageDecoderPlugin(move(stream))));
  2180. TRY(plugin->m_context->decode_image_header());
  2181. return plugin;
  2182. }
  2183. bool JPEGXLImageDecoderPlugin::is_animated()
  2184. {
  2185. return false;
  2186. }
  2187. size_t JPEGXLImageDecoderPlugin::loop_count()
  2188. {
  2189. return 0;
  2190. }
  2191. size_t JPEGXLImageDecoderPlugin::frame_count()
  2192. {
  2193. return 1;
  2194. }
  2195. size_t JPEGXLImageDecoderPlugin::first_animated_frame_index()
  2196. {
  2197. return 0;
  2198. }
  2199. ErrorOr<ImageFrameDescriptor> JPEGXLImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  2200. {
  2201. if (index > 0)
  2202. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Invalid frame index");
  2203. if (m_context->state() == JPEGXLLoadingContext::State::Error)
  2204. return Error::from_string_literal("JPEGXLImageDecoderPlugin: Decoding failed");
  2205. if (m_context->state() < JPEGXLLoadingContext::State::FrameDecoded)
  2206. TRY(m_context->decode());
  2207. return ImageFrameDescriptor { m_context->bitmap(), 0 };
  2208. }
  2209. ErrorOr<Optional<ReadonlyBytes>> JPEGXLImageDecoderPlugin::icc_data()
  2210. {
  2211. return OptionalNone {};
  2212. }
  2213. }