Parser.cpp 83 KB

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