Parser.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. /*
  2. * Copyright (c) 2021, Hunter Salyer <thefalsehonesty@gmail.com>
  3. * Copyright (c) 2022, Gregory Bertilson <zaggy1024@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/String.h>
  8. #include <LibGfx/Point.h>
  9. #include <LibGfx/Size.h>
  10. #include "Decoder.h"
  11. #include "Parser.h"
  12. #include "Utilities.h"
  13. #if defined(AK_COMPILER_GCC)
  14. # pragma GCC optimize("O3")
  15. #endif
  16. namespace Video::VP9 {
  17. #define TRY_READ(expression) DECODER_TRY(DecoderErrorCategory::Corrupted, expression)
  18. Parser::Parser(Decoder& decoder)
  19. : m_probability_tables(make<ProbabilityTables>())
  20. , m_decoder(decoder)
  21. {
  22. }
  23. Parser::~Parser()
  24. {
  25. }
  26. Vector<size_t> Parser::parse_superframe_sizes(ReadonlyBytes frame_data)
  27. {
  28. if (frame_data.size() < 1)
  29. return {};
  30. // The decoder determines the presence of a superframe by:
  31. // 1. parsing the final byte of the chunk and checking that the superframe_marker equals 0b110,
  32. // If the checks in steps 1 and 3 both pass, then the chunk is determined to contain a superframe and each
  33. // frame in the superframe is passed to the decoding process in turn.
  34. // Otherwise, the chunk is determined to not contain a superframe, and the whole chunk is passed to the
  35. // decoding process.
  36. // NOTE: Reading from span data will be quicker than spinning up a BitStream.
  37. u8 superframe_byte = frame_data[frame_data.size() - 1];
  38. // NOTE: We have to read out of the byte from the little end first, hence the padding bits in the masks below.
  39. u8 superframe_marker = superframe_byte & 0b1110'0000;
  40. if (superframe_marker == 0b1100'0000) {
  41. u8 bytes_per_framesize = ((superframe_byte >> 3) & 0b11) + 1;
  42. u8 frames_in_superframe = (superframe_byte & 0b111) + 1;
  43. // 2. setting the total size of the superframe_index SzIndex equal to 2 + NumFrames * SzBytes,
  44. size_t index_size = 2 + bytes_per_framesize * frames_in_superframe;
  45. if (index_size > frame_data.size())
  46. return {};
  47. auto superframe_header_data = frame_data.data() + frame_data.size() - index_size;
  48. u8 start_superframe_byte = *(superframe_header_data++);
  49. // 3. checking that the first byte of the superframe_index matches the final byte.
  50. if (superframe_byte != start_superframe_byte)
  51. return {};
  52. Vector<size_t> result;
  53. for (u8 i = 0; i < frames_in_superframe; i++) {
  54. size_t frame_size = 0;
  55. for (u8 j = 0; j < bytes_per_framesize; j++)
  56. frame_size |= (static_cast<size_t>(*(superframe_header_data++)) << (j * 8));
  57. result.append(frame_size);
  58. }
  59. return result;
  60. }
  61. return {};
  62. }
  63. /* (6.1) */
  64. DecoderErrorOr<FrameContext> Parser::parse_frame(ReadonlyBytes frame_data)
  65. {
  66. m_bit_stream = make<BitStream>(frame_data.data(), frame_data.size());
  67. m_syntax_element_counter = make<SyntaxElementCounter>();
  68. auto frame_context = TRY(uncompressed_header());
  69. if (!trailing_bits())
  70. return DecoderError::corrupted("Trailing bits were non-zero"sv);
  71. // FIXME: This should not be an error. Spec says that we consume padding bits until the end of the sample.
  72. if (frame_context.header_size_in_bytes == 0)
  73. return DecoderError::corrupted("Frame header is zero-sized"sv);
  74. m_probability_tables->load_probs(frame_context.probability_context_index);
  75. m_probability_tables->load_probs2(frame_context.probability_context_index);
  76. m_syntax_element_counter->clear_counts();
  77. TRY_READ(m_bit_stream->init_bool(frame_context.header_size_in_bytes));
  78. TRY(compressed_header(frame_context));
  79. TRY_READ(m_bit_stream->exit_bool());
  80. TRY(m_decoder.allocate_buffers(frame_context));
  81. TRY(decode_tiles(frame_context));
  82. TRY(refresh_probs(frame_context));
  83. m_previous_frame_type = frame_context.type;
  84. m_previous_frame_size = frame_context.size();
  85. m_previous_show_frame = frame_context.shows_a_frame();
  86. m_previous_color_config = frame_context.color_config;
  87. m_previous_loop_filter_ref_deltas = frame_context.loop_filter_reference_deltas;
  88. m_previous_loop_filter_mode_deltas = frame_context.loop_filter_mode_deltas;
  89. return frame_context;
  90. }
  91. bool Parser::trailing_bits()
  92. {
  93. while (m_bit_stream->bits_remaining() & 7u) {
  94. if (MUST(m_bit_stream->read_bit()))
  95. return false;
  96. }
  97. return true;
  98. }
  99. DecoderErrorOr<void> Parser::refresh_probs(FrameContext const& frame_context)
  100. {
  101. if (!frame_context.error_resilient_mode && !frame_context.parallel_decoding_mode) {
  102. m_probability_tables->load_probs(frame_context.probability_context_index);
  103. TRY(m_decoder.adapt_coef_probs(frame_context.is_inter_predicted()));
  104. if (frame_context.is_inter_predicted()) {
  105. m_probability_tables->load_probs2(frame_context.probability_context_index);
  106. TRY(m_decoder.adapt_non_coef_probs(frame_context));
  107. }
  108. }
  109. if (frame_context.should_replace_probability_context)
  110. m_probability_tables->save_probs(frame_context.probability_context_index);
  111. return {};
  112. }
  113. DecoderErrorOr<ColorRange> Parser::read_color_range()
  114. {
  115. if (TRY_READ(m_bit_stream->read_bit()))
  116. return ColorRange::Full;
  117. return ColorRange::Studio;
  118. }
  119. /* (6.2) */
  120. DecoderErrorOr<FrameContext> Parser::uncompressed_header()
  121. {
  122. // NOTE: m_reusable_frame_block_contexts does not need to retain any data between frame decodes.
  123. // This is only stored so that we don't need to allocate a frame's block contexts on each
  124. // call to this function, since it will rarely change sizes.
  125. FrameContext frame_context { m_reusable_frame_block_contexts };
  126. frame_context.color_config = m_previous_color_config;
  127. auto frame_marker = TRY_READ(m_bit_stream->read_bits(2));
  128. if (frame_marker != 2)
  129. return DecoderError::corrupted("uncompressed_header: Frame marker must be 2"sv);
  130. auto profile_low_bit = TRY_READ(m_bit_stream->read_bit());
  131. auto profile_high_bit = TRY_READ(m_bit_stream->read_bit());
  132. frame_context.profile = (profile_high_bit << 1u) + profile_low_bit;
  133. if (frame_context.profile == 3 && TRY_READ(m_bit_stream->read_bit()))
  134. return DecoderError::corrupted("uncompressed_header: Profile 3 reserved bit was non-zero"sv);
  135. if (TRY_READ(m_bit_stream->read_bit())) {
  136. frame_context.set_existing_frame_to_show(TRY_READ(m_bit_stream->read_bits(3)));
  137. return frame_context;
  138. }
  139. bool is_keyframe = !TRY_READ(m_bit_stream->read_bit());
  140. if (!TRY_READ(m_bit_stream->read_bit()))
  141. frame_context.set_frame_hidden();
  142. frame_context.error_resilient_mode = TRY_READ(m_bit_stream->read_bit());
  143. FrameType type;
  144. Gfx::Size<u32> frame_size;
  145. Gfx::Size<u32> render_size;
  146. u8 reference_frames_to_update_flags = 0xFF; // Save frame to all reference indices by default.
  147. enum class ResetProbabilities : u8 {
  148. No = 0,
  149. // 1 also means No here, but we don't need to do anything with the No case.
  150. OnlyCurrent = 2,
  151. All = 3,
  152. };
  153. ResetProbabilities reset_frame_context = ResetProbabilities::All;
  154. if (is_keyframe) {
  155. type = FrameType::KeyFrame;
  156. TRY(frame_sync_code());
  157. frame_context.color_config = TRY(parse_color_config(frame_context));
  158. frame_size = TRY(parse_frame_size());
  159. render_size = TRY(parse_render_size(frame_size));
  160. } else {
  161. if (!frame_context.shows_a_frame() && TRY_READ(m_bit_stream->read_bit())) {
  162. type = FrameType::IntraOnlyFrame;
  163. } else {
  164. type = FrameType::InterFrame;
  165. reset_frame_context = ResetProbabilities::No;
  166. }
  167. if (!frame_context.error_resilient_mode)
  168. reset_frame_context = static_cast<ResetProbabilities>(TRY_READ(m_bit_stream->read_bits(2)));
  169. if (type == FrameType::IntraOnlyFrame) {
  170. TRY(frame_sync_code());
  171. frame_context.color_config = frame_context.profile > 0 ? TRY(parse_color_config(frame_context)) : ColorConfig();
  172. reference_frames_to_update_flags = TRY_READ(m_bit_stream->read_f8());
  173. frame_size = TRY(parse_frame_size());
  174. render_size = TRY(parse_render_size(frame_size));
  175. } else {
  176. reference_frames_to_update_flags = TRY_READ(m_bit_stream->read_f8());
  177. for (auto i = 0; i < 3; i++) {
  178. frame_context.reference_frame_indices[i] = TRY_READ(m_bit_stream->read_bits(3));
  179. frame_context.reference_frame_sign_biases[LastFrame + i] = TRY_READ(m_bit_stream->read_bit());
  180. }
  181. frame_size = TRY(parse_frame_size_with_refs(frame_context.reference_frame_indices));
  182. render_size = TRY(parse_render_size(frame_size));
  183. frame_context.high_precision_motion_vectors_allowed = TRY_READ(m_bit_stream->read_bit());
  184. frame_context.interpolation_filter = TRY(read_interpolation_filter());
  185. }
  186. }
  187. bool should_replace_probability_context = false;
  188. bool parallel_decoding_mode = true;
  189. if (!frame_context.error_resilient_mode) {
  190. should_replace_probability_context = TRY_READ(m_bit_stream->read_bit());
  191. parallel_decoding_mode = TRY_READ(m_bit_stream->read_bit());
  192. }
  193. u8 probability_context_index = TRY_READ(m_bit_stream->read_bits(2));
  194. switch (reset_frame_context) {
  195. case ResetProbabilities::All:
  196. setup_past_independence();
  197. for (auto i = 0; i < 4; i++) {
  198. m_probability_tables->save_probs(i);
  199. }
  200. probability_context_index = 0;
  201. break;
  202. case ResetProbabilities::OnlyCurrent:
  203. setup_past_independence();
  204. m_probability_tables->save_probs(probability_context_index);
  205. probability_context_index = 0;
  206. break;
  207. default:
  208. break;
  209. }
  210. frame_context.type = type;
  211. DECODER_TRY_ALLOC(frame_context.set_size(frame_size));
  212. frame_context.render_size = render_size;
  213. TRY(compute_image_size(frame_context));
  214. frame_context.reference_frames_to_update_flags = reference_frames_to_update_flags;
  215. frame_context.parallel_decoding_mode = parallel_decoding_mode;
  216. frame_context.should_replace_probability_context = should_replace_probability_context;
  217. frame_context.probability_context_index = probability_context_index;
  218. TRY(loop_filter_params(frame_context));
  219. TRY(quantization_params(frame_context));
  220. TRY(segmentation_params());
  221. TRY(parse_tile_counts(frame_context));
  222. frame_context.header_size_in_bytes = TRY_READ(m_bit_stream->read_f16());
  223. return frame_context;
  224. }
  225. DecoderErrorOr<void> Parser::frame_sync_code()
  226. {
  227. if (TRY_READ(m_bit_stream->read_f8()) != 0x49)
  228. return DecoderError::corrupted("frame_sync_code: Byte 0 was not 0x49."sv);
  229. if (TRY_READ(m_bit_stream->read_f8()) != 0x83)
  230. return DecoderError::corrupted("frame_sync_code: Byte 1 was not 0x83."sv);
  231. if (TRY_READ(m_bit_stream->read_f8()) != 0x42)
  232. return DecoderError::corrupted("frame_sync_code: Byte 2 was not 0x42."sv);
  233. return {};
  234. }
  235. DecoderErrorOr<ColorConfig> Parser::parse_color_config(FrameContext const& frame_context)
  236. {
  237. // (6.2.2) color_config( )
  238. u8 bit_depth;
  239. if (frame_context.profile >= 2) {
  240. bit_depth = TRY_READ(m_bit_stream->read_bit()) ? 12 : 10;
  241. } else {
  242. bit_depth = 8;
  243. }
  244. auto color_space = static_cast<ColorSpace>(TRY_READ(m_bit_stream->read_bits(3)));
  245. VERIFY(color_space <= ColorSpace::RGB);
  246. ColorRange color_range;
  247. bool subsampling_x, subsampling_y;
  248. if (color_space != ColorSpace::RGB) {
  249. color_range = TRY(read_color_range());
  250. if (frame_context.profile == 1 || frame_context.profile == 3) {
  251. subsampling_x = TRY_READ(m_bit_stream->read_bit());
  252. subsampling_y = TRY_READ(m_bit_stream->read_bit());
  253. if (TRY_READ(m_bit_stream->read_bit()))
  254. return DecoderError::corrupted("color_config: Subsampling reserved zero was set"sv);
  255. } else {
  256. subsampling_x = true;
  257. subsampling_y = true;
  258. }
  259. } else {
  260. color_range = ColorRange::Full;
  261. if (frame_context.profile == 1 || frame_context.profile == 3) {
  262. subsampling_x = false;
  263. subsampling_y = false;
  264. if (TRY_READ(m_bit_stream->read_bit()))
  265. return DecoderError::corrupted("color_config: RGB reserved zero was set"sv);
  266. } else {
  267. // FIXME: Spec does not specify the subsampling value here. Is this an error or should we set a default?
  268. VERIFY_NOT_REACHED();
  269. }
  270. }
  271. return ColorConfig { bit_depth, color_space, color_range, subsampling_x, subsampling_y };
  272. }
  273. DecoderErrorOr<Gfx::Size<u32>> Parser::parse_frame_size()
  274. {
  275. return Gfx::Size<u32> { TRY_READ(m_bit_stream->read_f16()) + 1, TRY_READ(m_bit_stream->read_f16()) + 1 };
  276. }
  277. DecoderErrorOr<Gfx::Size<u32>> Parser::parse_render_size(Gfx::Size<u32> frame_size)
  278. {
  279. // FIXME: This function should save this bit as a value in the FrameContext. The bit can be
  280. // used in files where the pixel aspect ratio changes between samples in the video.
  281. // If the bit is set, the pixel aspect ratio should be recalculated, whereas if only
  282. // the frame size has changed and the render size is unadjusted, then the pixel aspect
  283. // ratio should be retained and the new render size determined based on that.
  284. // See the Firefox source code here:
  285. // https://searchfox.org/mozilla-central/source/dom/media/platforms/wrappers/MediaChangeMonitor.cpp#268-276
  286. if (!TRY_READ(m_bit_stream->read_bit()))
  287. return frame_size;
  288. return Gfx::Size<u32> { TRY_READ(m_bit_stream->read_f16()) + 1, TRY_READ(m_bit_stream->read_f16()) + 1 };
  289. }
  290. DecoderErrorOr<Gfx::Size<u32>> Parser::parse_frame_size_with_refs(Array<u8, 3> const& reference_indices)
  291. {
  292. Optional<Gfx::Size<u32>> size;
  293. for (auto frame_index : reference_indices) {
  294. if (TRY_READ(m_bit_stream->read_bit())) {
  295. size.emplace(m_ref_frame_size[frame_index]);
  296. break;
  297. }
  298. }
  299. if (size.has_value())
  300. return size.value();
  301. return TRY(parse_frame_size());
  302. }
  303. DecoderErrorOr<void> Parser::compute_image_size(FrameContext& frame_context)
  304. {
  305. // 7.2.6 Compute image size semantics
  306. // When compute_image_size is invoked, the following ordered steps occur:
  307. // 1. If this is the first time compute_image_size is invoked, or if either FrameWidth or FrameHeight have
  308. // changed in value compared to the previous time this function was invoked, then the segmentation map is
  309. // cleared to all zeros by setting SegmentId[ row ][ col ] equal to 0 for row = 0..MiRows-1 and col =
  310. // 0..MiCols-1.
  311. // FIXME: What does this mean? SegmentIds is scoped to one frame, so it will not contain values here. It's
  312. // also suspicious that spec refers to this as SegmentId rather than SegmentIds (plural). Is this
  313. // supposed to refer to PrevSegmentIds?
  314. bool first_invoke = m_is_first_compute_image_size_invoke;
  315. m_is_first_compute_image_size_invoke = false;
  316. bool same_size = m_previous_frame_size == frame_context.size();
  317. // 2. The variable UsePrevFrameMvs is set equal to 1 if all of the following conditions are true:
  318. // a. This is not the first time compute_image_size is invoked.
  319. // b. Both FrameWidth and FrameHeight have the same value compared to the previous time this function
  320. // was invoked.
  321. // c. show_frame was equal to 1 the previous time this function was invoked.
  322. // d. error_resilient_mode is equal to 0.
  323. // e. FrameIsIntra is equal to 0.
  324. // Otherwise, UsePrevFrameMvs is set equal to 0.
  325. m_use_prev_frame_mvs = !first_invoke && same_size && m_previous_show_frame && !frame_context.error_resilient_mode && frame_context.is_inter_predicted();
  326. return {};
  327. }
  328. DecoderErrorOr<InterpolationFilter> Parser::read_interpolation_filter()
  329. {
  330. if (TRY_READ(m_bit_stream->read_bit())) {
  331. return InterpolationFilter::Switchable;
  332. }
  333. return literal_to_type[TRY_READ(m_bit_stream->read_bits(2))];
  334. }
  335. DecoderErrorOr<void> Parser::loop_filter_params(FrameContext& frame_context)
  336. {
  337. frame_context.loop_filter_level = TRY_READ(m_bit_stream->read_bits(6));
  338. frame_context.loop_filter_sharpness = TRY_READ(m_bit_stream->read_bits(3));
  339. frame_context.loop_filter_delta_enabled = TRY_READ(m_bit_stream->read_bit());
  340. auto reference_deltas = m_previous_loop_filter_ref_deltas;
  341. auto mode_deltas = m_previous_loop_filter_mode_deltas;
  342. if (frame_context.loop_filter_delta_enabled && TRY_READ(m_bit_stream->read_bit())) {
  343. for (auto& loop_filter_ref_delta : reference_deltas) {
  344. if (TRY_READ(m_bit_stream->read_bit()))
  345. loop_filter_ref_delta = TRY_READ(m_bit_stream->read_s(6));
  346. }
  347. for (auto& loop_filter_mode_delta : mode_deltas) {
  348. if (TRY_READ(m_bit_stream->read_bit()))
  349. loop_filter_mode_delta = TRY_READ(m_bit_stream->read_s(6));
  350. }
  351. }
  352. frame_context.loop_filter_reference_deltas = reference_deltas;
  353. frame_context.loop_filter_mode_deltas = mode_deltas;
  354. return {};
  355. }
  356. DecoderErrorOr<void> Parser::quantization_params(FrameContext& frame_context)
  357. {
  358. frame_context.base_quantizer_index = TRY_READ(m_bit_stream->read_f8());
  359. frame_context.y_dc_quantizer_index_delta = TRY(read_delta_q());
  360. frame_context.uv_dc_quantizer_index_delta = TRY(read_delta_q());
  361. frame_context.uv_ac_quantizer_index_delta = TRY(read_delta_q());
  362. return {};
  363. }
  364. DecoderErrorOr<i8> Parser::read_delta_q()
  365. {
  366. if (TRY_READ(m_bit_stream->read_bit()))
  367. return TRY_READ(m_bit_stream->read_s(4));
  368. return 0;
  369. }
  370. DecoderErrorOr<void> Parser::segmentation_params()
  371. {
  372. m_segmentation_enabled = TRY_READ(m_bit_stream->read_bit());
  373. if (!m_segmentation_enabled)
  374. return {};
  375. m_segmentation_update_map = TRY_READ(m_bit_stream->read_bit());
  376. if (m_segmentation_update_map) {
  377. for (auto& segmentation_tree_prob : m_segmentation_tree_probs)
  378. segmentation_tree_prob = TRY(read_prob());
  379. m_segmentation_temporal_update = TRY_READ(m_bit_stream->read_bit());
  380. for (auto& segmentation_pred_prob : m_segmentation_pred_prob)
  381. segmentation_pred_prob = m_segmentation_temporal_update ? TRY(read_prob()) : 255;
  382. }
  383. auto segmentation_update_data = (TRY_READ(m_bit_stream->read_bit()));
  384. if (!segmentation_update_data)
  385. return {};
  386. m_segmentation_abs_or_delta_update = TRY_READ(m_bit_stream->read_bit());
  387. for (auto i = 0; i < MAX_SEGMENTS; i++) {
  388. for (auto j = 0; j < SEG_LVL_MAX; j++) {
  389. auto feature_value = 0;
  390. auto feature_enabled = TRY_READ(m_bit_stream->read_bit());
  391. m_feature_enabled[i][j] = feature_enabled;
  392. if (feature_enabled) {
  393. auto bits_to_read = segmentation_feature_bits[j];
  394. feature_value = TRY_READ(m_bit_stream->read_bits(bits_to_read));
  395. if (segmentation_feature_signed[j]) {
  396. if (TRY_READ(m_bit_stream->read_bit()))
  397. feature_value = -feature_value;
  398. }
  399. }
  400. m_feature_data[i][j] = feature_value;
  401. }
  402. }
  403. return {};
  404. }
  405. DecoderErrorOr<u8> Parser::read_prob()
  406. {
  407. if (TRY_READ(m_bit_stream->read_bit()))
  408. return TRY_READ(m_bit_stream->read_f8());
  409. return 255;
  410. }
  411. static u16 calc_min_log2_of_tile_columns(u32 superblock_columns)
  412. {
  413. auto min_log_2 = 0u;
  414. while ((u32)(MAX_TILE_WIDTH_B64 << min_log_2) < superblock_columns)
  415. min_log_2++;
  416. return min_log_2;
  417. }
  418. static u16 calc_max_log2_tile_cols(u32 superblock_columns)
  419. {
  420. u16 max_log_2 = 1;
  421. while ((superblock_columns >> max_log_2) >= MIN_TILE_WIDTH_B64)
  422. max_log_2++;
  423. return max_log_2 - 1;
  424. }
  425. DecoderErrorOr<void> Parser::parse_tile_counts(FrameContext& frame_context)
  426. {
  427. auto superblock_columns = frame_context.superblock_columns();
  428. auto log2_of_tile_columns = calc_min_log2_of_tile_columns(superblock_columns);
  429. auto log2_of_tile_columns_maximum = calc_max_log2_tile_cols(superblock_columns);
  430. while (log2_of_tile_columns < log2_of_tile_columns_maximum) {
  431. if (TRY_READ(m_bit_stream->read_bit()))
  432. log2_of_tile_columns++;
  433. else
  434. break;
  435. }
  436. u16 log2_of_tile_rows = TRY_READ(m_bit_stream->read_bit());
  437. if (log2_of_tile_rows > 0) {
  438. log2_of_tile_rows += TRY_READ(m_bit_stream->read_bit());
  439. }
  440. frame_context.log2_of_tile_counts = Gfx::Size<u16>(log2_of_tile_columns, log2_of_tile_rows);
  441. return {};
  442. }
  443. void Parser::setup_past_independence()
  444. {
  445. for (auto i = 0; i < 8; i++) {
  446. for (auto j = 0; j < 4; j++) {
  447. m_feature_data[i][j] = 0;
  448. m_feature_enabled[i][j] = false;
  449. }
  450. }
  451. m_previous_block_contexts.reset();
  452. m_segmentation_abs_or_delta_update = false;
  453. m_previous_loop_filter_ref_deltas[IntraFrame] = 1;
  454. m_previous_loop_filter_ref_deltas[LastFrame] = 0;
  455. m_previous_loop_filter_ref_deltas[GoldenFrame] = -1;
  456. m_previous_loop_filter_ref_deltas[AltRefFrame] = -1;
  457. m_previous_loop_filter_mode_deltas.fill(0);
  458. m_probability_tables->reset_probs();
  459. }
  460. DecoderErrorOr<void> Parser::compressed_header(FrameContext& frame_context)
  461. {
  462. frame_context.transform_mode = TRY(read_tx_mode(frame_context));
  463. if (frame_context.transform_mode == TXModeSelect)
  464. TRY(tx_mode_probs());
  465. TRY(read_coef_probs(frame_context.transform_mode));
  466. TRY(read_skip_prob());
  467. if (frame_context.is_inter_predicted()) {
  468. TRY(read_inter_mode_probs());
  469. if (frame_context.interpolation_filter == Switchable)
  470. TRY(read_interp_filter_probs());
  471. TRY(read_is_inter_probs());
  472. TRY(frame_reference_mode(frame_context));
  473. TRY(frame_reference_mode_probs(frame_context));
  474. TRY(read_y_mode_probs());
  475. TRY(read_partition_probs());
  476. TRY(mv_probs(frame_context));
  477. }
  478. return {};
  479. }
  480. DecoderErrorOr<TXMode> Parser::read_tx_mode(FrameContext const& frame_context)
  481. {
  482. if (frame_context.is_lossless()) {
  483. return TXMode::Only_4x4;
  484. }
  485. auto tx_mode = TRY_READ(m_bit_stream->read_literal(2));
  486. if (tx_mode == Allow_32x32)
  487. tx_mode += TRY_READ(m_bit_stream->read_literal(1));
  488. return static_cast<TXMode>(tx_mode);
  489. }
  490. DecoderErrorOr<void> Parser::tx_mode_probs()
  491. {
  492. auto& tx_probs = m_probability_tables->tx_probs();
  493. for (auto i = 0; i < TX_SIZE_CONTEXTS; i++) {
  494. for (auto j = 0; j < TX_SIZES - 3; j++)
  495. tx_probs[TX_8x8][i][j] = TRY(diff_update_prob(tx_probs[TX_8x8][i][j]));
  496. }
  497. for (auto i = 0; i < TX_SIZE_CONTEXTS; i++) {
  498. for (auto j = 0; j < TX_SIZES - 2; j++)
  499. tx_probs[TX_16x16][i][j] = TRY(diff_update_prob(tx_probs[TX_16x16][i][j]));
  500. }
  501. for (auto i = 0; i < TX_SIZE_CONTEXTS; i++) {
  502. for (auto j = 0; j < TX_SIZES - 1; j++)
  503. tx_probs[TX_32x32][i][j] = TRY(diff_update_prob(tx_probs[TX_32x32][i][j]));
  504. }
  505. return {};
  506. }
  507. DecoderErrorOr<u8> Parser::diff_update_prob(u8 prob)
  508. {
  509. auto update_prob = TRY_READ(m_bit_stream->read_bool(252));
  510. if (update_prob) {
  511. auto delta_prob = TRY(decode_term_subexp());
  512. prob = inv_remap_prob(delta_prob, prob);
  513. }
  514. return prob;
  515. }
  516. DecoderErrorOr<u8> Parser::decode_term_subexp()
  517. {
  518. if (TRY_READ(m_bit_stream->read_literal(1)) == 0)
  519. return TRY_READ(m_bit_stream->read_literal(4));
  520. if (TRY_READ(m_bit_stream->read_literal(1)) == 0)
  521. return TRY_READ(m_bit_stream->read_literal(4)) + 16;
  522. if (TRY_READ(m_bit_stream->read_literal(1)) == 0)
  523. return TRY_READ(m_bit_stream->read_literal(5)) + 32;
  524. auto v = TRY_READ(m_bit_stream->read_literal(7));
  525. if (v < 65)
  526. return v + 64;
  527. return (v << 1u) - 1 + TRY_READ(m_bit_stream->read_literal(1));
  528. }
  529. u8 Parser::inv_remap_prob(u8 delta_prob, u8 prob)
  530. {
  531. u8 m = prob - 1;
  532. auto v = inv_map_table[delta_prob];
  533. if ((m << 1u) <= 255)
  534. return 1 + inv_recenter_nonneg(v, m);
  535. return 255 - inv_recenter_nonneg(v, 254 - m);
  536. }
  537. u8 Parser::inv_recenter_nonneg(u8 v, u8 m)
  538. {
  539. if (v > 2 * m)
  540. return v;
  541. if (v & 1u)
  542. return m - ((v + 1u) >> 1u);
  543. return m + (v >> 1u);
  544. }
  545. DecoderErrorOr<void> Parser::read_coef_probs(TXMode transform_mode)
  546. {
  547. auto max_tx_size = tx_mode_to_biggest_tx_size[transform_mode];
  548. for (u8 tx_size = 0; tx_size <= max_tx_size; tx_size++) {
  549. auto update_probs = TRY_READ(m_bit_stream->read_literal(1));
  550. if (update_probs == 1) {
  551. for (auto i = 0; i < 2; i++) {
  552. for (auto j = 0; j < 2; j++) {
  553. for (auto k = 0; k < 6; k++) {
  554. auto max_l = (k == 0) ? 3 : 6;
  555. for (auto l = 0; l < max_l; l++) {
  556. for (auto m = 0; m < 3; m++) {
  557. auto& prob = m_probability_tables->coef_probs()[tx_size][i][j][k][l][m];
  558. prob = TRY(diff_update_prob(prob));
  559. }
  560. }
  561. }
  562. }
  563. }
  564. }
  565. }
  566. return {};
  567. }
  568. DecoderErrorOr<void> Parser::read_skip_prob()
  569. {
  570. for (auto i = 0; i < SKIP_CONTEXTS; i++)
  571. m_probability_tables->skip_prob()[i] = TRY(diff_update_prob(m_probability_tables->skip_prob()[i]));
  572. return {};
  573. }
  574. DecoderErrorOr<void> Parser::read_inter_mode_probs()
  575. {
  576. for (auto i = 0; i < INTER_MODE_CONTEXTS; i++) {
  577. for (auto j = 0; j < INTER_MODES - 1; j++)
  578. m_probability_tables->inter_mode_probs()[i][j] = TRY(diff_update_prob(m_probability_tables->inter_mode_probs()[i][j]));
  579. }
  580. return {};
  581. }
  582. DecoderErrorOr<void> Parser::read_interp_filter_probs()
  583. {
  584. for (auto i = 0; i < INTERP_FILTER_CONTEXTS; i++) {
  585. for (auto j = 0; j < SWITCHABLE_FILTERS - 1; j++)
  586. m_probability_tables->interp_filter_probs()[i][j] = TRY(diff_update_prob(m_probability_tables->interp_filter_probs()[i][j]));
  587. }
  588. return {};
  589. }
  590. DecoderErrorOr<void> Parser::read_is_inter_probs()
  591. {
  592. for (auto i = 0; i < IS_INTER_CONTEXTS; i++)
  593. m_probability_tables->is_inter_prob()[i] = TRY(diff_update_prob(m_probability_tables->is_inter_prob()[i]));
  594. return {};
  595. }
  596. static void setup_compound_reference_mode(FrameContext& frame_context)
  597. {
  598. ReferenceFrameType fixed_reference;
  599. ReferenceFramePair variable_references;
  600. if (frame_context.reference_frame_sign_biases[LastFrame] == frame_context.reference_frame_sign_biases[GoldenFrame]) {
  601. fixed_reference = AltRefFrame;
  602. variable_references = { LastFrame, GoldenFrame };
  603. } else if (frame_context.reference_frame_sign_biases[LastFrame] == frame_context.reference_frame_sign_biases[AltRefFrame]) {
  604. fixed_reference = GoldenFrame;
  605. variable_references = { LastFrame, AltRefFrame };
  606. } else {
  607. fixed_reference = LastFrame;
  608. variable_references = { GoldenFrame, AltRefFrame };
  609. }
  610. frame_context.fixed_reference_type = fixed_reference;
  611. frame_context.variable_reference_types = variable_references;
  612. }
  613. DecoderErrorOr<void> Parser::frame_reference_mode(FrameContext& frame_context)
  614. {
  615. auto compound_reference_allowed = false;
  616. for (size_t i = 2; i <= REFS_PER_FRAME; i++) {
  617. if (frame_context.reference_frame_sign_biases[i] != frame_context.reference_frame_sign_biases[1])
  618. compound_reference_allowed = true;
  619. }
  620. ReferenceMode reference_mode;
  621. if (compound_reference_allowed) {
  622. auto non_single_reference = TRY_READ(m_bit_stream->read_literal(1));
  623. if (non_single_reference == 0) {
  624. reference_mode = SingleReference;
  625. } else {
  626. auto reference_select = TRY_READ(m_bit_stream->read_literal(1));
  627. if (reference_select == 0)
  628. reference_mode = CompoundReference;
  629. else
  630. reference_mode = ReferenceModeSelect;
  631. }
  632. } else {
  633. reference_mode = SingleReference;
  634. }
  635. frame_context.reference_mode = reference_mode;
  636. if (reference_mode != SingleReference)
  637. setup_compound_reference_mode(frame_context);
  638. return {};
  639. }
  640. DecoderErrorOr<void> Parser::frame_reference_mode_probs(FrameContext const& frame_context)
  641. {
  642. if (frame_context.reference_mode == ReferenceModeSelect) {
  643. for (auto i = 0; i < COMP_MODE_CONTEXTS; i++) {
  644. auto& comp_mode_prob = m_probability_tables->comp_mode_prob();
  645. comp_mode_prob[i] = TRY(diff_update_prob(comp_mode_prob[i]));
  646. }
  647. }
  648. if (frame_context.reference_mode != CompoundReference) {
  649. for (auto i = 0; i < REF_CONTEXTS; i++) {
  650. auto& single_ref_prob = m_probability_tables->single_ref_prob();
  651. single_ref_prob[i][0] = TRY(diff_update_prob(single_ref_prob[i][0]));
  652. single_ref_prob[i][1] = TRY(diff_update_prob(single_ref_prob[i][1]));
  653. }
  654. }
  655. if (frame_context.reference_mode != SingleReference) {
  656. for (auto i = 0; i < REF_CONTEXTS; i++) {
  657. auto& comp_ref_prob = m_probability_tables->comp_ref_prob();
  658. comp_ref_prob[i] = TRY(diff_update_prob(comp_ref_prob[i]));
  659. }
  660. }
  661. return {};
  662. }
  663. DecoderErrorOr<void> Parser::read_y_mode_probs()
  664. {
  665. for (auto i = 0; i < BLOCK_SIZE_GROUPS; i++) {
  666. for (auto j = 0; j < INTRA_MODES - 1; j++) {
  667. auto& y_mode_probs = m_probability_tables->y_mode_probs();
  668. y_mode_probs[i][j] = TRY(diff_update_prob(y_mode_probs[i][j]));
  669. }
  670. }
  671. return {};
  672. }
  673. DecoderErrorOr<void> Parser::read_partition_probs()
  674. {
  675. for (auto i = 0; i < PARTITION_CONTEXTS; i++) {
  676. for (auto j = 0; j < PARTITION_TYPES - 1; j++) {
  677. auto& partition_probs = m_probability_tables->partition_probs();
  678. partition_probs[i][j] = TRY(diff_update_prob(partition_probs[i][j]));
  679. }
  680. }
  681. return {};
  682. }
  683. DecoderErrorOr<void> Parser::mv_probs(FrameContext const& frame_context)
  684. {
  685. for (auto j = 0; j < MV_JOINTS - 1; j++) {
  686. auto& mv_joint_probs = m_probability_tables->mv_joint_probs();
  687. mv_joint_probs[j] = TRY(update_mv_prob(mv_joint_probs[j]));
  688. }
  689. for (auto i = 0; i < 2; i++) {
  690. auto& mv_sign_prob = m_probability_tables->mv_sign_prob();
  691. mv_sign_prob[i] = TRY(update_mv_prob(mv_sign_prob[i]));
  692. for (auto j = 0; j < MV_CLASSES - 1; j++) {
  693. auto& mv_class_probs = m_probability_tables->mv_class_probs();
  694. mv_class_probs[i][j] = TRY(update_mv_prob(mv_class_probs[i][j]));
  695. }
  696. auto& mv_class0_bit_prob = m_probability_tables->mv_class0_bit_prob();
  697. mv_class0_bit_prob[i] = TRY(update_mv_prob(mv_class0_bit_prob[i]));
  698. for (auto j = 0; j < MV_OFFSET_BITS; j++) {
  699. auto& mv_bits_prob = m_probability_tables->mv_bits_prob();
  700. mv_bits_prob[i][j] = TRY(update_mv_prob(mv_bits_prob[i][j]));
  701. }
  702. }
  703. for (auto i = 0; i < 2; i++) {
  704. for (auto j = 0; j < CLASS0_SIZE; j++) {
  705. for (auto k = 0; k < MV_FR_SIZE - 1; k++) {
  706. auto& mv_class0_fr_probs = m_probability_tables->mv_class0_fr_probs();
  707. mv_class0_fr_probs[i][j][k] = TRY(update_mv_prob(mv_class0_fr_probs[i][j][k]));
  708. }
  709. }
  710. for (auto k = 0; k < MV_FR_SIZE - 1; k++) {
  711. auto& mv_fr_probs = m_probability_tables->mv_fr_probs();
  712. mv_fr_probs[i][k] = TRY(update_mv_prob(mv_fr_probs[i][k]));
  713. }
  714. }
  715. if (frame_context.high_precision_motion_vectors_allowed) {
  716. for (auto i = 0; i < 2; i++) {
  717. auto& mv_class0_hp_prob = m_probability_tables->mv_class0_hp_prob();
  718. auto& mv_hp_prob = m_probability_tables->mv_hp_prob();
  719. mv_class0_hp_prob[i] = TRY(update_mv_prob(mv_class0_hp_prob[i]));
  720. mv_hp_prob[i] = TRY(update_mv_prob(mv_hp_prob[i]));
  721. }
  722. }
  723. return {};
  724. }
  725. DecoderErrorOr<u8> Parser::update_mv_prob(u8 prob)
  726. {
  727. if (TRY_READ(m_bit_stream->read_bool(252))) {
  728. return (TRY_READ(m_bit_stream->read_literal(7)) << 1u) | 1u;
  729. }
  730. return prob;
  731. }
  732. DecoderErrorOr<void> Parser::decode_tiles(FrameContext& frame_context)
  733. {
  734. auto log2_dimensions = frame_context.log2_of_tile_counts;
  735. auto tile_cols = 1 << log2_dimensions.width();
  736. auto tile_rows = 1 << log2_dimensions.height();
  737. clear_above_context(frame_context);
  738. for (auto tile_row = 0; tile_row < tile_rows; tile_row++) {
  739. for (auto tile_col = 0; tile_col < tile_cols; tile_col++) {
  740. auto last_tile = (tile_row == tile_rows - 1) && (tile_col == tile_cols - 1);
  741. u64 tile_size;
  742. if (last_tile)
  743. tile_size = m_bit_stream->bytes_remaining();
  744. else
  745. tile_size = TRY_READ(m_bit_stream->read_bits(32));
  746. auto rows_start = get_tile_offset(tile_row, frame_context.rows(), log2_dimensions.height());
  747. auto rows_end = get_tile_offset(tile_row + 1, frame_context.rows(), log2_dimensions.height());
  748. auto columns_start = get_tile_offset(tile_col, frame_context.columns(), log2_dimensions.width());
  749. auto columns_end = get_tile_offset(tile_col + 1, frame_context.columns(), log2_dimensions.width());
  750. auto tile_context = TileContext(frame_context, rows_start, rows_end, columns_start, columns_end);
  751. TRY_READ(m_bit_stream->init_bool(tile_size));
  752. TRY(decode_tile(tile_context));
  753. TRY_READ(m_bit_stream->exit_bool());
  754. }
  755. }
  756. return {};
  757. }
  758. template<typename T>
  759. void Parser::clear_context(Vector<T>& context, size_t size)
  760. {
  761. context.resize_and_keep_capacity(size);
  762. __builtin_memset(context.data(), 0, sizeof(T) * size);
  763. }
  764. template<typename T>
  765. void Parser::clear_context(Vector<Vector<T>>& context, size_t outer_size, size_t inner_size)
  766. {
  767. if (context.size() < outer_size)
  768. context.resize(outer_size);
  769. for (auto& sub_vector : context)
  770. clear_context(sub_vector, inner_size);
  771. }
  772. void Parser::clear_above_context(FrameContext& frame_context)
  773. {
  774. for (auto i = 0u; i < m_above_nonzero_context.size(); i++)
  775. clear_context(m_above_nonzero_context[i], 2 * frame_context.columns());
  776. clear_context(m_above_seg_pred_context, frame_context.columns());
  777. clear_context(m_above_partition_context, frame_context.superblock_columns() * 8);
  778. }
  779. u32 Parser::get_tile_offset(u32 tile_num, u32 mis, u32 tile_size_log2)
  780. {
  781. u32 super_blocks = (mis + 7) >> 3u;
  782. u32 offset = ((tile_num * super_blocks) >> tile_size_log2) << 3u;
  783. return min(offset, mis);
  784. }
  785. DecoderErrorOr<void> Parser::decode_tile(TileContext& tile_context)
  786. {
  787. for (auto row = tile_context.rows_start; row < tile_context.rows_end; row += 8) {
  788. clear_left_context(tile_context);
  789. for (auto col = tile_context.columns_start; col < tile_context.columns_end; col += 8) {
  790. TRY(decode_partition(tile_context, row, col, Block_64x64));
  791. }
  792. }
  793. return {};
  794. }
  795. void Parser::clear_left_context(TileContext& tile_context)
  796. {
  797. for (auto i = 0u; i < m_left_nonzero_context.size(); i++)
  798. clear_context(m_left_nonzero_context[i], 2 * tile_context.frame_context.rows());
  799. clear_context(m_left_seg_pred_context, tile_context.frame_context.rows());
  800. clear_context(m_left_partition_context, tile_context.frame_context.superblock_rows() * 8);
  801. }
  802. DecoderErrorOr<void> Parser::decode_partition(TileContext& tile_context, u32 row, u32 column, BlockSubsize subsize)
  803. {
  804. if (row >= tile_context.frame_context.rows() || column >= tile_context.frame_context.columns())
  805. return {};
  806. u8 num_8x8 = num_8x8_blocks_wide_lookup[subsize];
  807. auto half_block_8x8 = num_8x8 >> 1;
  808. bool has_rows = (row + half_block_8x8) < tile_context.frame_context.rows();
  809. bool has_cols = (column + half_block_8x8) < tile_context.frame_context.columns();
  810. auto partition = TRY_READ(TreeParser::parse_partition(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, has_rows, has_cols, subsize, num_8x8, m_above_partition_context, m_left_partition_context, row, column, !tile_context.frame_context.is_inter_predicted()));
  811. auto child_subsize = subsize_lookup[partition][subsize];
  812. if (child_subsize < Block_8x8 || partition == PartitionNone) {
  813. TRY(decode_block(tile_context, row, column, child_subsize));
  814. } else if (partition == PartitionHorizontal) {
  815. TRY(decode_block(tile_context, row, column, child_subsize));
  816. if (has_rows)
  817. TRY(decode_block(tile_context, row + half_block_8x8, column, child_subsize));
  818. } else if (partition == PartitionVertical) {
  819. TRY(decode_block(tile_context, row, column, child_subsize));
  820. if (has_cols)
  821. TRY(decode_block(tile_context, row, column + half_block_8x8, child_subsize));
  822. } else {
  823. TRY(decode_partition(tile_context, row, column, child_subsize));
  824. TRY(decode_partition(tile_context, row, column + half_block_8x8, child_subsize));
  825. TRY(decode_partition(tile_context, row + half_block_8x8, column, child_subsize));
  826. TRY(decode_partition(tile_context, row + half_block_8x8, column + half_block_8x8, child_subsize));
  827. }
  828. if (subsize == Block_8x8 || partition != PartitionSplit) {
  829. auto above_context = 15 >> b_width_log2_lookup[child_subsize];
  830. auto left_context = 15 >> b_height_log2_lookup[child_subsize];
  831. for (size_t i = 0; i < num_8x8; i++) {
  832. m_above_partition_context[column + i] = above_context;
  833. m_left_partition_context[row + i] = left_context;
  834. }
  835. }
  836. return {};
  837. }
  838. size_t Parser::get_image_index(FrameContext const& frame_context, u32 row, u32 column) const
  839. {
  840. VERIFY(row < frame_context.rows() && column < frame_context.columns());
  841. return row * frame_context.columns() + column;
  842. }
  843. DecoderErrorOr<void> Parser::decode_block(TileContext& tile_context, u32 row, u32 column, BlockSubsize subsize)
  844. {
  845. auto above_context = row > 0 ? tile_context.frame_block_contexts().at(row - 1, column) : FrameBlockContext();
  846. auto left_context = column > tile_context.columns_start ? tile_context.frame_block_contexts().at(row, column - 1) : FrameBlockContext();
  847. auto block_context = BlockContext(tile_context, row, column, subsize);
  848. TRY(mode_info(block_context, above_context, left_context));
  849. auto had_residual_tokens = TRY(residual(block_context, above_context.is_available, left_context.is_available));
  850. if (block_context.is_inter_predicted() && subsize >= Block_8x8 && !had_residual_tokens)
  851. block_context.should_skip_residuals = true;
  852. for (size_t y = 0; y < block_context.contexts_view.height(); y++) {
  853. for (size_t x = 0; x < block_context.contexts_view.width(); x++) {
  854. auto sub_block_context = FrameBlockContext { true, block_context.should_skip_residuals, block_context.tx_size, block_context.y_prediction_mode(), block_context.sub_block_prediction_modes, block_context.interpolation_filter, block_context.reference_frame_types, block_context.sub_block_motion_vectors, block_context.segment_id };
  855. block_context.contexts_view.at(y, x) = sub_block_context;
  856. VERIFY(block_context.frame_block_contexts().at(row + y, column + x).tx_size == sub_block_context.tx_size);
  857. }
  858. }
  859. return {};
  860. }
  861. DecoderErrorOr<void> Parser::mode_info(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  862. {
  863. if (block_context.frame_context.is_inter_predicted())
  864. TRY(inter_frame_mode_info(block_context, above_context, left_context));
  865. else
  866. TRY(intra_frame_mode_info(block_context, above_context, left_context));
  867. return {};
  868. }
  869. DecoderErrorOr<void> Parser::intra_frame_mode_info(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  870. {
  871. block_context.reference_frame_types = { ReferenceFrameType::None, ReferenceFrameType::None };
  872. VERIFY(!block_context.is_inter_predicted());
  873. TRY(set_intra_segment_id(block_context));
  874. block_context.should_skip_residuals = TRY(read_should_skip_residuals(block_context, above_context, left_context));
  875. block_context.tx_size = TRY(read_tx_size(block_context, above_context, left_context, true));
  876. // FIXME: This if statement is also present in parse_default_intra_mode. The selection of parameters for
  877. // the probability table lookup should be inlined here.
  878. if (block_context.size >= Block_8x8) {
  879. auto mode = TRY_READ(TreeParser::parse_default_intra_mode(*m_bit_stream, *m_probability_tables, block_context.size, above_context, left_context, block_context.sub_block_prediction_modes, 0, 0));
  880. for (auto& block_sub_mode : block_context.sub_block_prediction_modes)
  881. block_sub_mode = mode;
  882. } else {
  883. auto size_in_4x4_blocks = block_context.get_size_in_4x4_blocks();
  884. for (auto idy = 0; idy < 2; idy += size_in_4x4_blocks.height()) {
  885. for (auto idx = 0; idx < 2; idx += size_in_4x4_blocks.width()) {
  886. auto sub_mode = TRY_READ(TreeParser::parse_default_intra_mode(*m_bit_stream, *m_probability_tables, block_context.size, above_context, left_context, block_context.sub_block_prediction_modes, idx, idy));
  887. for (auto y = 0; y < size_in_4x4_blocks.height(); y++) {
  888. for (auto x = 0; x < size_in_4x4_blocks.width(); x++) {
  889. auto index = (idy + y) * 2 + idx + x;
  890. block_context.sub_block_prediction_modes[index] = sub_mode;
  891. }
  892. }
  893. }
  894. }
  895. }
  896. block_context.uv_prediction_mode = TRY_READ(TreeParser::parse_default_uv_mode(*m_bit_stream, *m_probability_tables, block_context.y_prediction_mode()));
  897. return {};
  898. }
  899. DecoderErrorOr<void> Parser::set_intra_segment_id(BlockContext& block_context)
  900. {
  901. if (m_segmentation_enabled && m_segmentation_update_map)
  902. block_context.segment_id = TRY_READ(TreeParser::parse_segment_id(*m_bit_stream, m_segmentation_tree_probs));
  903. else
  904. block_context.segment_id = 0;
  905. return {};
  906. }
  907. DecoderErrorOr<bool> Parser::read_should_skip_residuals(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  908. {
  909. if (seg_feature_active(block_context, SEG_LVL_SKIP))
  910. return true;
  911. return TRY_READ(TreeParser::parse_skip(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, above_context, left_context));
  912. }
  913. bool Parser::seg_feature_active(BlockContext const& block_context, u8 feature)
  914. {
  915. return m_segmentation_enabled && m_feature_enabled[block_context.segment_id][feature];
  916. }
  917. DecoderErrorOr<TXSize> Parser::read_tx_size(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context, bool allow_select)
  918. {
  919. auto max_tx_size = max_txsize_lookup[block_context.size];
  920. if (allow_select && block_context.frame_context.transform_mode == TXModeSelect && block_context.size >= Block_8x8)
  921. return (TRY_READ(TreeParser::parse_tx_size(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, max_tx_size, above_context, left_context)));
  922. return min(max_tx_size, tx_mode_to_biggest_tx_size[block_context.frame_context.transform_mode]);
  923. }
  924. DecoderErrorOr<void> Parser::inter_frame_mode_info(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  925. {
  926. TRY(set_inter_segment_id(block_context));
  927. block_context.should_skip_residuals = TRY(read_should_skip_residuals(block_context, above_context, left_context));
  928. auto is_inter = TRY(read_is_inter(block_context, above_context, left_context));
  929. block_context.tx_size = TRY(read_tx_size(block_context, above_context, left_context, !block_context.should_skip_residuals || !is_inter));
  930. if (is_inter) {
  931. TRY(inter_block_mode_info(block_context, above_context, left_context));
  932. } else {
  933. TRY(intra_block_mode_info(block_context));
  934. }
  935. return {};
  936. }
  937. DecoderErrorOr<void> Parser::set_inter_segment_id(BlockContext& block_context)
  938. {
  939. if (!m_segmentation_enabled) {
  940. block_context.segment_id = 0;
  941. return {};
  942. }
  943. auto predicted_segment_id = get_segment_id(block_context);
  944. if (!m_segmentation_update_map) {
  945. block_context.segment_id = predicted_segment_id;
  946. return {};
  947. }
  948. if (!m_segmentation_temporal_update) {
  949. block_context.segment_id = TRY_READ(TreeParser::parse_segment_id(*m_bit_stream, m_segmentation_tree_probs));
  950. return {};
  951. }
  952. auto seg_id_predicted = TRY_READ(TreeParser::parse_segment_id_predicted(*m_bit_stream, m_segmentation_pred_prob, m_left_seg_pred_context[block_context.row], m_above_seg_pred_context[block_context.column]));
  953. if (seg_id_predicted)
  954. block_context.segment_id = predicted_segment_id;
  955. else
  956. block_context.segment_id = TRY_READ(TreeParser::parse_segment_id(*m_bit_stream, m_segmentation_tree_probs));
  957. for (size_t i = 0; i < num_8x8_blocks_wide_lookup[block_context.size]; i++) {
  958. auto index = block_context.column + i;
  959. // (7.4.1) AboveSegPredContext[ i ] only needs to be set to 0 for i = 0..MiCols-1.
  960. if (index < m_above_seg_pred_context.size())
  961. m_above_seg_pred_context[index] = seg_id_predicted;
  962. }
  963. for (size_t i = 0; i < num_8x8_blocks_high_lookup[block_context.size]; i++) {
  964. auto index = block_context.row + i;
  965. // (7.4.1) LeftSegPredContext[ i ] only needs to be set to 0 for i = 0..MiRows-1.
  966. if (index < m_above_seg_pred_context.size())
  967. m_left_seg_pred_context[block_context.row + i] = seg_id_predicted;
  968. }
  969. return {};
  970. }
  971. u8 Parser::get_segment_id(BlockContext const& block_context)
  972. {
  973. auto bw = num_8x8_blocks_wide_lookup[block_context.size];
  974. auto bh = num_8x8_blocks_high_lookup[block_context.size];
  975. auto xmis = min(block_context.frame_context.columns() - block_context.column, (u32)bw);
  976. auto ymis = min(block_context.frame_context.rows() - block_context.row, (u32)bh);
  977. u8 segment = 7;
  978. for (size_t y = 0; y < ymis; y++) {
  979. for (size_t x = 0; x < xmis; x++) {
  980. segment = min(segment, m_previous_block_contexts.index_at(block_context.row + y, block_context.column + x));
  981. }
  982. }
  983. return segment;
  984. }
  985. DecoderErrorOr<bool> Parser::read_is_inter(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  986. {
  987. if (seg_feature_active(block_context, SEG_LVL_REF_FRAME))
  988. return m_feature_data[block_context.segment_id][SEG_LVL_REF_FRAME] != IntraFrame;
  989. return TRY_READ(TreeParser::parse_block_is_inter_predicted(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, above_context, left_context));
  990. }
  991. DecoderErrorOr<void> Parser::intra_block_mode_info(BlockContext& block_context)
  992. {
  993. block_context.reference_frame_types = { ReferenceFrameType::None, ReferenceFrameType::None };
  994. VERIFY(!block_context.is_inter_predicted());
  995. auto& sub_modes = block_context.sub_block_prediction_modes;
  996. if (block_context.size >= Block_8x8) {
  997. auto mode = TRY_READ(TreeParser::parse_intra_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, block_context.size));
  998. for (auto& block_sub_mode : sub_modes)
  999. block_sub_mode = mode;
  1000. } else {
  1001. auto size_in_4x4_blocks = block_context.get_size_in_4x4_blocks();
  1002. for (auto idy = 0; idy < 2; idy += size_in_4x4_blocks.height()) {
  1003. for (auto idx = 0; idx < 2; idx += size_in_4x4_blocks.width()) {
  1004. auto sub_intra_mode = TRY_READ(TreeParser::parse_sub_intra_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter));
  1005. for (auto y = 0; y < size_in_4x4_blocks.height(); y++) {
  1006. for (auto x = 0; x < size_in_4x4_blocks.width(); x++)
  1007. sub_modes[(idy + y) * 2 + idx + x] = sub_intra_mode;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. block_context.uv_prediction_mode = TRY_READ(TreeParser::parse_uv_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, block_context.y_prediction_mode()));
  1013. return {};
  1014. }
  1015. static void select_best_reference_motion_vectors(BlockContext& block_context, MotionVectorPair reference_motion_vectors, BlockMotionVectorCandidates& candidates, ReferenceIndex);
  1016. DecoderErrorOr<void> Parser::inter_block_mode_info(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  1017. {
  1018. TRY(read_ref_frames(block_context, above_context, left_context));
  1019. VERIFY(block_context.is_inter_predicted());
  1020. BlockMotionVectorCandidates motion_vector_candidates;
  1021. auto reference_motion_vectors = find_reference_motion_vectors(block_context, block_context.reference_frame_types.primary, -1);
  1022. select_best_reference_motion_vectors(block_context, reference_motion_vectors, motion_vector_candidates, ReferenceIndex::Primary);
  1023. if (block_context.is_compound()) {
  1024. auto reference_motion_vectors = find_reference_motion_vectors(block_context, block_context.reference_frame_types.secondary, -1);
  1025. select_best_reference_motion_vectors(block_context, reference_motion_vectors, motion_vector_candidates, ReferenceIndex::Secondary);
  1026. }
  1027. if (seg_feature_active(block_context, SEG_LVL_SKIP)) {
  1028. block_context.y_prediction_mode() = PredictionMode::ZeroMv;
  1029. } else if (block_context.size >= Block_8x8) {
  1030. block_context.y_prediction_mode() = TRY_READ(TreeParser::parse_inter_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, m_mode_context[block_context.reference_frame_types.primary]));
  1031. }
  1032. if (block_context.frame_context.interpolation_filter == Switchable)
  1033. block_context.interpolation_filter = TRY_READ(TreeParser::parse_interpolation_filter(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, above_context, left_context));
  1034. else
  1035. block_context.interpolation_filter = block_context.frame_context.interpolation_filter;
  1036. if (block_context.size < Block_8x8) {
  1037. auto size_in_4x4_blocks = block_context.get_size_in_4x4_blocks();
  1038. for (auto idy = 0; idy < 2; idy += size_in_4x4_blocks.height()) {
  1039. for (auto idx = 0; idx < 2; idx += size_in_4x4_blocks.width()) {
  1040. block_context.y_prediction_mode() = TRY_READ(TreeParser::parse_inter_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, m_mode_context[block_context.reference_frame_types.primary]));
  1041. if (block_context.y_prediction_mode() == PredictionMode::NearestMv || block_context.y_prediction_mode() == PredictionMode::NearMv) {
  1042. select_best_sub_block_reference_motion_vectors(block_context, motion_vector_candidates, idy * 2 + idx, ReferenceIndex::Primary);
  1043. if (block_context.is_compound())
  1044. select_best_sub_block_reference_motion_vectors(block_context, motion_vector_candidates, idy * 2 + idx, ReferenceIndex::Secondary);
  1045. }
  1046. auto new_motion_vector_pair = TRY(get_motion_vector(block_context, motion_vector_candidates));
  1047. for (auto y = 0; y < size_in_4x4_blocks.height(); y++) {
  1048. for (auto x = 0; x < size_in_4x4_blocks.width(); x++) {
  1049. auto sub_block_index = (idy + y) * 2 + idx + x;
  1050. block_context.sub_block_motion_vectors[sub_block_index] = new_motion_vector_pair;
  1051. }
  1052. }
  1053. }
  1054. }
  1055. return {};
  1056. }
  1057. auto new_motion_vector_pair = TRY(get_motion_vector(block_context, motion_vector_candidates));
  1058. for (auto block = 0; block < 4; block++)
  1059. block_context.sub_block_motion_vectors[block] = new_motion_vector_pair;
  1060. return {};
  1061. }
  1062. DecoderErrorOr<void> Parser::read_ref_frames(BlockContext& block_context, FrameBlockContext above_context, FrameBlockContext left_context)
  1063. {
  1064. if (seg_feature_active(block_context, SEG_LVL_REF_FRAME)) {
  1065. block_context.reference_frame_types = { static_cast<ReferenceFrameType>(m_feature_data[block_context.segment_id][SEG_LVL_REF_FRAME]), None };
  1066. return {};
  1067. }
  1068. ReferenceMode compound_mode = block_context.frame_context.reference_mode;
  1069. auto fixed_reference = block_context.frame_context.fixed_reference_type;
  1070. if (compound_mode == ReferenceModeSelect)
  1071. compound_mode = TRY_READ(TreeParser::parse_comp_mode(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, fixed_reference, above_context, left_context));
  1072. if (compound_mode == CompoundReference) {
  1073. auto variable_references = block_context.frame_context.variable_reference_types;
  1074. auto fixed_reference_index = ReferenceIndex::Primary;
  1075. auto variable_reference_index = ReferenceIndex::Secondary;
  1076. if (block_context.frame_context.reference_frame_sign_biases[fixed_reference])
  1077. swap(fixed_reference_index, variable_reference_index);
  1078. auto variable_reference_selection = TRY_READ(TreeParser::parse_comp_ref(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, fixed_reference, variable_references, variable_reference_index, above_context, left_context));
  1079. block_context.reference_frame_types[fixed_reference_index] = fixed_reference;
  1080. block_context.reference_frame_types[variable_reference_index] = variable_references[variable_reference_selection];
  1081. return {};
  1082. }
  1083. // FIXME: Maybe consolidate this into a tree. Context is different between part 1 and 2 but still, it would look nice here.
  1084. ReferenceFrameType primary_type = ReferenceFrameType::LastFrame;
  1085. auto single_ref_p1 = TRY_READ(TreeParser::parse_single_ref_part_1(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, above_context, left_context));
  1086. if (single_ref_p1) {
  1087. auto single_ref_p2 = TRY_READ(TreeParser::parse_single_ref_part_2(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, above_context, left_context));
  1088. primary_type = single_ref_p2 ? ReferenceFrameType::AltRefFrame : ReferenceFrameType::GoldenFrame;
  1089. }
  1090. block_context.reference_frame_types = { primary_type, ReferenceFrameType::None };
  1091. return {};
  1092. }
  1093. // assign_mv( isCompound ) in the spec.
  1094. DecoderErrorOr<MotionVectorPair> Parser::get_motion_vector(BlockContext const& block_context, BlockMotionVectorCandidates const& candidates)
  1095. {
  1096. MotionVectorPair result;
  1097. auto read_one = [&](ReferenceIndex index) -> DecoderErrorOr<void> {
  1098. switch (block_context.y_prediction_mode()) {
  1099. case PredictionMode::NewMv:
  1100. result[index] = TRY(read_motion_vector(block_context, candidates, index));
  1101. break;
  1102. case PredictionMode::NearestMv:
  1103. result[index] = candidates[index].nearest_vector;
  1104. break;
  1105. case PredictionMode::NearMv:
  1106. result[index] = candidates[index].near_vector;
  1107. break;
  1108. default:
  1109. result[index] = {};
  1110. break;
  1111. }
  1112. return {};
  1113. };
  1114. TRY(read_one(ReferenceIndex::Primary));
  1115. if (block_context.is_compound())
  1116. TRY(read_one(ReferenceIndex::Secondary));
  1117. return result;
  1118. }
  1119. // use_mv_hp( deltaMv ) in the spec.
  1120. static bool should_use_high_precision_motion_vector(MotionVector const& delta_vector)
  1121. {
  1122. return (abs(delta_vector.row()) >> 3) < COMPANDED_MVREF_THRESH && (abs(delta_vector.column()) >> 3) < COMPANDED_MVREF_THRESH;
  1123. }
  1124. // read_mv( ref ) in the spec.
  1125. DecoderErrorOr<MotionVector> Parser::read_motion_vector(BlockContext const& block_context, BlockMotionVectorCandidates const& candidates, ReferenceIndex reference_index)
  1126. {
  1127. m_use_hp = block_context.frame_context.high_precision_motion_vectors_allowed && should_use_high_precision_motion_vector(candidates[reference_index].best_vector);
  1128. MotionVector delta_vector;
  1129. auto joint = TRY_READ(TreeParser::parse_motion_vector_joint(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter));
  1130. if ((joint & MotionVectorNonZeroRow) != 0)
  1131. delta_vector.set_row(TRY(read_single_motion_vector_component(0)));
  1132. if ((joint & MotionVectorNonZeroColumn) != 0)
  1133. delta_vector.set_column(TRY(read_single_motion_vector_component(1)));
  1134. return candidates[reference_index].best_vector + delta_vector;
  1135. }
  1136. // read_mv_component( comp ) in the spec.
  1137. DecoderErrorOr<i32> Parser::read_single_motion_vector_component(u8 component)
  1138. {
  1139. auto mv_sign = TRY_READ(TreeParser::parse_motion_vector_sign(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component));
  1140. auto mv_class = TRY_READ(TreeParser::parse_motion_vector_class(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component));
  1141. u32 magnitude;
  1142. if (mv_class == MvClass0) {
  1143. auto mv_class0_bit = TRY_READ(TreeParser::parse_motion_vector_class0_bit(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component));
  1144. auto mv_class0_fr = TRY_READ(TreeParser::parse_motion_vector_class0_fr(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component, mv_class0_bit));
  1145. auto mv_class0_hp = TRY_READ(TreeParser::parse_motion_vector_class0_hp(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component, m_use_hp));
  1146. magnitude = ((mv_class0_bit << 3) | (mv_class0_fr << 1) | mv_class0_hp) + 1;
  1147. } else {
  1148. u32 bits = 0;
  1149. for (u8 i = 0; i < mv_class; i++) {
  1150. auto mv_bit = TRY_READ(TreeParser::parse_motion_vector_bit(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component, i));
  1151. bits |= mv_bit << i;
  1152. }
  1153. magnitude = CLASS0_SIZE << (mv_class + 2);
  1154. auto mv_fr = TRY_READ(TreeParser::parse_motion_vector_fr(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component));
  1155. auto mv_hp = TRY_READ(TreeParser::parse_motion_vector_hp(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, component, m_use_hp));
  1156. magnitude += ((bits << 3) | (mv_fr << 1) | mv_hp) + 1;
  1157. }
  1158. return (mv_sign ? -1 : 1) * static_cast<i32>(magnitude);
  1159. }
  1160. Gfx::Point<size_t> Parser::get_decoded_point_for_plane(FrameContext const& frame_context, u32 column, u32 row, u8 plane)
  1161. {
  1162. (void)frame_context;
  1163. if (plane == 0)
  1164. return { column * 8, row * 8 };
  1165. return { (column * 8) >> frame_context.color_config.subsampling_x, (row * 8) >> frame_context.color_config.subsampling_y };
  1166. }
  1167. Gfx::Size<size_t> Parser::get_decoded_size_for_plane(FrameContext const& frame_context, u8 plane)
  1168. {
  1169. auto point = get_decoded_point_for_plane(frame_context, frame_context.columns(), frame_context.rows(), plane);
  1170. return { point.x(), point.y() };
  1171. }
  1172. static BlockSubsize get_plane_block_size(bool subsampling_x, bool subsampling_y, u32 subsize, u8 plane)
  1173. {
  1174. auto sub_x = (plane > 0) ? subsampling_x : 0;
  1175. auto sub_y = (plane > 0) ? subsampling_y : 0;
  1176. return ss_size_lookup[subsize][sub_x][sub_y];
  1177. }
  1178. static TXSize get_uv_tx_size(bool subsampling_x, bool subsampling_y, TXSize tx_size, BlockSubsize size)
  1179. {
  1180. if (size < Block_8x8)
  1181. return TX_4x4;
  1182. return min(tx_size, max_txsize_lookup[get_plane_block_size(subsampling_x, subsampling_y, size, 1)]);
  1183. }
  1184. DecoderErrorOr<bool> Parser::residual(BlockContext& block_context, bool has_block_above, bool has_block_left)
  1185. {
  1186. bool had_residual_tokens = false;
  1187. auto block_size = block_context.size < Block_8x8 ? Block_8x8 : block_context.size;
  1188. for (u8 plane = 0; plane < 3; plane++) {
  1189. auto tx_size = (plane > 0) ? get_uv_tx_size(block_context.frame_context.color_config.subsampling_x, block_context.frame_context.color_config.subsampling_y, block_context.tx_size, block_context.size) : block_context.tx_size;
  1190. auto step = 1 << tx_size;
  1191. auto plane_size = get_plane_block_size(block_context.frame_context.color_config.subsampling_x, block_context.frame_context.color_config.subsampling_y, block_size, plane);
  1192. auto num_4x4_w = num_4x4_blocks_wide_lookup[plane_size];
  1193. auto num_4x4_h = num_4x4_blocks_high_lookup[plane_size];
  1194. auto sub_x = (plane > 0) ? block_context.frame_context.color_config.subsampling_x : 0;
  1195. auto sub_y = (plane > 0) ? block_context.frame_context.color_config.subsampling_y : 0;
  1196. auto base_x = (block_context.column * 8) >> sub_x;
  1197. auto base_y = (block_context.row * 8) >> sub_y;
  1198. if (block_context.is_inter_predicted()) {
  1199. if (block_context.size < Block_8x8) {
  1200. for (auto y = 0; y < num_4x4_h; y++) {
  1201. for (auto x = 0; x < num_4x4_w; x++) {
  1202. TRY(m_decoder.predict_inter(plane, block_context, base_x + (4 * x), base_y + (4 * y), 4, 4, (y * num_4x4_w) + x));
  1203. }
  1204. }
  1205. } else {
  1206. TRY(m_decoder.predict_inter(plane, block_context, base_x, base_y, num_4x4_w * 4, num_4x4_h * 4, 0));
  1207. }
  1208. }
  1209. auto max_x = (block_context.frame_context.columns() * 8) >> sub_x;
  1210. auto max_y = (block_context.frame_context.rows() * 8) >> sub_y;
  1211. auto block_index = 0;
  1212. for (auto y = 0; y < num_4x4_h; y += step) {
  1213. for (auto x = 0; x < num_4x4_w; x += step) {
  1214. auto start_x = base_x + (4 * x);
  1215. auto start_y = base_y + (4 * y);
  1216. auto non_zero = false;
  1217. if (start_x < max_x && start_y < max_y) {
  1218. if (!block_context.is_inter_predicted())
  1219. TRY(m_decoder.predict_intra(plane, block_context, start_x, start_y, has_block_left || x > 0, has_block_above || y > 0, (x + step) < num_4x4_w, tx_size, block_index));
  1220. if (!block_context.should_skip_residuals) {
  1221. non_zero = TRY(tokens(block_context, plane, start_x, start_y, tx_size, block_index));
  1222. had_residual_tokens = had_residual_tokens || non_zero;
  1223. TRY(m_decoder.reconstruct(plane, block_context, start_x, start_y, tx_size));
  1224. }
  1225. }
  1226. auto& above_sub_context = m_above_nonzero_context[plane];
  1227. auto above_sub_context_index = start_x >> 2;
  1228. auto above_sub_context_end = min(above_sub_context_index + step, above_sub_context.size());
  1229. for (; above_sub_context_index < above_sub_context_end; above_sub_context_index++)
  1230. above_sub_context[above_sub_context_index] = non_zero;
  1231. auto& left_sub_context = m_left_nonzero_context[plane];
  1232. auto left_sub_context_index = start_y >> 2;
  1233. auto left_sub_context_end = min(left_sub_context_index + step, left_sub_context.size());
  1234. for (; left_sub_context_index < left_sub_context_end; left_sub_context_index++)
  1235. left_sub_context[left_sub_context_index] = non_zero;
  1236. block_index++;
  1237. }
  1238. }
  1239. }
  1240. return had_residual_tokens;
  1241. }
  1242. DecoderErrorOr<bool> Parser::tokens(BlockContext& block_context, size_t plane, u32 start_x, u32 start_y, TXSize tx_size, u32 block_index)
  1243. {
  1244. u32 segment_eob = 16 << (tx_size << 1);
  1245. auto const* scan = get_scan(block_context, plane, tx_size, block_index);
  1246. auto check_eob = true;
  1247. u32 c = 0;
  1248. for (; c < segment_eob; c++) {
  1249. auto pos = scan[c];
  1250. auto band = (tx_size == TX_4x4) ? coefband_4x4[c] : coefband_8x8plus[c];
  1251. auto tokens_context = TreeParser::get_tokens_context(block_context.frame_context.color_config.subsampling_x, block_context.frame_context.color_config.subsampling_y, block_context.frame_context.rows(), block_context.frame_context.columns(), m_above_nonzero_context, m_left_nonzero_context, m_token_cache, tx_size, m_tx_type, plane, start_x, start_y, pos, block_context.is_inter_predicted(), band, c);
  1252. if (check_eob) {
  1253. auto more_coefs = TRY_READ(TreeParser::parse_more_coefficients(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, tokens_context));
  1254. if (!more_coefs)
  1255. break;
  1256. }
  1257. auto token = TRY_READ(TreeParser::parse_token(*m_bit_stream, *m_probability_tables, *m_syntax_element_counter, tokens_context));
  1258. m_token_cache[pos] = energy_class[token];
  1259. if (token == ZeroToken) {
  1260. m_tokens[pos] = 0;
  1261. check_eob = false;
  1262. } else {
  1263. i32 coef = TRY(read_coef(block_context.frame_context.color_config.bit_depth, token));
  1264. bool sign_bit = TRY_READ(m_bit_stream->read_literal(1));
  1265. m_tokens[pos] = sign_bit ? -coef : coef;
  1266. check_eob = true;
  1267. }
  1268. }
  1269. for (u32 i = c; i < segment_eob; i++)
  1270. m_tokens[scan[i]] = 0;
  1271. return c > 0;
  1272. }
  1273. u32 const* Parser::get_scan(BlockContext const& block_context, size_t plane, TXSize tx_size, u32 block_index)
  1274. {
  1275. if (plane > 0 || tx_size == TX_32x32) {
  1276. m_tx_type = DCT_DCT;
  1277. } else if (tx_size == TX_4x4) {
  1278. if (block_context.frame_context.is_lossless() || block_context.is_inter_predicted())
  1279. m_tx_type = DCT_DCT;
  1280. else
  1281. m_tx_type = mode_to_txfm_map[to_underlying(block_context.size < Block_8x8 ? block_context.sub_block_prediction_modes[block_index] : block_context.y_prediction_mode())];
  1282. } else {
  1283. m_tx_type = mode_to_txfm_map[to_underlying(block_context.y_prediction_mode())];
  1284. }
  1285. if (tx_size == TX_4x4) {
  1286. if (m_tx_type == ADST_DCT)
  1287. return row_scan_4x4;
  1288. if (m_tx_type == DCT_ADST)
  1289. return col_scan_4x4;
  1290. return default_scan_4x4;
  1291. }
  1292. if (tx_size == TX_8x8) {
  1293. if (m_tx_type == ADST_DCT)
  1294. return row_scan_8x8;
  1295. if (m_tx_type == DCT_ADST)
  1296. return col_scan_8x8;
  1297. return default_scan_8x8;
  1298. }
  1299. if (tx_size == TX_16x16) {
  1300. if (m_tx_type == ADST_DCT)
  1301. return row_scan_16x16;
  1302. if (m_tx_type == DCT_ADST)
  1303. return col_scan_16x16;
  1304. return default_scan_16x16;
  1305. }
  1306. return default_scan_32x32;
  1307. }
  1308. DecoderErrorOr<i32> Parser::read_coef(u8 bit_depth, Token token)
  1309. {
  1310. auto cat = extra_bits[token][0];
  1311. auto num_extra = extra_bits[token][1];
  1312. u32 coef = extra_bits[token][2];
  1313. if (token == DctValCat6) {
  1314. for (size_t e = 0; e < (u8)(bit_depth - 8); e++) {
  1315. auto high_bit = TRY_READ(m_bit_stream->read_bool(255));
  1316. coef += high_bit << (5 + bit_depth - e);
  1317. }
  1318. }
  1319. for (size_t e = 0; e < num_extra; e++) {
  1320. auto coef_bit = TRY_READ(m_bit_stream->read_bool(cat_probs[cat][e]));
  1321. coef += coef_bit << (num_extra - 1 - e);
  1322. }
  1323. return coef;
  1324. }
  1325. // is_inside( candidateR, candidateC ) in the spec.
  1326. static bool motion_vector_is_inside_tile(TileContext const& tile_context, MotionVector vector)
  1327. {
  1328. if (vector.row() < 0)
  1329. return false;
  1330. if (vector.column() < 0)
  1331. return false;
  1332. u32 row_positive = vector.row();
  1333. u32 column_positive = vector.column();
  1334. return row_positive < tile_context.frame_context.rows() && column_positive >= tile_context.columns_start && column_positive < tile_context.columns_end;
  1335. }
  1336. // add_mv_ref_list( refList ) in the spec.
  1337. static void add_motion_vector_to_list_deduped(MotionVector const& vector, Vector<MotionVector, 2>& list)
  1338. {
  1339. if (list.size() >= 2)
  1340. return;
  1341. if (list.size() == 1 && vector == list[0])
  1342. return;
  1343. list.append(vector);
  1344. }
  1345. // get_block_mv( candidateR, candidateC, refList, usePrev ) in the spec.
  1346. MotionVectorCandidate Parser::get_motion_vector_from_current_or_previous_frame(BlockContext const& block_context, MotionVector candidate_vector, ReferenceIndex reference_index, bool use_prev)
  1347. {
  1348. if (use_prev) {
  1349. auto const& prev_context = m_previous_block_contexts.at(candidate_vector.row(), candidate_vector.column());
  1350. return { prev_context.ref_frames[reference_index], prev_context.primary_motion_vector_pair[reference_index] };
  1351. }
  1352. auto const& current_context = block_context.frame_block_contexts().at(candidate_vector.row(), candidate_vector.column());
  1353. return { current_context.ref_frames[reference_index], current_context.primary_motion_vector_pair()[reference_index] };
  1354. }
  1355. // if_same_ref_frame_add_mv( candidateR, candidateC, refFrame, usePrev ) in the spec.
  1356. void Parser::add_motion_vector_if_reference_frame_type_is_same(BlockContext const& block_context, MotionVector candidate_vector, ReferenceFrameType ref_frame, Vector<MotionVector, 2>& list, bool use_prev)
  1357. {
  1358. for (auto i = 0u; i < 2; i++) {
  1359. auto candidate = get_motion_vector_from_current_or_previous_frame(block_context, candidate_vector, static_cast<ReferenceIndex>(i), use_prev);
  1360. if (candidate.type == ref_frame) {
  1361. add_motion_vector_to_list_deduped(candidate.vector, list);
  1362. return;
  1363. }
  1364. }
  1365. }
  1366. // scale_mv( refList, refFrame ) in the spec.
  1367. static void apply_sign_bias_to_motion_vector(FrameContext const& frame_context, MotionVectorCandidate& candidate, ReferenceFrameType ref_frame)
  1368. {
  1369. if (frame_context.reference_frame_sign_biases[candidate.type] != frame_context.reference_frame_sign_biases[ref_frame])
  1370. candidate.vector *= -1;
  1371. }
  1372. // if_diff_ref_frame_add_mv( candidateR, candidateC, refFrame, usePrev ) in the spec.
  1373. void Parser::add_motion_vector_if_reference_frame_type_is_different(BlockContext const& block_context, MotionVector candidate_vector, ReferenceFrameType ref_frame, Vector<MotionVector, 2>& list, bool use_prev)
  1374. {
  1375. auto first_candidate = get_motion_vector_from_current_or_previous_frame(block_context, candidate_vector, ReferenceIndex::Primary, use_prev);
  1376. if (first_candidate.type > ReferenceFrameType::IntraFrame && first_candidate.type != ref_frame) {
  1377. apply_sign_bias_to_motion_vector(block_context.frame_context, first_candidate, ref_frame);
  1378. add_motion_vector_to_list_deduped(first_candidate.vector, list);
  1379. }
  1380. auto second_candidate = get_motion_vector_from_current_or_previous_frame(block_context, candidate_vector, ReferenceIndex::Secondary, use_prev);
  1381. auto mvs_are_same = first_candidate.vector == second_candidate.vector;
  1382. if (second_candidate.type > ReferenceFrameType::IntraFrame && second_candidate.type != ref_frame && !mvs_are_same) {
  1383. apply_sign_bias_to_motion_vector(block_context.frame_context, second_candidate, ref_frame);
  1384. add_motion_vector_to_list_deduped(second_candidate.vector, list);
  1385. }
  1386. }
  1387. // This function handles both clamp_mv_row( mvec, border ) and clamp_mv_col( mvec, border ) in the spec.
  1388. static MotionVector clamp_motion_vector(BlockContext const& block_context, MotionVector vector, i32 border)
  1389. {
  1390. i32 blocks_high = num_8x8_blocks_high_lookup[block_context.size];
  1391. // Casts must be done here to prevent subtraction underflow from wrapping the values.
  1392. i32 mb_to_top_edge = -8 * (static_cast<i32>(block_context.row) * MI_SIZE);
  1393. i32 mb_to_bottom_edge = 8 * ((static_cast<i32>(block_context.frame_context.rows()) - blocks_high - static_cast<i32>(block_context.row)) * MI_SIZE);
  1394. i32 blocks_wide = num_8x8_blocks_wide_lookup[block_context.size];
  1395. i32 mb_to_left_edge = -8 * (static_cast<i32>(block_context.column) * MI_SIZE);
  1396. i32 mb_to_right_edge = 8 * ((static_cast<i32>(block_context.frame_context.columns()) - blocks_wide - static_cast<i32>(block_context.column)) * MI_SIZE);
  1397. return {
  1398. clip_3(mb_to_top_edge - border, mb_to_bottom_edge + border, vector.row()),
  1399. clip_3(mb_to_left_edge - border, mb_to_right_edge + border, vector.column())
  1400. };
  1401. }
  1402. // 6.5.1 Find MV refs syntax
  1403. // find_mv_refs( refFrame, block ) in the spec.
  1404. MotionVectorPair Parser::find_reference_motion_vectors(BlockContext const& block_context, ReferenceFrameType reference_frame, i32 block)
  1405. {
  1406. bool different_ref_found = false;
  1407. u8 context_counter = 0;
  1408. Vector<MotionVector, 2> list;
  1409. MotionVector base_coordinates = MotionVector(block_context.row, block_context.column);
  1410. for (auto i = 0u; i < 2; i++) {
  1411. auto offset_vector = mv_ref_blocks[block_context.size][i];
  1412. auto candidate = base_coordinates + offset_vector;
  1413. if (motion_vector_is_inside_tile(block_context.tile_context, candidate)) {
  1414. different_ref_found = true;
  1415. auto context = block_context.frame_block_contexts().at(candidate.row(), candidate.column());
  1416. context_counter += mode_2_counter[to_underlying(context.y_mode)];
  1417. for (auto i = 0u; i < 2; i++) {
  1418. auto reference_index = static_cast<ReferenceIndex>(i);
  1419. if (context.ref_frames[reference_index] == reference_frame) {
  1420. // This section up until add_mv_ref_list() is defined in spec as get_sub_block_mv().
  1421. constexpr u8 idx_n_column_to_subblock[4][2] = {
  1422. { 1, 2 },
  1423. { 1, 3 },
  1424. { 3, 2 },
  1425. { 3, 3 }
  1426. };
  1427. auto index = block >= 0 ? idx_n_column_to_subblock[block][offset_vector.column() == 0] : 3;
  1428. add_motion_vector_to_list_deduped(context.sub_block_motion_vectors[index][reference_index], list);
  1429. break;
  1430. }
  1431. }
  1432. }
  1433. }
  1434. for (auto i = 2u; i < MVREF_NEIGHBOURS; i++) {
  1435. MotionVector candidate = base_coordinates + mv_ref_blocks[block_context.size][i];
  1436. if (motion_vector_is_inside_tile(block_context.tile_context, candidate)) {
  1437. different_ref_found = true;
  1438. add_motion_vector_if_reference_frame_type_is_same(block_context, candidate, reference_frame, list, false);
  1439. }
  1440. }
  1441. if (m_use_prev_frame_mvs)
  1442. add_motion_vector_if_reference_frame_type_is_same(block_context, base_coordinates, reference_frame, list, true);
  1443. if (different_ref_found) {
  1444. for (auto i = 0u; i < MVREF_NEIGHBOURS; i++) {
  1445. MotionVector candidate = base_coordinates + mv_ref_blocks[block_context.size][i];
  1446. if (motion_vector_is_inside_tile(block_context.tile_context, candidate))
  1447. add_motion_vector_if_reference_frame_type_is_different(block_context, candidate, reference_frame, list, false);
  1448. }
  1449. }
  1450. if (m_use_prev_frame_mvs)
  1451. add_motion_vector_if_reference_frame_type_is_different(block_context, base_coordinates, reference_frame, list, true);
  1452. m_mode_context[reference_frame] = counter_to_context[context_counter];
  1453. for (auto i = 0u; i < list.size(); i++) {
  1454. // clamp_mv_ref( i ) in the spec.
  1455. list[i] = clamp_motion_vector(block_context, list[i], MV_BORDER);
  1456. }
  1457. MotionVectorPair result;
  1458. for (auto i = 0u; i < list.size(); i++)
  1459. result[static_cast<ReferenceIndex>(i)] = list[i];
  1460. return result;
  1461. }
  1462. // find_best_ref_mvs( refList ) in the spec.
  1463. static void select_best_reference_motion_vectors(BlockContext& block_context, MotionVectorPair reference_motion_vectors, BlockMotionVectorCandidates& candidates, ReferenceIndex reference_index)
  1464. {
  1465. auto adjust_and_clamp_vector = [&](MotionVector& vector) {
  1466. auto delta_row = vector.row();
  1467. auto delta_column = vector.column();
  1468. if (!block_context.frame_context.high_precision_motion_vectors_allowed || !should_use_high_precision_motion_vector(vector)) {
  1469. if ((delta_row & 1) != 0)
  1470. delta_row += delta_row > 0 ? -1 : 1;
  1471. if ((delta_column & 1) != 0)
  1472. delta_column += delta_column > 0 ? -1 : 1;
  1473. }
  1474. vector = { delta_row, delta_column };
  1475. vector = clamp_motion_vector(block_context, vector, (BORDERINPIXELS - INTERP_EXTEND) << 3);
  1476. };
  1477. adjust_and_clamp_vector(reference_motion_vectors.primary);
  1478. adjust_and_clamp_vector(reference_motion_vectors.secondary);
  1479. candidates[reference_index].nearest_vector = reference_motion_vectors.primary;
  1480. candidates[reference_index].near_vector = reference_motion_vectors.secondary;
  1481. candidates[reference_index].best_vector = reference_motion_vectors.primary;
  1482. }
  1483. // append_sub8x8_mvs( block, refList ) in the spec.
  1484. void Parser::select_best_sub_block_reference_motion_vectors(BlockContext const& block_context, BlockMotionVectorCandidates& candidates, i32 block, ReferenceIndex reference_index)
  1485. {
  1486. Array<MotionVector, 2> sub_8x8_mvs;
  1487. MotionVectorPair reference_motion_vectors = find_reference_motion_vectors(block_context, block_context.reference_frame_types[reference_index], block);
  1488. auto destination_index = 0;
  1489. if (block == 0) {
  1490. sub_8x8_mvs[destination_index++] = reference_motion_vectors.primary;
  1491. sub_8x8_mvs[destination_index++] = reference_motion_vectors.secondary;
  1492. } else if (block <= 2) {
  1493. sub_8x8_mvs[destination_index++] = block_context.sub_block_motion_vectors[0][reference_index];
  1494. } else {
  1495. sub_8x8_mvs[destination_index++] = block_context.sub_block_motion_vectors[2][reference_index];
  1496. for (auto index = 1; index >= 0 && destination_index < 2; index--) {
  1497. auto block_vector = block_context.sub_block_motion_vectors[index][reference_index];
  1498. if (block_vector != sub_8x8_mvs[0])
  1499. sub_8x8_mvs[destination_index++] = block_vector;
  1500. }
  1501. }
  1502. for (auto n = 0u; n < 2 && destination_index < 2; n++) {
  1503. auto ref_list_vector = reference_motion_vectors[static_cast<ReferenceIndex>(n)];
  1504. if (ref_list_vector != sub_8x8_mvs[0])
  1505. sub_8x8_mvs[destination_index++] = ref_list_vector;
  1506. }
  1507. if (destination_index < 2)
  1508. sub_8x8_mvs[destination_index++] = {};
  1509. candidates[reference_index].nearest_vector = sub_8x8_mvs[0];
  1510. candidates[reference_index].near_vector = sub_8x8_mvs[1];
  1511. }
  1512. }