WebPLoaderLossy.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. /*
  2. * Copyright (c) 2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Endian.h>
  8. #include <AK/Format.h>
  9. #include <AK/MemoryStream.h>
  10. #include <AK/Vector.h>
  11. #include <LibGfx/ImageFormats/BooleanDecoder.h>
  12. #include <LibGfx/ImageFormats/WebPLoaderLossy.h>
  13. #include <LibGfx/ImageFormats/WebPLoaderLossyTables.h>
  14. // Lossy format: https://datatracker.ietf.org/doc/html/rfc6386
  15. // Summary:
  16. // A lossy webp image is a VP8 keyframe.
  17. // A VP8 keyframe consists of 16x16 pixel tiles called macroblocks. Each macroblock is subdivided into 4x4 pixel tiles called subblocks.
  18. // Pixel values are stored as YUV 4:2:0. That is, each 4x4 luma pixels are covered by 1 pixel U chroma and 1 pixel V chroma.
  19. // This means one macroblock is covered by 4x4 Y subblocks and 2x2 U and V subblocks each.
  20. // VP8 data consists of:
  21. // * A tiny bit of uncompressed data, storing image dimensions and the size of the first compressed chunk of data, called the first partition
  22. // * The first partition, which is a entropy-coded bitstream storing:
  23. // 1. A fixed-size header.
  24. // The main piece of data this stores is a probability distribution for how pixel values of each macroblock are predicted from previously decoded data.
  25. // It also stores how may independent entropy-coded bitstreams are used to store the actual pixel data (for all images I've seen so far, just one).
  26. // 2. For each macroblock, it stores how that macroblock's pixel values are predicted from previously decoded data (and some more per-macroblock metadata).
  27. // There are independent prediction modes for Y, U, V.
  28. // U and V store a single prediction mode per macroblock.
  29. // Y can store a single prediction mode per macroblock, or it can store one subblock prediction mode for each of the 4x4 luma subblocks.
  30. // * One or more additional entropy-coded bitstreams ("partitions") that store the discrete cosine transform ("DCT") coefficients for the actual pixel data for each macroblock.
  31. // Each macroblock is subdivided into 4x4 tiles called "subblocks". A 16x16 pixel macroblock consists of:
  32. // 0. If the macroblock stores 4x4 luma subblock prediction modes, the 4x4 DC coefficients of each subblock's DCT are stored at the start of the macroblock's data,
  33. // as coefficients of an inverse Walsh-Hadamard Transform (WHT).
  34. // 1. 4x4 luma subblocks
  35. // 2. 2x2 U chrome subblocks
  36. // 3. 2x2 U chrome subblocks
  37. // That is, each macroblock stores 24 or 25 sets of coefficients.
  38. // Each set of coefficients stores 16 numbers, using a combination of a custom prefix tree and dequantization.
  39. // The inverse DCT output is added to the output of the prediction.
  40. namespace Gfx {
  41. // https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossy
  42. // https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax"
  43. ErrorOr<VP8Header> decode_webp_chunk_VP8_header(ReadonlyBytes vp8_data)
  44. {
  45. if (vp8_data.size() < 10)
  46. return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk too small");
  47. // FIXME: Eventually, this should probably call into LibVideo/VP8,
  48. // and image decoders should move into LibImageDecoders which depends on both LibGfx and LibVideo.
  49. // (LibVideo depends on LibGfx, so LibGfx can't depend on LibVideo itself.)
  50. // https://datatracker.ietf.org/doc/html/rfc6386#section-4 "Overview of Compressed Data Format"
  51. // "The decoder is simply presented with a sequence of compressed frames [...]
  52. // The first frame presented to the decompressor is [...] a key frame. [...]
  53. // [E]very compressed frame has three or more pieces. It begins with an uncompressed data chunk comprising 10 bytes in the case of key frames"
  54. u8 const* data = vp8_data.data();
  55. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.1 "Uncompressed Data Chunk"
  56. u32 frame_tag = data[0] | (data[1] << 8) | (data[2] << 16);
  57. bool is_key_frame = (frame_tag & 1) == 0; // https://www.rfc-editor.org/errata/eid5534
  58. u8 version = (frame_tag & 0xe) >> 1;
  59. bool show_frame = (frame_tag & 0x10) != 0;
  60. u32 size_of_first_partition = frame_tag >> 5;
  61. if (!is_key_frame)
  62. return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk not a key frame");
  63. if (!show_frame)
  64. return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk has invalid visibility for webp image");
  65. if (version > 3)
  66. return Error::from_string_literal("WebPImageDecoderPlugin: unknown version number in 'VP8 ' chunk");
  67. u32 start_code = data[3] | (data[4] << 8) | (data[5] << 16);
  68. if (start_code != 0x2a019d) // https://www.rfc-editor.org/errata/eid7370
  69. return Error::from_string_literal("WebPImageDecoderPlugin: 'VP8 ' chunk invalid start_code");
  70. // "The scaling specifications for each dimension are encoded as follows.
  71. // 0 | No upscaling (the most common case).
  72. // 1 | Upscale by 5/4.
  73. // 2 | Upscale by 5/3.
  74. // 3 | Upscale by 2."
  75. // This is a display-time operation and doesn't affect decoding."
  76. u16 width_and_horizontal_scale = data[6] | (data[7] << 8);
  77. u16 width = width_and_horizontal_scale & 0x3fff;
  78. u8 horizontal_scale = width_and_horizontal_scale >> 14;
  79. u16 heigth_and_vertical_scale = data[8] | (data[9] << 8);
  80. u16 height = heigth_and_vertical_scale & 0x3fff;
  81. u8 vertical_scale = heigth_and_vertical_scale >> 14;
  82. dbgln_if(WEBP_DEBUG, "version {}, show_frame {}, size_of_first_partition {}, width {}, horizontal_scale {}, height {}, vertical_scale {}",
  83. version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale);
  84. return VP8Header { version, show_frame, size_of_first_partition, width, horizontal_scale, height, vertical_scale, vp8_data.slice(10, size_of_first_partition), vp8_data.slice(10 + size_of_first_partition) };
  85. }
  86. namespace {
  87. // Reads n bits followed by a sign bit (0: positive, 1: negative).
  88. ErrorOr<i8> read_signed_literal(BooleanDecoder& decoder, u8 n)
  89. {
  90. VERIFY(n <= 7);
  91. i8 i = TRY(decoder.read_literal(n));
  92. if (TRY(decoder.read_literal(1)))
  93. i = -i;
  94. return i;
  95. }
  96. // https://datatracker.ietf.org/doc/html/rfc6386#section-19 "Annex A: Bitstream Syntax"
  97. #define L(n) decoder.read_literal(n)
  98. #define B(prob) decoder.read_bool(prob)
  99. #define L_signed(n) read_signed_literal(decoder, n)
  100. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.2 "Color Space and Pixel Type (Key Frames Only)"
  101. enum class ColorSpaceAndPixelType {
  102. YUV = 0,
  103. ReservedForFutureUse = 1,
  104. };
  105. enum class ClampingSpecification {
  106. DecoderMustClampTo0To255 = 0,
  107. NoClampingNecessary = 1,
  108. };
  109. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.3 Segment-Based Adjustments"
  110. // https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header"
  111. enum class SegmentFeatureMode {
  112. // Spec 19.2 says 0 is delta, 1 absolute; spec 9.3 has it the other way round. 19.2 is correct.
  113. // https://www.rfc-editor.org/errata/eid7519
  114. DeltaValueMode = 0,
  115. AbsoluteValueMode = 1,
  116. };
  117. struct Segmentation {
  118. bool update_macroblock_segmentation_map { false };
  119. SegmentFeatureMode segment_feature_mode { SegmentFeatureMode::DeltaValueMode };
  120. i8 quantizer_update_value[4] {};
  121. i8 loop_filter_update_value[4] {};
  122. u8 macroblock_segment_tree_probabilities[3] = { 255, 255, 255 };
  123. };
  124. ErrorOr<Segmentation> decode_VP8_frame_header_segmentation(BooleanDecoder&);
  125. // Also https://datatracker.ietf.org/doc/html/rfc6386#section-9.6 "Dequantization Indices"
  126. struct QuantizationIndices {
  127. u8 y_ac { 0 };
  128. i8 y_dc_delta { 0 };
  129. i8 y2_dc_delta { 0 };
  130. i8 y2_ac_delta { 0 };
  131. i8 uv_dc_delta { 0 };
  132. i8 uv_ac_delta { 0 };
  133. };
  134. ErrorOr<QuantizationIndices> decode_VP8_frame_header_quantization_indices(BooleanDecoder&);
  135. struct LoopFilterAdjustment {
  136. bool enable_loop_filter_adjustment { false };
  137. i8 ref_frame_delta[4] {};
  138. i8 mb_mode_delta[4] {};
  139. };
  140. ErrorOr<LoopFilterAdjustment> decode_VP8_frame_header_loop_filter_adjustment(BooleanDecoder&);
  141. using CoefficientProbabilities = Prob[4][8][3][num_dct_tokens - 1];
  142. ErrorOr<void> decode_VP8_frame_header_coefficient_probabilities(BooleanDecoder&, CoefficientProbabilities);
  143. // https://datatracker.ietf.org/doc/html/rfc6386#section-15 "Loop Filter"
  144. // "The first is a flag (filter_type) selecting the type of filter (normal or simple)"
  145. enum class FilterType {
  146. Normal = 0,
  147. Simple = 1,
  148. };
  149. // https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header"
  150. struct FrameHeader {
  151. ColorSpaceAndPixelType color_space {};
  152. ClampingSpecification clamping_type {};
  153. bool is_segmentation_enabled {};
  154. Segmentation segmentation {};
  155. FilterType filter_type {};
  156. u8 loop_filter_level {};
  157. u8 sharpness_level {};
  158. LoopFilterAdjustment loop_filter_adjustment {};
  159. u8 number_of_dct_partitions {};
  160. QuantizationIndices quantization_indices {};
  161. CoefficientProbabilities coefficient_probabilities;
  162. bool enable_skipping_of_macroblocks_containing_only_zero_coefficients {};
  163. u8 probability_skip_false;
  164. };
  165. ErrorOr<FrameHeader> decode_VP8_frame_header(BooleanDecoder& decoder)
  166. {
  167. // https://datatracker.ietf.org/doc/html/rfc6386#section-19.2 "Frame Header"
  168. FrameHeader header;
  169. // In the VP8 spec, this is in an `if (key_frames)`, but webp files only have key frames.
  170. header.color_space = ColorSpaceAndPixelType { TRY(L(1)) };
  171. header.clamping_type = ClampingSpecification { TRY(L(1)) };
  172. dbgln_if(WEBP_DEBUG, "color_space {} clamping_type {}", (int)header.color_space, (int)header.clamping_type);
  173. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.3 "Segment-Based Adjustments"
  174. header.is_segmentation_enabled = TRY(L(1));
  175. dbgln_if(WEBP_DEBUG, "segmentation_enabled {}", header.is_segmentation_enabled);
  176. if (header.is_segmentation_enabled)
  177. header.segmentation = TRY(decode_VP8_frame_header_segmentation(decoder));
  178. header.filter_type = FilterType { TRY(L(1)) };
  179. header.loop_filter_level = TRY(L(6));
  180. header.sharpness_level = TRY(L(3));
  181. dbgln_if(WEBP_DEBUG, "filter_type {} loop_filter_level {} sharpness_level {}", (int)header.filter_type, header.loop_filter_level, header.sharpness_level);
  182. header.loop_filter_adjustment = TRY(decode_VP8_frame_header_loop_filter_adjustment(decoder));
  183. u8 log2_nbr_of_dct_partitions = TRY(L(2));
  184. dbgln_if(WEBP_DEBUG, "log2_nbr_of_dct_partitions {}", log2_nbr_of_dct_partitions);
  185. header.number_of_dct_partitions = 1 << log2_nbr_of_dct_partitions;
  186. header.quantization_indices = TRY(decode_VP8_frame_header_quantization_indices(decoder));
  187. // In the VP8 spec, this is in an `if (key_frames)` followed by a lengthy `else`, but webp files only have key frames.
  188. u8 refresh_entropy_probs = TRY(L(1)); // Has no effect in webp files.
  189. dbgln_if(WEBP_DEBUG, "refresh_entropy_probs {}", refresh_entropy_probs);
  190. memcpy(header.coefficient_probabilities, DEFAULT_COEFFICIENT_PROBABILITIES, sizeof(header.coefficient_probabilities));
  191. TRY(decode_VP8_frame_header_coefficient_probabilities(decoder, header.coefficient_probabilities));
  192. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.11 "Remaining Frame Header Data (Key Frame)"
  193. header.enable_skipping_of_macroblocks_containing_only_zero_coefficients = TRY(L(1));
  194. dbgln_if(WEBP_DEBUG, "mb_no_skip_coeff {}", header.enable_skipping_of_macroblocks_containing_only_zero_coefficients);
  195. if (header.enable_skipping_of_macroblocks_containing_only_zero_coefficients) {
  196. header.probability_skip_false = TRY(L(8));
  197. dbgln_if(WEBP_DEBUG, "prob_skip_false {}", header.probability_skip_false);
  198. }
  199. // In the VP8 spec, there is a length `if (!key_frames)` here, but webp files only have key frames.
  200. return header;
  201. }
  202. ErrorOr<Segmentation> decode_VP8_frame_header_segmentation(BooleanDecoder& decoder)
  203. {
  204. // Corresponds to "update_segmentation()" in section 19.2 of the spec.
  205. Segmentation segmentation;
  206. segmentation.update_macroblock_segmentation_map = TRY(L(1));
  207. u8 update_segment_feature_data = TRY(L(1));
  208. dbgln_if(WEBP_DEBUG, "update_mb_segmentation_map {} update_segment_feature_data {}",
  209. segmentation.update_macroblock_segmentation_map, update_segment_feature_data);
  210. if (update_segment_feature_data) {
  211. segmentation.segment_feature_mode = static_cast<SegmentFeatureMode>(TRY(L(1)));
  212. dbgln_if(WEBP_DEBUG, "segment_feature_mode {}", (int)segmentation.segment_feature_mode);
  213. for (int i = 0; i < 4; ++i) {
  214. u8 quantizer_update = TRY(L(1));
  215. dbgln_if(WEBP_DEBUG, "quantizer_update {}", quantizer_update);
  216. if (quantizer_update) {
  217. i8 quantizer_update_value = TRY(L_signed(7));
  218. dbgln_if(WEBP_DEBUG, "quantizer_update_value {}", quantizer_update_value);
  219. segmentation.quantizer_update_value[i] = quantizer_update_value;
  220. }
  221. }
  222. for (int i = 0; i < 4; ++i) {
  223. u8 loop_filter_update = TRY(L(1));
  224. dbgln_if(WEBP_DEBUG, "loop_filter_update {}", loop_filter_update);
  225. if (loop_filter_update) {
  226. i8 loop_filter_update_value = TRY(L_signed(6));
  227. dbgln_if(WEBP_DEBUG, "loop_filter_update_value {}", loop_filter_update_value);
  228. segmentation.loop_filter_update_value[i] = loop_filter_update_value;
  229. }
  230. }
  231. }
  232. if (segmentation.update_macroblock_segmentation_map) {
  233. // This reads mb_segment_tree_probs for https://datatracker.ietf.org/doc/html/rfc6386#section-10.
  234. for (int i = 0; i < 3; ++i) {
  235. u8 segment_prob_update = TRY(L(1));
  236. dbgln_if(WEBP_DEBUG, "segment_prob_update {}", segment_prob_update);
  237. if (segment_prob_update) {
  238. u8 segment_prob = TRY(L(8));
  239. dbgln_if(WEBP_DEBUG, "segment_prob {}", segment_prob);
  240. segmentation.macroblock_segment_tree_probabilities[i] = segment_prob;
  241. }
  242. }
  243. }
  244. return segmentation;
  245. }
  246. ErrorOr<QuantizationIndices> decode_VP8_frame_header_quantization_indices(BooleanDecoder& decoder)
  247. {
  248. // Corresponds to "quant_indices()" in section 19.2 of the spec.
  249. QuantizationIndices quantization_indices;
  250. // "The first 7-bit index gives the dequantization table index for
  251. // Y-plane AC coefficients, called yac_qi. It is always coded and acts
  252. // as a baseline for the other 5 quantization indices, each of which is
  253. // represented by a delta from this baseline index."
  254. quantization_indices.y_ac = TRY(L(7));
  255. dbgln_if(WEBP_DEBUG, "y_ac_qi {}", quantization_indices.y_ac);
  256. auto read_delta = [&decoder](StringView name, i8* destination) -> ErrorOr<void> {
  257. u8 is_present = TRY(L(1));
  258. dbgln_if(WEBP_DEBUG, "{}_present {}", name, is_present);
  259. if (is_present) {
  260. i8 delta = TRY(L_signed(4));
  261. dbgln_if(WEBP_DEBUG, "{} {}", name, delta);
  262. *destination = delta;
  263. }
  264. return {};
  265. };
  266. TRY(read_delta("y_dc_delta"sv, &quantization_indices.y_dc_delta));
  267. TRY(read_delta("y2_dc_delta"sv, &quantization_indices.y2_dc_delta));
  268. TRY(read_delta("y2_ac_delta"sv, &quantization_indices.y2_ac_delta));
  269. TRY(read_delta("uv_dc_delta"sv, &quantization_indices.uv_dc_delta));
  270. TRY(read_delta("uv_ac_delta"sv, &quantization_indices.uv_ac_delta));
  271. return quantization_indices;
  272. }
  273. ErrorOr<LoopFilterAdjustment> decode_VP8_frame_header_loop_filter_adjustment(BooleanDecoder& decoder)
  274. {
  275. // Corresponds to "mb_lf_adjustments()" in section 19.2 of the spec.
  276. LoopFilterAdjustment adjustment;
  277. adjustment.enable_loop_filter_adjustment = TRY(L(1));
  278. if (adjustment.enable_loop_filter_adjustment) {
  279. u8 mode_ref_lf_delta_update = TRY(L(1));
  280. dbgln_if(WEBP_DEBUG, "mode_ref_lf_delta_update {}", mode_ref_lf_delta_update);
  281. if (mode_ref_lf_delta_update) {
  282. for (int i = 0; i < 4; ++i) {
  283. u8 ref_frame_delta_update_flag = TRY(L(1));
  284. dbgln_if(WEBP_DEBUG, "ref_frame_delta_update_flag {}", ref_frame_delta_update_flag);
  285. if (ref_frame_delta_update_flag) {
  286. i8 delta = TRY(L_signed(6));
  287. dbgln_if(WEBP_DEBUG, "delta {}", delta);
  288. adjustment.ref_frame_delta[i] = delta;
  289. }
  290. }
  291. for (int i = 0; i < 4; ++i) {
  292. u8 mb_mode_delta_update_flag = TRY(L(1));
  293. dbgln_if(WEBP_DEBUG, "mb_mode_delta_update_flag {}", mb_mode_delta_update_flag);
  294. if (mb_mode_delta_update_flag) {
  295. i8 delta = TRY(L_signed(6));
  296. dbgln_if(WEBP_DEBUG, "delta {}", delta);
  297. adjustment.mb_mode_delta[i] = delta;
  298. }
  299. }
  300. }
  301. }
  302. return adjustment;
  303. }
  304. ErrorOr<void> decode_VP8_frame_header_coefficient_probabilities(BooleanDecoder& decoder, CoefficientProbabilities coefficient_probabilities)
  305. {
  306. // Corresponds to "token_prob_update()" in section 19.2 of the spec.
  307. for (int i = 0; i < 4; i++) {
  308. for (int j = 0; j < 8; j++) {
  309. for (int k = 0; k < 3; k++) {
  310. for (int l = 0; l < 11; l++) {
  311. // token_prob_update() says L(1) and L(8), but it's actually B(p) and L(8).
  312. // https://datatracker.ietf.org/doc/html/rfc6386#section-13.4 "Token Probability Updates" describes it correctly.
  313. if (TRY(B(COEFFICIENT_UPDATE_PROBABILITIES[i][j][k][l])))
  314. coefficient_probabilities[i][j][k][l] = TRY(L(8));
  315. }
  316. }
  317. }
  318. }
  319. return {};
  320. }
  321. // https://datatracker.ietf.org/doc/html/rfc6386#section-8.1 "Tree Coding Implementation"
  322. ErrorOr<u8> tree_decode(BooleanDecoder& decoder, ReadonlySpan<TreeIndex> tree, ReadonlyBytes probabilities, TreeIndex initial_i = 0)
  323. {
  324. TreeIndex i = initial_i;
  325. while (true) {
  326. u8 b = TRY(B(probabilities[i >> 1]));
  327. i = tree[i + b];
  328. if (i <= 0)
  329. return -i;
  330. }
  331. }
  332. // Similar to BlockContext in LibVideo/VP9/Context.h
  333. struct MacroblockMetadata {
  334. // https://datatracker.ietf.org/doc/html/rfc6386#section-10 "Segment-Based Feature Adjustments"
  335. // Read only if `update_mb_segmentation_map` is set.
  336. int segment_id { 0 }; // 0, 1, 2, or 3. Fits in two bits.
  337. // https://datatracker.ietf.org/doc/html/rfc6386#section-11.1 "mb_skip_coeff"
  338. bool skip_coefficients { false };
  339. IntraMacroblockMode intra_y_mode;
  340. IntraMacroblockMode uv_mode;
  341. IntraBlockMode intra_b_modes[16];
  342. };
  343. ErrorOr<Vector<MacroblockMetadata>> decode_VP8_macroblock_metadata(BooleanDecoder& decoder, FrameHeader const& header, int macroblock_width, int macroblock_height)
  344. {
  345. // https://datatracker.ietf.org/doc/html/rfc6386#section-19.3
  346. // Corresponds to "macroblock_header()" in section 19.3 of the spec.
  347. Vector<MacroblockMetadata> macroblock_metadata;
  348. // Key frames must use intra prediction, that is new macroblocks are predicted from old macroblocks in the same frame.
  349. // (Inter prediction on the other hand predicts new macroblocks from the corresponding macroblock in the previous frame.)
  350. // https://datatracker.ietf.org/doc/html/rfc6386#section-11.3 "Subblock Mode Contexts"
  351. // "For macroblocks on the top row or left edge of the image, some of
  352. // the predictors will be non-existent. Such predictors are taken
  353. // to have had the value B_DC_PRED, which, perhaps conveniently,
  354. // takes the value 0 in the enumeration above.
  355. // A simple management scheme for these contexts might maintain a row
  356. // of above predictors and four left predictors. Before decoding the
  357. // frame, the entire row is initialized to B_DC_PRED; before decoding
  358. // each row of macroblocks, the four left predictors are also set to
  359. // B_DC_PRED. After decoding a macroblock, the bottom four subblock
  360. // modes are copied into the row predictor (at the current position,
  361. // which then advances to be above the next macroblock), and the
  362. // right four subblock modes are copied into the left predictor."
  363. Vector<IntraBlockMode> above;
  364. TRY(above.try_resize(macroblock_width * 4)); // One per 4x4 subblock.
  365. // It's possible to not decode all macroblock metadata at once. Instead, this could for example decode one row of metadata,
  366. // then decode the coefficients for one row of macroblocks, convert that row to pixels, and then go on to the next row of macroblocks.
  367. // That'd require slightly less memory. But MacroblockMetadata is fairly small, and this way we can keep the context
  368. // (`above`, `left`) in stack variables instead of having to have a class for that. So keep it simple for now.
  369. for (int mb_y = 0; mb_y < macroblock_height; ++mb_y) {
  370. IntraBlockMode left[4] {};
  371. for (int mb_x = 0; mb_x < macroblock_width; ++mb_x) {
  372. MacroblockMetadata metadata;
  373. if (header.segmentation.update_macroblock_segmentation_map)
  374. metadata.segment_id = TRY(tree_decode(decoder, MACROBLOCK_SEGMENT_TREE, header.segmentation.macroblock_segment_tree_probabilities));
  375. if (header.enable_skipping_of_macroblocks_containing_only_zero_coefficients)
  376. metadata.skip_coefficients = TRY(B(header.probability_skip_false));
  377. int intra_y_mode = TRY(tree_decode(decoder, KEYFRAME_YMODE_TREE, KEYFRAME_YMODE_PROBABILITIES));
  378. metadata.intra_y_mode = (IntraMacroblockMode)intra_y_mode;
  379. // "If the Ymode is B_PRED, it is followed by a (tree-coded) mode for each of the 16 Y subblocks."
  380. if (intra_y_mode == B_PRED) {
  381. for (int y = 0; y < 4; ++y) {
  382. for (int x = 0; x < 4; ++x) {
  383. // "The outer two dimensions of this array are indexed by the already-
  384. // coded subblock modes above and to the left of the current block,
  385. // respectively."
  386. int A = above[mb_x * 4 + x];
  387. int L = left[y];
  388. auto intra_b_mode = static_cast<IntraBlockMode>(TRY(tree_decode(decoder, BLOCK_MODE_TREE, KEYFRAME_BLOCK_MODE_PROBABILITIES[A][L])));
  389. metadata.intra_b_modes[y * 4 + x] = intra_b_mode;
  390. above[mb_x * 4 + x] = intra_b_mode;
  391. left[y] = intra_b_mode;
  392. }
  393. }
  394. } else {
  395. VERIFY(intra_y_mode < B_PRED);
  396. constexpr IntraBlockMode b_mode_from_y_mode[] = { B_DC_PRED, B_VE_PRED, B_HE_PRED, B_TM_PRED };
  397. IntraBlockMode intra_b_mode = b_mode_from_y_mode[intra_y_mode];
  398. for (int i = 0; i < 4; ++i) {
  399. above[mb_x * 4 + i] = intra_b_mode;
  400. left[i] = intra_b_mode;
  401. }
  402. }
  403. metadata.uv_mode = (IntraMacroblockMode)TRY(tree_decode(decoder, UV_MODE_TREE, KEYFRAME_UV_MODE_PROBABILITIES));
  404. TRY(macroblock_metadata.try_append(metadata));
  405. }
  406. }
  407. return macroblock_metadata;
  408. }
  409. // Every macroblock stores:
  410. // - One optional set of coefficients for Y2
  411. // - 16 sets of Y coefficients for the 4x4 Y subblocks of the macroblock
  412. // - 4 sets of U coefficients for the 2x2 U subblocks of the macroblock
  413. // - 4 sets of V coefficients for the 2x2 V subblocks of the macroblock
  414. // That's 24 or 25 sets of coefficients total. This struct identifies one of these sets by index.
  415. // If a macroblock does not have Y2, then i goes from [1..25], else it goes [0..25].
  416. struct CoefficientBlockIndex {
  417. int i;
  418. CoefficientBlockIndex(int i)
  419. : i(i)
  420. {
  421. VERIFY(i >= 0);
  422. VERIFY(i <= 25);
  423. }
  424. bool is_y2() const { return i == 0; }
  425. bool is_y() const { return i >= 1 && i <= 16; }
  426. bool is_u() const { return i >= 17 && i <= 20; }
  427. bool is_v() const { return i >= 21; }
  428. u8 sub_x() const
  429. {
  430. VERIFY(i > 0);
  431. if (i <= 16)
  432. return (i - 1) % 4;
  433. if (i <= 20)
  434. return (i - 17) % 2;
  435. return (i - 21) % 2;
  436. }
  437. u8 sub_y() const
  438. {
  439. VERIFY(i > 0);
  440. if (i <= 16)
  441. return (i - 1) / 4;
  442. if (i <= 20)
  443. return (i - 17) / 2;
  444. return (i - 21) / 2;
  445. }
  446. };
  447. int plane_index(CoefficientBlockIndex index, bool have_y2)
  448. {
  449. // https://datatracker.ietf.org/doc/html/rfc6386#section-13.3 "Token Probabilities"
  450. // "o 0 - Y beginning at coefficient 1 (i.e., Y after Y2)
  451. // o 1 - Y2
  452. // o 2 - U or V
  453. // o 3 - Y beginning at coefficient 0 (i.e., Y in the absence of Y2)."
  454. if (index.is_y2())
  455. return 1;
  456. if (index.is_u() || index.is_v())
  457. return 2;
  458. if (have_y2)
  459. return 0;
  460. return 3;
  461. }
  462. ErrorOr<i16> coefficient_value_for_token(BooleanDecoder& decoder, u8 token)
  463. {
  464. // Implements the second half of https://datatracker.ietf.org/doc/html/rfc6386#section-13.2 "Coding of Individual Coefficient Values"
  465. i16 v = static_cast<i16>(token); // For DCT_0 to DCT4
  466. if (token >= dct_cat1 && token <= dct_cat6) {
  467. static int constexpr starts[] = { 5, 7, 11, 19, 35, 67 };
  468. static int constexpr bits[] = { 1, 2, 3, 4, 5, 11 };
  469. static Prob constexpr Pcat1[] = { 159 };
  470. static Prob constexpr Pcat2[] = { 165, 145 };
  471. static Prob constexpr Pcat3[] = { 173, 148, 140 };
  472. static Prob constexpr Pcat4[] = { 176, 155, 140, 135 };
  473. static Prob constexpr Pcat5[] = { 180, 157, 141, 134, 130 };
  474. static Prob constexpr Pcat6[] = { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129 };
  475. static Prob const* const Pcats[] = { Pcat1, Pcat2, Pcat3, Pcat4, Pcat5, Pcat6 };
  476. v = 0;
  477. // This loop corresponds to `DCTextra` in the spec in section 13.2.
  478. for (int i = 0; i < bits[token - dct_cat1]; ++i)
  479. v = (v << 1) | TRY(decoder.read_bool(Pcats[token - dct_cat1][i]));
  480. v += starts[token - dct_cat1];
  481. }
  482. if (v) {
  483. if (TRY(decoder.read_bool(128)))
  484. v = -v;
  485. }
  486. return v;
  487. }
  488. i16 dequantize_value(i16 value, bool is_dc, QuantizationIndices const& quantization_indices, Segmentation const& segmentation, int segment_id, CoefficientBlockIndex index)
  489. {
  490. // https://datatracker.ietf.org/doc/html/rfc6386#section-9.6 "Dequantization Indices"
  491. // "before inverting the transform, each decoded coefficient
  492. // is multiplied by one of six dequantization factors, the choice of
  493. // which depends on the plane (Y, chroma = U or V, Y2) and coefficient
  494. // position (DC = coefficient 0, AC = coefficients 1-15). The six
  495. // values are specified using 7-bit indices into six corresponding fixed
  496. // tables (the tables are given in Section 14)."
  497. // Section 14 then lists two (!) fixed tables (which are in WebPLoaderLossyTables.h)
  498. // "Lookup values from the above two tables are directly used in the DC
  499. // and AC coefficients in Y1, respectively. For Y2 and chroma, values
  500. // from the above tables undergo either scaling or clamping before the
  501. // multiplies. Details regarding these scaling and clamping processes
  502. // can be found in related lookup functions in dixie.c (Section 20.4)."
  503. // Apparently spec writing became too much work at this point. In section 20.4, in dequant_init():
  504. // * For y2, the output (!) of dc_qlookup is multiplied by 2, the output of ac_qlookup is multiplied by 155 / 100
  505. // * Also for y2, ac_qlookup is at least 8 for lower table entries (XXX!)
  506. // * For uv, the dc_qlookup index is clamped to 117 (instead of 127 for everything else)
  507. // (or, alternatively, the value is clamped to 132 at most)
  508. u8 y_ac_base = quantization_indices.y_ac;
  509. if (segmentation.update_macroblock_segmentation_map) {
  510. if (segmentation.segment_feature_mode == SegmentFeatureMode::DeltaValueMode)
  511. y_ac_base += segmentation.quantizer_update_value[segment_id];
  512. else
  513. y_ac_base = segmentation.quantizer_update_value[segment_id];
  514. }
  515. u8 dequantization_index;
  516. if (index.is_y2())
  517. dequantization_index = y_ac_base + (is_dc ? quantization_indices.y2_dc_delta : quantization_indices.y2_ac_delta);
  518. else if (index.is_u() || index.is_v())
  519. dequantization_index = y_ac_base + (is_dc ? quantization_indices.uv_dc_delta : quantization_indices.uv_ac_delta);
  520. else
  521. dequantization_index = is_dc ? (y_ac_base + quantization_indices.y_dc_delta) : y_ac_base;
  522. // clamp index
  523. if ((index.is_u() || index.is_v()) && is_dc)
  524. dequantization_index = min(dequantization_index, 117);
  525. else
  526. dequantization_index = min(dequantization_index, 127);
  527. // "the multiplies are computed and stored using 16-bit signed integers."
  528. i16 dequantization_factor;
  529. if (is_dc)
  530. dequantization_factor = (i16)dc_qlookup[dequantization_index];
  531. else
  532. dequantization_factor = (i16)ac_qlookup[dequantization_index];
  533. if (index.is_y2()) {
  534. if (is_dc)
  535. dequantization_factor *= 2;
  536. else
  537. dequantization_factor = (dequantization_factor * 155) / 100;
  538. }
  539. return dequantization_factor * value;
  540. }
  541. // Reading macroblock coefficients requires needing to know if the block to the left and above the current macroblock
  542. // has non-zero coefficients. This stores that state.
  543. struct CoefficientReadingContext {
  544. // Store if each plane has nonzero coefficients in the block above and to the left of the current block.
  545. Vector<bool> y2_above;
  546. Vector<bool> y_above;
  547. Vector<bool> u_above;
  548. Vector<bool> v_above;
  549. bool y2_left {};
  550. bool y_left[4] {};
  551. bool u_left[2] {};
  552. bool v_left[2] {};
  553. ErrorOr<void> initialize(int macroblock_width)
  554. {
  555. TRY(y2_above.try_resize(macroblock_width));
  556. TRY(y_above.try_resize(macroblock_width * 4));
  557. TRY(u_above.try_resize(macroblock_width * 2));
  558. TRY(v_above.try_resize(macroblock_width * 2));
  559. return {};
  560. }
  561. void start_new_row()
  562. {
  563. y2_left = false;
  564. for (bool& b : y_left)
  565. b = false;
  566. for (bool& b : u_left)
  567. b = false;
  568. for (bool& b : v_left)
  569. b = false;
  570. }
  571. bool& was_above_nonzero(CoefficientBlockIndex index, int mb_x)
  572. {
  573. if (index.is_y2())
  574. return y2_above[mb_x];
  575. if (index.is_u())
  576. return u_above[mb_x * 2 + index.sub_x()];
  577. if (index.is_v())
  578. return v_above[mb_x * 2 + index.sub_x()];
  579. return y_above[mb_x * 4 + index.sub_x()];
  580. }
  581. bool was_above_nonzero(CoefficientBlockIndex index, int mb_x) const { return const_cast<CoefficientReadingContext&>(*this).was_above_nonzero(index, mb_x); }
  582. bool& was_left_nonzero(CoefficientBlockIndex index)
  583. {
  584. if (index.is_y2())
  585. return y2_left;
  586. if (index.is_u())
  587. return u_left[index.sub_y()];
  588. if (index.is_v())
  589. return v_left[index.sub_y()];
  590. return y_left[index.sub_y()];
  591. }
  592. bool was_left_nonzero(CoefficientBlockIndex index) const { return const_cast<CoefficientReadingContext&>(*this).was_left_nonzero(index); }
  593. void update(CoefficientBlockIndex index, int mb_x, bool subblock_has_nonzero_coefficients)
  594. {
  595. was_above_nonzero(index, mb_x) = subblock_has_nonzero_coefficients;
  596. was_left_nonzero(index) = subblock_has_nonzero_coefficients;
  597. }
  598. };
  599. using Coefficients = i16[16];
  600. // Returns if any non-zero coefficients were read.
  601. ErrorOr<bool> read_coefficent_block(BooleanDecoder& decoder, Coefficients out_coefficients, CoefficientBlockIndex block_index, CoefficientReadingContext& coefficient_reading_context, int mb_x, bool have_y2, int segment_id, FrameHeader const& header)
  602. {
  603. // Corresponds to `residual_block()` in https://datatracker.ietf.org/doc/html/rfc6386#section-19.3,
  604. // but also does dequantization of the stored values.
  605. // "firstCoeff is 1 for luma blocks of macroblocks containing Y2 subblock; otherwise 0"
  606. int firstCoeff = have_y2 && block_index.is_y() ? 1 : 0;
  607. i16 last_decoded_value = num_dct_tokens; // Start with an invalid value
  608. bool subblock_has_nonzero_coefficients = false;
  609. for (int j = firstCoeff; j < 16; ++j) {
  610. // https://datatracker.ietf.org/doc/html/rfc6386#section-13.2 "Coding of Individual Coefficient Values"
  611. // https://datatracker.ietf.org/doc/html/rfc6386#section-13.3 "Token Probabilities"
  612. // "Working from the outside in, the outermost dimension is indexed by
  613. // the type of plane being decoded"
  614. int plane = plane_index(block_index, have_y2);
  615. // "The next dimension is selected by the position of the coefficient
  616. // being decoded. That position, c, steps by ones up to 15, starting
  617. // from zero for block types 1, 2, or 3 and starting from one for block
  618. // type 0. The second array index is then"
  619. // "block type" here seems to refer to the "type of plane" in the previous paragraph.
  620. static int constexpr coeff_bands[16] = { 0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7 };
  621. int band = coeff_bands[j];
  622. // "The third dimension is the trickiest."
  623. int tricky = 0;
  624. // "For the first coefficient (DC, unless the block type is 0), we
  625. // consider the (already encoded) blocks within the same plane (Y2, Y,
  626. // U, or V) above and to the left of the current block. The context
  627. // index is then the number (0, 1, or 2) of these blocks that had at
  628. // least one non-zero coefficient in their residue record. Specifically
  629. // for Y2, because macroblocks above and to the left may or may not have
  630. // a Y2 block, the block above is determined by the most recent
  631. // macroblock in the same column that has a Y2 block, and the block to
  632. // the left is determined by the most recent macroblock in the same row
  633. // that has a Y2 block.
  634. // [...]
  635. // As with other contexts used by VP8, the "neighboring block" context
  636. // described here needs a special definition for subblocks lying along
  637. // the top row or left edge of the frame. These "non-existent"
  638. // predictors above and to the left of the image are simply taken to be
  639. // empty -- that is, taken to contain no non-zero coefficients."
  640. if (j == firstCoeff) {
  641. bool was_left_nonzero = coefficient_reading_context.was_left_nonzero(block_index);
  642. bool was_above_nonzero = coefficient_reading_context.was_above_nonzero(block_index, mb_x);
  643. tricky = static_cast<int>(was_left_nonzero) + static_cast<int>(was_above_nonzero);
  644. }
  645. // "Beyond the first coefficient, the context index is determined by the
  646. // absolute value of the most recently decoded coefficient (necessarily
  647. // within the current block) and is 0 if the last coefficient was a
  648. // zero, 1 if it was plus or minus one, and 2 if its absolute value
  649. // exceeded one."
  650. else {
  651. if (last_decoded_value == 0)
  652. tricky = 0;
  653. else if (last_decoded_value == 1 || last_decoded_value == -1)
  654. tricky = 1;
  655. else
  656. tricky = 2;
  657. }
  658. // "In general, all DCT coefficients are decoded using the same tree.
  659. // However, if the preceding coefficient is a DCT_0, decoding will skip
  660. // the first branch, since it is not possible for dct_eob to follow a
  661. // DCT_0."
  662. u8 token = TRY(tree_decode(decoder, COEFFICIENT_TREE, header.coefficient_probabilities[plane][band][tricky], last_decoded_value == DCT_0 ? 2 : 0));
  663. if (token == dct_eob)
  664. break;
  665. i16 v = TRY(coefficient_value_for_token(decoder, token));
  666. if (v) {
  667. // Subblock has non-0 coefficients. Store that, so that `tricky` on the next subblock is initialized correctly.
  668. subblock_has_nonzero_coefficients = true;
  669. }
  670. // last_decoded_value is used for setting `tricky`. It needs to be set to the last decoded token, not to the last dequantized value.
  671. last_decoded_value = v;
  672. i16 dequantized_value = dequantize_value(v, j == 0, header.quantization_indices, header.segmentation, segment_id, block_index);
  673. static int constexpr Zigzag[] = { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 };
  674. out_coefficients[Zigzag[j]] = dequantized_value;
  675. }
  676. return subblock_has_nonzero_coefficients;
  677. }
  678. struct MacroblockCoefficients {
  679. Coefficients y_coeffs[16] {};
  680. Coefficients u_coeffs[4] {};
  681. Coefficients v_coeffs[4] {};
  682. };
  683. ErrorOr<MacroblockCoefficients> read_macroblock_coefficients(BooleanDecoder& decoder, FrameHeader const& header, CoefficientReadingContext& coefficient_reading_context, MacroblockMetadata const& metadata, int mb_x)
  684. {
  685. // Corresponds to `residual_data()` in https://datatracker.ietf.org/doc/html/rfc6386#section-19.3,
  686. // but also does the inverse walsh-hadamard transform if a Y2 block is present.
  687. MacroblockCoefficients coefficients;
  688. Coefficients y2_coeffs {};
  689. // "firstCoeff is 1 for luma blocks of macroblocks containing Y2 subblock; otherwise 0"
  690. // https://datatracker.ietf.org/doc/html/rfc6386#section-13
  691. // "For all intra- and inter-prediction modes apart from B_PRED (intra:
  692. // whose Y subblocks are independently predicted) and SPLITMV (inter),
  693. // each macroblock's residue record begins with the Y2 component of the
  694. // residue, coded using a WHT. B_PRED and SPLITMV coded macroblocks
  695. // omit this WHT and specify the 0th DCT coefficient in each of the 16 Y
  696. // subblocks."
  697. bool have_y2 = metadata.intra_y_mode != B_PRED;
  698. // "for Y2, because macroblocks above and to the left may or may not have
  699. // a Y2 block, the block above is determined by the most recent
  700. // macroblock in the same column that has a Y2 block, and the block to
  701. // the left is determined by the most recent macroblock in the same row
  702. // that has a Y2 block."
  703. // We only write to y2_above / y2_left when it's present, so we don't need to do any explicit work to get the right behavior.
  704. // "After the optional Y2 block, the residue record continues with 16
  705. // DCTs for the Y subblocks, followed by 4 DCTs for the U subblocks,
  706. // ending with 4 DCTs for the V subblocks. The subblocks occur in the
  707. // usual order."
  708. /* (1 Y2)?, 16 Y, 4 U, 4 V */
  709. for (int i = have_y2 ? 0 : 1; i < 25; ++i) {
  710. CoefficientBlockIndex block_index { i };
  711. bool subblock_has_nonzero_coefficients = false;
  712. if (!metadata.skip_coefficients) {
  713. i16* to_read;
  714. if (block_index.is_y2())
  715. to_read = y2_coeffs;
  716. else if (block_index.is_u())
  717. to_read = coefficients.u_coeffs[i - 17];
  718. else if (block_index.is_v())
  719. to_read = coefficients.v_coeffs[i - 21];
  720. else // Y
  721. to_read = coefficients.y_coeffs[i - 1];
  722. subblock_has_nonzero_coefficients = TRY(read_coefficent_block(decoder, to_read, block_index, coefficient_reading_context, mb_x, have_y2, metadata.segment_id, header));
  723. }
  724. coefficient_reading_context.update(block_index, mb_x, subblock_has_nonzero_coefficients);
  725. }
  726. // https://datatracker.ietf.org/doc/html/rfc6386#section-14.2 "Inverse Transforms"
  727. // "If the Y2 residue block exists (i.e., the macroblock luma mode is not
  728. // SPLITMV or B_PRED), it is inverted first (using the inverse WHT) and
  729. // the element of the result at row i, column j is used as the 0th
  730. // coefficient of the Y subblock at position (i, j), that is, the Y
  731. // subblock whose index is (i * 4) + j."
  732. if (have_y2) {
  733. Coefficients wht_output;
  734. vp8_short_inv_walsh4x4_c(y2_coeffs, wht_output);
  735. for (size_t i = 0; i < 16; ++i)
  736. coefficients.y_coeffs[i][0] = wht_output[i];
  737. }
  738. return coefficients;
  739. }
  740. template<int N>
  741. void predict_macroblock(Span<i16> prediction, IntraMacroblockMode mode, int mb_x, int mb_y, ReadonlySpan<i16> left, ReadonlySpan<i16> above, i16 truemotion_corner)
  742. {
  743. // https://datatracker.ietf.org/doc/html/rfc6386#section-12.2 "Chroma Prediction"
  744. // (Also used for the DC_PRED, H_PRED, V_PRED, TM_PRED for luma prediction.)
  745. if (mode == DC_PRED) {
  746. if (mb_x == 0 && mb_y == 0) {
  747. for (size_t i = 0; i < N * N; ++i)
  748. prediction[i] = 128;
  749. } else {
  750. int sum = 0, n = 0;
  751. if (mb_x > 0) {
  752. for (int i = 0; i < N; ++i)
  753. sum += left[i];
  754. n += N;
  755. }
  756. if (mb_y > 0) {
  757. for (int i = 0; i < N; ++i)
  758. sum += above[mb_x * N + i];
  759. n += N;
  760. }
  761. i16 average = (sum + n / 2) / n;
  762. for (size_t i = 0; i < N * N; ++i)
  763. prediction[i] = average;
  764. }
  765. } else if (mode == H_PRED) {
  766. for (int y = 0; y < N; ++y)
  767. for (int x = 0; x < N; ++x)
  768. prediction[y * N + x] = left[y];
  769. } else if (mode == V_PRED) {
  770. for (int y = 0; y < N; ++y)
  771. for (int x = 0; x < N; ++x)
  772. prediction[y * N + x] = above[mb_x * N + x];
  773. } else {
  774. VERIFY(mode == TM_PRED);
  775. for (int y = 0; y < N; ++y)
  776. for (int x = 0; x < N; ++x)
  777. prediction[y * N + x] = left[y] + above[mb_x * N + x] - truemotion_corner;
  778. }
  779. }
  780. void predict_y_subblock(Span<i16> y_prediction, IntraBlockMode mode, int x, int y, ReadonlySpan<i16> left, ReadonlySpan<i16> above, i16 corner)
  781. {
  782. // https://datatracker.ietf.org/doc/html/rfc6386#section-12.3 "Luma Prediction"
  783. // Roughly corresponds to "subblock_intra_predict()" in the spec.
  784. auto weighted_average = [](i16 x, i16 y, i16 z) { return (x + 2 * y + z + 2) / 4; };
  785. auto average = [](i16 x, i16 y) { return (x + y + 1) / 2; };
  786. auto at = [&y_prediction, y, x](int px, int py) -> i16& { return y_prediction[(4 * y + py) * 16 + 4 * x + px]; };
  787. if (mode == B_DC_PRED) {
  788. // XXX spec text says this is like DC_PRED but predict_dc_nxn() in the sample impl looks like it doesn't do the "oob isn't read" part. what's right?
  789. // DC16NoTopLeft_C vs DC4_C in libwebp dec.c / common_dec.h suggests the spec text is incomplete :/
  790. int sum = 0, n = 8;
  791. for (int i = 0; i < 4; ++i)
  792. sum += left[i] + above[i];
  793. i16 average = (sum + n / 2) / n;
  794. for (int py = 0; py < 4; ++py)
  795. for (int px = 0; px < 4; ++px)
  796. y_prediction[(4 * y + py) * 16 + 4 * x + px] = average;
  797. } else if (mode == B_TM_PRED) {
  798. for (int py = 0; py < 4; ++py)
  799. for (int px = 0; px < 4; ++px)
  800. y_prediction[(4 * y + py) * 16 + 4 * x + px] = clamp(left[py] + above[px] - corner, 0, 255);
  801. } else if (mode == B_VE_PRED) {
  802. for (int py = 0; py < 4; ++py)
  803. for (int px = 0; px < 4; ++px) {
  804. auto top_left = (px > 0 ? above[px - 1] : corner);
  805. y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(top_left, above[px], above[px + 1]);
  806. }
  807. } else if (mode == B_HE_PRED) {
  808. for (int py = 0; py < 4; ++py)
  809. for (int px = 0; px < 4; ++px) {
  810. if (py == 0) {
  811. y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(corner, left[py], left[py + 1]);
  812. } else if (py == 3) {
  813. /* Bottom row is exceptional because L[4] does not exist */
  814. y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(left[2], left[3], left[3]);
  815. } else {
  816. y_prediction[(4 * y + py) * 16 + 4 * x + px] = weighted_average(left[py - 1], left[py], left[py + 1]);
  817. }
  818. }
  819. } else if (mode == B_LD_PRED) {
  820. // this is 45-deg prediction from above, going left-down (i.e. isochromes on -1/+1 diags)
  821. at(0, 0) = weighted_average(above[0], above[1], above[2]);
  822. at(0, 1) = at(1, 0) = weighted_average(above[1], above[2], above[3]);
  823. at(0, 2) = at(1, 1) = at(2, 0) = weighted_average(above[2], above[3], above[4]);
  824. at(0, 3) = at(1, 2) = at(2, 1) = at(3, 0) = weighted_average(above[3], above[4], above[5]);
  825. at(1, 3) = at(2, 2) = at(3, 1) = weighted_average(above[4], above[5], above[6]);
  826. at(2, 3) = at(3, 2) = weighted_average(above[5], above[6], above[7]);
  827. at(3, 3) = weighted_average(above[6], above[7], above[7]); // intentionally 6, 7, 7
  828. } else if (mode == B_RD_PRED) {
  829. // this is 45-deg prediction from above / left, going right-down (i.e. isochromes on +1/+1 diags)
  830. at(0, 3) = weighted_average(left[3], left[2], left[1]);
  831. at(0, 2) = at(1, 3) = weighted_average(left[2], left[1], left[0]);
  832. at(0, 1) = at(1, 2) = at(2, 3) = weighted_average(left[1], left[0], corner);
  833. at(0, 0) = at(1, 1) = at(2, 2) = at(3, 3) = weighted_average(left[0], corner, above[0]);
  834. at(1, 0) = at(2, 1) = at(3, 2) = weighted_average(corner, above[0], above[1]);
  835. at(2, 0) = at(3, 1) = weighted_average(above[0], above[1], above[2]);
  836. at(3, 0) = weighted_average(above[1], above[2], above[3]);
  837. } else if (mode == B_VR_PRED) {
  838. // this is 22.5-deg prediction
  839. at(0, 3) = weighted_average(left[2], left[1], left[0]);
  840. at(0, 2) = weighted_average(left[1], left[0], corner);
  841. at(1, 3) = at(0, 1) = weighted_average(left[0], corner, above[0]);
  842. at(1, 2) = at(0, 0) = average(corner, above[0]);
  843. at(2, 3) = at(1, 1) = weighted_average(corner, above[0], above[1]);
  844. at(2, 2) = at(1, 0) = average(above[0], above[1]);
  845. at(3, 3) = at(2, 1) = weighted_average(above[0], above[1], above[2]);
  846. at(3, 2) = at(2, 0) = average(above[1], above[2]);
  847. at(3, 1) = weighted_average(above[1], above[2], above[3]);
  848. at(3, 0) = average(above[2], above[3]);
  849. } else if (mode == B_VL_PRED) {
  850. // this is 22.5-deg prediction
  851. at(0, 0) = average(above[0], above[1]);
  852. at(0, 1) = weighted_average(above[0], above[1], above[2]);
  853. at(0, 2) = at(1, 0) = average(above[1], above[2]);
  854. at(1, 1) = at(0, 3) = weighted_average(above[1], above[2], above[3]);
  855. at(1, 2) = at(2, 0) = average(above[2], above[3]);
  856. at(1, 3) = at(2, 1) = weighted_average(above[2], above[3], above[4]);
  857. at(2, 2) = at(3, 0) = average(above[3], above[4]);
  858. at(2, 3) = at(3, 1) = weighted_average(above[3], above[4], above[5]);
  859. /* Last two values do not strictly follow the pattern. */
  860. at(3, 2) = weighted_average(above[4], above[5], above[6]);
  861. at(3, 3) = weighted_average(above[5], above[6], above[7]);
  862. } else if (mode == B_HD_PRED) {
  863. // this is 22.5-deg prediction
  864. at(0, 3) = average(left[3], left[2]);
  865. at(1, 3) = weighted_average(left[3], left[2], left[1]);
  866. at(0, 2) = at(2, 3) = average(left[2], left[1]);
  867. at(1, 2) = at(3, 3) = weighted_average(left[2], left[1], left[0]);
  868. at(2, 2) = at(0, 1) = average(left[1], left[0]);
  869. at(3, 2) = at(1, 1) = weighted_average(left[1], left[0], corner);
  870. at(2, 1) = at(0, 0) = average(left[0], corner);
  871. at(3, 1) = at(1, 0) = weighted_average(left[0], corner, above[0]);
  872. at(2, 0) = weighted_average(corner, above[0], above[1]);
  873. at(3, 0) = weighted_average(above[0], above[1], above[2]);
  874. } else {
  875. VERIFY(mode == B_HU_PRED);
  876. // this is 22.5-deg prediction
  877. at(0, 0) = average(left[0], left[1]);
  878. at(1, 0) = weighted_average(left[0], left[1], left[2]);
  879. at(2, 0) = at(0, 1) = average(left[1], left[2]);
  880. at(3, 0) = at(1, 1) = weighted_average(left[1], left[2], left[3]);
  881. at(2, 1) = at(0, 2) = average(left[2], left[3]);
  882. at(3, 1) = at(1, 2) = weighted_average(left[2], left[3], left[3]); // Intentionally 2, 3, 3
  883. /* Not possible to follow pattern for much of the bottom
  884. row because no (nearby) already-constructed pixels lie
  885. on the diagonals in question. */
  886. at(2, 2) = at(3, 2) = at(0, 3) = at(1, 3) = at(2, 3) = at(3, 3) = left[3];
  887. }
  888. }
  889. template<int N>
  890. void add_idct_to_prediction(Span<i16> prediction, Coefficients coefficients, int x, int y)
  891. {
  892. Coefficients idct_output;
  893. short_idct4x4llm_c(coefficients, idct_output, 4 * sizeof(i16));
  894. // https://datatracker.ietf.org/doc/html/rfc6386#section-14.5 "Summation of Predictor and Residue"
  895. for (int py = 0; py < 4; ++py) { // Loop over 4x4 pixels in subblock
  896. for (int px = 0; px < 4; ++px) {
  897. // sum with prediction
  898. i16& p = prediction[(4 * y + py) * N + (4 * x + px)];
  899. p += idct_output[py * 4 + px];
  900. // p = clamp(p, 0, 255);
  901. }
  902. }
  903. }
  904. template<int N>
  905. void process_macroblock(Span<i16> output, IntraMacroblockMode mode, int mb_x, int mb_y, ReadonlySpan<i16> left, ReadonlySpan<i16> above, i16 truemotion_corner, Coefficients coefficients_array[])
  906. {
  907. predict_macroblock<4 * N>(output, mode, mb_x, mb_y, left, above, truemotion_corner);
  908. // https://datatracker.ietf.org/doc/html/rfc6386#section-14.4 "Implementation of the DCT Inversion"
  909. // Loop over the 4x4 subblocks
  910. for (int y = 0, i = 0; y < N; ++y)
  911. for (int x = 0; x < N; ++x, ++i)
  912. add_idct_to_prediction<4 * N>(output, coefficients_array[i], x, y);
  913. }
  914. void process_subblocks(Span<i16> y_output, MacroblockMetadata const& metadata, int mb_x, int mb_y, ReadonlySpan<i16> predicted_y_left, ReadonlySpan<i16> predicted_y_above, i16 y_truemotion_corner, Coefficients coefficients_array[], int macroblock_width)
  915. {
  916. // Loop over the 4x4 subblocks
  917. for (int y = 0, i = 0; y < 4; ++y) {
  918. for (int x = 0; x < 4; ++x, ++i) {
  919. i16 corner = y_truemotion_corner;
  920. if (x > 0 && y == 0)
  921. corner = predicted_y_above[mb_x * 16 + 4 * x - 1];
  922. else if (x > 0 && y > 0)
  923. corner = y_output[(4 * y - 1) * 16 + 4 * x - 1];
  924. else if (x == 0 && y > 0)
  925. corner = predicted_y_left[4 * y - 1];
  926. i16 left[4], above[8];
  927. for (int i = 0; i < 4; ++i) {
  928. if (x == 0)
  929. left[i] = predicted_y_left[4 * y + i];
  930. else
  931. left[i] = y_output[(4 * y + i) * 16 + 4 * x - 1];
  932. }
  933. // Subblock prediction can read 8 pixels above the block.
  934. // For rightmost subblocks, the right 4 pixels there aren't initialized yet, so those get the 4 pixels to the right above the macroblock.
  935. // For the rightmost macroblock, there's no macroblock to its right, so there they get the rightmost pixel above.
  936. // But in the 0th row, there's no pixel above, so there they become 127.
  937. for (int i = 0; i < 8; ++i) {
  938. if (x == 3 && i >= 4) { // rightmost subblock, 4 right pixels?
  939. if (mb_x == macroblock_width - 1) { // rightmost macroblock
  940. if (mb_y == 0) { // topmost macroblock row
  941. above[i] = 127;
  942. } else {
  943. above[i] = predicted_y_above[mb_x * 16 + 4 * x + 3];
  944. }
  945. } else {
  946. above[i] = predicted_y_above[mb_x * 16 + 4 * x + i];
  947. }
  948. } else if (y == 0) {
  949. above[i] = predicted_y_above[mb_x * 16 + 4 * x + i];
  950. } else {
  951. above[i] = y_output[(4 * y - 1) * 16 + 4 * x + i];
  952. }
  953. }
  954. predict_y_subblock(y_output, metadata.intra_b_modes[y * 4 + x], x, y, left, above, corner);
  955. // Have to do IDCT summation here, since its results affect prediction of next subblock already.
  956. add_idct_to_prediction<16>(y_output, coefficients_array[4 * y + x], x, y);
  957. }
  958. }
  959. }
  960. void convert_yuv_to_rgb(Bitmap& bitmap, int mb_x, int mb_y, ReadonlySpan<i16> y_data, ReadonlySpan<i16> u_data, ReadonlySpan<i16> v_data)
  961. {
  962. // Convert YUV to RGB.
  963. for (int y = 0; y < 16; ++y) {
  964. for (int x = 0; x < 16; ++x) {
  965. // "is then saturated to 8-bit unsigned range (using, say, the
  966. // clamp255 function defined above) before being stored as an 8-bit
  967. // unsigned pixel value."
  968. u8 Y = clamp(y_data[y * 16 + x], 0, 255);
  969. // FIXME: Could do nicer upsampling than just nearest neighbor
  970. u8 U = clamp(u_data[(y / 2) * 8 + x / 2], 0, 255);
  971. u8 V = clamp(v_data[(y / 2) * 8 + x / 2], 0, 255);
  972. // XXX: These numbers are from the fixed-point values in libwebp's yuv.h. There's probably a better reference somewhere.
  973. int r = 1.1655 * Y + 1.596 * V - 222.4;
  974. int g = 1.1655 * Y - 0.3917 * U - 0.8129 * V + 136.0625;
  975. int b = 1.1655 * Y + 2.0172 * U - 276.33;
  976. bitmap.scanline(mb_y * 16 + y)[mb_x * 16 + x] = Color(clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255)).value();
  977. }
  978. }
  979. }
  980. ErrorOr<void> decode_VP8_image_data(Gfx::Bitmap& bitmap, FrameHeader const& header, ReadonlyBytes data, int macroblock_width, int macroblock_height, Vector<MacroblockMetadata> const& macroblock_metadata)
  981. {
  982. FixedMemoryStream memory_stream { data };
  983. BigEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream) };
  984. auto decoder = TRY(BooleanDecoder::initialize(MaybeOwned { bit_stream }, data.size() * 8));
  985. CoefficientReadingContext coefficient_reading_context;
  986. TRY(coefficient_reading_context.initialize(macroblock_width));
  987. Vector<i16> predicted_y_above;
  988. TRY(predicted_y_above.try_resize(macroblock_width * 16));
  989. for (size_t i = 0; i < predicted_y_above.size(); ++i)
  990. predicted_y_above[i] = 127;
  991. Vector<i16> predicted_u_above;
  992. TRY(predicted_u_above.try_resize(macroblock_width * 8));
  993. for (size_t i = 0; i < predicted_u_above.size(); ++i)
  994. predicted_u_above[i] = 127;
  995. Vector<i16> predicted_v_above;
  996. TRY(predicted_v_above.try_resize(macroblock_width * 8));
  997. for (size_t i = 0; i < predicted_v_above.size(); ++i)
  998. predicted_v_above[i] = 127;
  999. for (int mb_y = 0, macroblock_index = 0; mb_y < macroblock_height; ++mb_y) {
  1000. coefficient_reading_context.start_new_row();
  1001. i16 predicted_y_left[16] { 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129 };
  1002. i16 predicted_u_left[8] { 129, 129, 129, 129, 129, 129, 129, 129 };
  1003. i16 predicted_v_left[8] { 129, 129, 129, 129, 129, 129, 129, 129 };
  1004. // The spec doesn't say if this should be 127, 129, or something else.
  1005. // But ReconstructRow in frame_dec.c in libwebp suggests 129.
  1006. i16 y_truemotion_corner = 129;
  1007. i16 u_truemotion_corner = 129;
  1008. i16 v_truemotion_corner = 129;
  1009. for (int mb_x = 0; mb_x < macroblock_width; ++mb_x, ++macroblock_index) {
  1010. auto const& metadata = macroblock_metadata[macroblock_index];
  1011. auto coefficients = TRY(read_macroblock_coefficients(decoder, header, coefficient_reading_context, metadata, mb_x));
  1012. i16 y_data[16 * 16] {};
  1013. if (metadata.intra_y_mode == B_PRED)
  1014. process_subblocks(y_data, metadata, mb_x, mb_y, predicted_y_left, predicted_y_above, y_truemotion_corner, coefficients.y_coeffs, macroblock_width);
  1015. else
  1016. process_macroblock<4>(y_data, metadata.intra_y_mode, mb_x, mb_y, predicted_y_left, predicted_y_above, y_truemotion_corner, coefficients.y_coeffs);
  1017. i16 u_data[8 * 8] {};
  1018. process_macroblock<2>(u_data, metadata.uv_mode, mb_x, mb_y, predicted_u_left, predicted_u_above, u_truemotion_corner, coefficients.u_coeffs);
  1019. i16 v_data[8 * 8] {};
  1020. process_macroblock<2>(v_data, metadata.uv_mode, mb_x, mb_y, predicted_v_left, predicted_v_above, v_truemotion_corner, coefficients.v_coeffs);
  1021. // FIXME: insert loop filtering here
  1022. convert_yuv_to_rgb(bitmap, mb_x, mb_y, y_data, u_data, v_data);
  1023. y_truemotion_corner = predicted_y_above[mb_x * 16 + 15];
  1024. for (int i = 0; i < 16; ++i)
  1025. predicted_y_left[i] = y_data[15 + i * 16];
  1026. for (int i = 0; i < 16; ++i)
  1027. predicted_y_above[mb_x * 16 + i] = y_data[15 * 16 + i];
  1028. u_truemotion_corner = predicted_u_above[mb_x * 8 + 7];
  1029. for (int i = 0; i < 8; ++i)
  1030. predicted_u_left[i] = u_data[7 + i * 8];
  1031. for (int i = 0; i < 8; ++i)
  1032. predicted_u_above[mb_x * 8 + i] = u_data[7 * 8 + i];
  1033. v_truemotion_corner = predicted_v_above[mb_x * 8 + 7];
  1034. for (int i = 0; i < 8; ++i)
  1035. predicted_v_left[i] = v_data[7 + i * 8];
  1036. for (int i = 0; i < 8; ++i)
  1037. predicted_v_above[mb_x * 8 + i] = v_data[7 * 8 + i];
  1038. }
  1039. }
  1040. return {};
  1041. }
  1042. }
  1043. ErrorOr<NonnullRefPtr<Bitmap>> decode_webp_chunk_VP8_contents(VP8Header const& vp8_header, bool include_alpha_channel)
  1044. {
  1045. // The first partition stores header, per-segment state, and macroblock metadata.
  1046. FixedMemoryStream memory_stream { vp8_header.first_partition };
  1047. BigEndianInputBitStream bit_stream { MaybeOwned<Stream>(memory_stream) };
  1048. auto decoder = TRY(BooleanDecoder::initialize(MaybeOwned { bit_stream }, vp8_header.first_partition.size() * 8));
  1049. auto header = TRY(decode_VP8_frame_header(decoder));
  1050. // https://datatracker.ietf.org/doc/html/rfc6386#section-2 "Format Overview"
  1051. // "Internally, VP8 decomposes each output frame into an array of
  1052. // macroblocks. A macroblock is a square array of pixels whose Y
  1053. // dimensions are 16x16 and whose U and V dimensions are 8x8."
  1054. int macroblock_width = ceil_div(vp8_header.width, 16);
  1055. int macroblock_height = ceil_div(vp8_header.height, 16);
  1056. auto macroblock_metadata = TRY(decode_VP8_macroblock_metadata(decoder, header, macroblock_width, macroblock_height));
  1057. // Done with the first partition!
  1058. if (header.number_of_dct_partitions > 1)
  1059. return Error::from_string_literal("WebPImageDecoderPlugin: decoding lossy webps with more than one dct partition not yet implemented");
  1060. auto bitmap_format = include_alpha_channel ? BitmapFormat::BGRA8888 : BitmapFormat::BGRx8888;
  1061. auto bitmap = TRY(Bitmap::create(bitmap_format, { macroblock_width * 16, macroblock_height * 16 }));
  1062. TRY(decode_VP8_image_data(*bitmap, header, vp8_header.second_partition, macroblock_width, macroblock_height, macroblock_metadata));
  1063. auto width = static_cast<int>(vp8_header.width);
  1064. auto height = static_cast<int>(vp8_header.height);
  1065. if (bitmap->physical_size() == IntSize { width, height })
  1066. return bitmap;
  1067. return bitmap->cropped({ 0, 0, width, height });
  1068. }
  1069. }