Parser.cpp 85 KB

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