WebPLoaderLossy.cpp 59 KB

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