Parser.cpp 87 KB

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