vp9_bitstream.c 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. /*
  2. * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <assert.h>
  11. #include <stdio.h>
  12. #include <limits.h>
  13. #include "vpx/vpx_encoder.h"
  14. #include "vpx_dsp/bitwriter_buffer.h"
  15. #include "vpx_dsp/vpx_dsp_common.h"
  16. #include "vpx_mem/vpx_mem.h"
  17. #include "vpx_ports/mem_ops.h"
  18. #include "vpx_ports/system_state.h"
  19. #if CONFIG_BITSTREAM_DEBUG
  20. #include "vpx_util/vpx_debug_util.h"
  21. #endif // CONFIG_BITSTREAM_DEBUG
  22. #include "vp9/common/vp9_entropy.h"
  23. #include "vp9/common/vp9_entropymode.h"
  24. #include "vp9/common/vp9_entropymv.h"
  25. #include "vp9/common/vp9_mvref_common.h"
  26. #include "vp9/common/vp9_pred_common.h"
  27. #include "vp9/common/vp9_seg_common.h"
  28. #include "vp9/common/vp9_tile_common.h"
  29. #include "vp9/encoder/vp9_cost.h"
  30. #include "vp9/encoder/vp9_bitstream.h"
  31. #include "vp9/encoder/vp9_encodemv.h"
  32. #include "vp9/encoder/vp9_mcomp.h"
  33. #include "vp9/encoder/vp9_segmentation.h"
  34. #include "vp9/encoder/vp9_subexp.h"
  35. #include "vp9/encoder/vp9_tokenize.h"
  36. static const struct vp9_token intra_mode_encodings[INTRA_MODES] = {
  37. { 0, 1 }, { 6, 3 }, { 28, 5 }, { 30, 5 }, { 58, 6 },
  38. { 59, 6 }, { 126, 7 }, { 127, 7 }, { 62, 6 }, { 2, 2 }
  39. };
  40. static const struct vp9_token
  41. switchable_interp_encodings[SWITCHABLE_FILTERS] = { { 0, 1 },
  42. { 2, 2 },
  43. { 3, 2 } };
  44. static const struct vp9_token partition_encodings[PARTITION_TYPES] = {
  45. { 0, 1 }, { 2, 2 }, { 6, 3 }, { 7, 3 }
  46. };
  47. static const struct vp9_token inter_mode_encodings[INTER_MODES] = {
  48. { 2, 2 }, { 6, 3 }, { 0, 1 }, { 7, 3 }
  49. };
  50. static void write_intra_mode(vpx_writer *w, PREDICTION_MODE mode,
  51. const vpx_prob *probs) {
  52. vp9_write_token(w, vp9_intra_mode_tree, probs, &intra_mode_encodings[mode]);
  53. }
  54. static void write_inter_mode(vpx_writer *w, PREDICTION_MODE mode,
  55. const vpx_prob *probs) {
  56. assert(is_inter_mode(mode));
  57. vp9_write_token(w, vp9_inter_mode_tree, probs,
  58. &inter_mode_encodings[INTER_OFFSET(mode)]);
  59. }
  60. static void encode_unsigned_max(struct vpx_write_bit_buffer *wb, int data,
  61. int max) {
  62. vpx_wb_write_literal(wb, data, get_unsigned_bits(max));
  63. }
  64. static void prob_diff_update(const vpx_tree_index *tree,
  65. vpx_prob probs[/*n - 1*/],
  66. const unsigned int counts[/*n - 1*/], int n,
  67. vpx_writer *w) {
  68. int i;
  69. unsigned int branch_ct[32][2];
  70. // Assuming max number of probabilities <= 32
  71. assert(n <= 32);
  72. vp9_tree_probs_from_distribution(tree, branch_ct, counts);
  73. for (i = 0; i < n - 1; ++i)
  74. vp9_cond_prob_diff_update(w, &probs[i], branch_ct[i]);
  75. }
  76. static void write_selected_tx_size(const VP9_COMMON *cm,
  77. const MACROBLOCKD *const xd, vpx_writer *w) {
  78. TX_SIZE tx_size = xd->mi[0]->tx_size;
  79. BLOCK_SIZE bsize = xd->mi[0]->sb_type;
  80. const TX_SIZE max_tx_size = max_txsize_lookup[bsize];
  81. const vpx_prob *const tx_probs =
  82. get_tx_probs(max_tx_size, get_tx_size_context(xd), &cm->fc->tx_probs);
  83. vpx_write(w, tx_size != TX_4X4, tx_probs[0]);
  84. if (tx_size != TX_4X4 && max_tx_size >= TX_16X16) {
  85. vpx_write(w, tx_size != TX_8X8, tx_probs[1]);
  86. if (tx_size != TX_8X8 && max_tx_size >= TX_32X32)
  87. vpx_write(w, tx_size != TX_16X16, tx_probs[2]);
  88. }
  89. }
  90. static int write_skip(const VP9_COMMON *cm, const MACROBLOCKD *const xd,
  91. int segment_id, const MODE_INFO *mi, vpx_writer *w) {
  92. if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)) {
  93. return 1;
  94. } else {
  95. const int skip = mi->skip;
  96. vpx_write(w, skip, vp9_get_skip_prob(cm, xd));
  97. return skip;
  98. }
  99. }
  100. static void update_skip_probs(VP9_COMMON *cm, vpx_writer *w,
  101. FRAME_COUNTS *counts) {
  102. int k;
  103. for (k = 0; k < SKIP_CONTEXTS; ++k)
  104. vp9_cond_prob_diff_update(w, &cm->fc->skip_probs[k], counts->skip[k]);
  105. }
  106. static void update_switchable_interp_probs(VP9_COMMON *cm, vpx_writer *w,
  107. FRAME_COUNTS *counts) {
  108. int j;
  109. for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
  110. prob_diff_update(vp9_switchable_interp_tree,
  111. cm->fc->switchable_interp_prob[j],
  112. counts->switchable_interp[j], SWITCHABLE_FILTERS, w);
  113. }
  114. static void pack_mb_tokens(vpx_writer *w, TOKENEXTRA **tp,
  115. const TOKENEXTRA *const stop,
  116. vpx_bit_depth_t bit_depth) {
  117. const TOKENEXTRA *p;
  118. const vp9_extra_bit *const extra_bits =
  119. #if CONFIG_VP9_HIGHBITDEPTH
  120. (bit_depth == VPX_BITS_12)
  121. ? vp9_extra_bits_high12
  122. : (bit_depth == VPX_BITS_10) ? vp9_extra_bits_high10 : vp9_extra_bits;
  123. #else
  124. vp9_extra_bits;
  125. (void)bit_depth;
  126. #endif // CONFIG_VP9_HIGHBITDEPTH
  127. for (p = *tp; p < stop && p->token != EOSB_TOKEN; ++p) {
  128. if (p->token == EOB_TOKEN) {
  129. vpx_write(w, 0, p->context_tree[0]);
  130. continue;
  131. }
  132. vpx_write(w, 1, p->context_tree[0]);
  133. while (p->token == ZERO_TOKEN) {
  134. vpx_write(w, 0, p->context_tree[1]);
  135. ++p;
  136. if (p == stop || p->token == EOSB_TOKEN) {
  137. *tp = (TOKENEXTRA *)(uintptr_t)p + (p->token == EOSB_TOKEN);
  138. return;
  139. }
  140. }
  141. {
  142. const int t = p->token;
  143. const vpx_prob *const context_tree = p->context_tree;
  144. assert(t != ZERO_TOKEN);
  145. assert(t != EOB_TOKEN);
  146. assert(t != EOSB_TOKEN);
  147. vpx_write(w, 1, context_tree[1]);
  148. if (t == ONE_TOKEN) {
  149. vpx_write(w, 0, context_tree[2]);
  150. vpx_write_bit(w, p->extra & 1);
  151. } else { // t >= TWO_TOKEN && t < EOB_TOKEN
  152. const struct vp9_token *const a = &vp9_coef_encodings[t];
  153. const int v = a->value;
  154. const int n = a->len;
  155. const int e = p->extra;
  156. vpx_write(w, 1, context_tree[2]);
  157. vp9_write_tree(w, vp9_coef_con_tree,
  158. vp9_pareto8_full[context_tree[PIVOT_NODE] - 1], v,
  159. n - UNCONSTRAINED_NODES, 0);
  160. if (t >= CATEGORY1_TOKEN) {
  161. const vp9_extra_bit *const b = &extra_bits[t];
  162. const unsigned char *pb = b->prob;
  163. int v = e >> 1;
  164. int n = b->len; // number of bits in v, assumed nonzero
  165. do {
  166. const int bb = (v >> --n) & 1;
  167. vpx_write(w, bb, *pb++);
  168. } while (n);
  169. }
  170. vpx_write_bit(w, e & 1);
  171. }
  172. }
  173. }
  174. *tp = (TOKENEXTRA *)(uintptr_t)p + (p->token == EOSB_TOKEN);
  175. }
  176. static void write_segment_id(vpx_writer *w, const struct segmentation *seg,
  177. int segment_id) {
  178. if (seg->enabled && seg->update_map)
  179. vp9_write_tree(w, vp9_segment_tree, seg->tree_probs, segment_id, 3, 0);
  180. }
  181. // This function encodes the reference frame
  182. static void write_ref_frames(const VP9_COMMON *cm, const MACROBLOCKD *const xd,
  183. vpx_writer *w) {
  184. const MODE_INFO *const mi = xd->mi[0];
  185. const int is_compound = has_second_ref(mi);
  186. const int segment_id = mi->segment_id;
  187. // If segment level coding of this signal is disabled...
  188. // or the segment allows multiple reference frame options
  189. if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) {
  190. assert(!is_compound);
  191. assert(mi->ref_frame[0] ==
  192. get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME));
  193. } else {
  194. // does the feature use compound prediction or not
  195. // (if not specified at the frame/segment level)
  196. if (cm->reference_mode == REFERENCE_MODE_SELECT) {
  197. vpx_write(w, is_compound, vp9_get_reference_mode_prob(cm, xd));
  198. } else {
  199. assert((!is_compound) == (cm->reference_mode == SINGLE_REFERENCE));
  200. }
  201. if (is_compound) {
  202. const int idx = cm->ref_frame_sign_bias[cm->comp_fixed_ref];
  203. vpx_write(w, mi->ref_frame[!idx] == cm->comp_var_ref[1],
  204. vp9_get_pred_prob_comp_ref_p(cm, xd));
  205. } else {
  206. const int bit0 = mi->ref_frame[0] != LAST_FRAME;
  207. vpx_write(w, bit0, vp9_get_pred_prob_single_ref_p1(cm, xd));
  208. if (bit0) {
  209. const int bit1 = mi->ref_frame[0] != GOLDEN_FRAME;
  210. vpx_write(w, bit1, vp9_get_pred_prob_single_ref_p2(cm, xd));
  211. }
  212. }
  213. }
  214. }
  215. static void pack_inter_mode_mvs(
  216. VP9_COMP *cpi, const MACROBLOCKD *const xd,
  217. const MB_MODE_INFO_EXT *const mbmi_ext, vpx_writer *w,
  218. unsigned int *const max_mv_magnitude,
  219. int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE]) {
  220. VP9_COMMON *const cm = &cpi->common;
  221. const nmv_context *nmvc = &cm->fc->nmvc;
  222. const struct segmentation *const seg = &cm->seg;
  223. const MODE_INFO *const mi = xd->mi[0];
  224. const PREDICTION_MODE mode = mi->mode;
  225. const int segment_id = mi->segment_id;
  226. const BLOCK_SIZE bsize = mi->sb_type;
  227. const int allow_hp = cm->allow_high_precision_mv;
  228. const int is_inter = is_inter_block(mi);
  229. const int is_compound = has_second_ref(mi);
  230. int skip, ref;
  231. if (seg->update_map) {
  232. if (seg->temporal_update) {
  233. const int pred_flag = mi->seg_id_predicted;
  234. vpx_prob pred_prob = vp9_get_pred_prob_seg_id(seg, xd);
  235. vpx_write(w, pred_flag, pred_prob);
  236. if (!pred_flag) write_segment_id(w, seg, segment_id);
  237. } else {
  238. write_segment_id(w, seg, segment_id);
  239. }
  240. }
  241. skip = write_skip(cm, xd, segment_id, mi, w);
  242. if (!segfeature_active(seg, segment_id, SEG_LVL_REF_FRAME))
  243. vpx_write(w, is_inter, vp9_get_intra_inter_prob(cm, xd));
  244. if (bsize >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT &&
  245. !(is_inter && skip)) {
  246. write_selected_tx_size(cm, xd, w);
  247. }
  248. if (!is_inter) {
  249. if (bsize >= BLOCK_8X8) {
  250. write_intra_mode(w, mode, cm->fc->y_mode_prob[size_group_lookup[bsize]]);
  251. } else {
  252. int idx, idy;
  253. const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
  254. const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
  255. for (idy = 0; idy < 2; idy += num_4x4_h) {
  256. for (idx = 0; idx < 2; idx += num_4x4_w) {
  257. const PREDICTION_MODE b_mode = mi->bmi[idy * 2 + idx].as_mode;
  258. write_intra_mode(w, b_mode, cm->fc->y_mode_prob[0]);
  259. }
  260. }
  261. }
  262. write_intra_mode(w, mi->uv_mode, cm->fc->uv_mode_prob[mode]);
  263. } else {
  264. const int mode_ctx = mbmi_ext->mode_context[mi->ref_frame[0]];
  265. const vpx_prob *const inter_probs = cm->fc->inter_mode_probs[mode_ctx];
  266. write_ref_frames(cm, xd, w);
  267. // If segment skip is not enabled code the mode.
  268. if (!segfeature_active(seg, segment_id, SEG_LVL_SKIP)) {
  269. if (bsize >= BLOCK_8X8) {
  270. write_inter_mode(w, mode, inter_probs);
  271. }
  272. }
  273. if (cm->interp_filter == SWITCHABLE) {
  274. const int ctx = get_pred_context_switchable_interp(xd);
  275. vp9_write_token(w, vp9_switchable_interp_tree,
  276. cm->fc->switchable_interp_prob[ctx],
  277. &switchable_interp_encodings[mi->interp_filter]);
  278. ++interp_filter_selected[0][mi->interp_filter];
  279. } else {
  280. assert(mi->interp_filter == cm->interp_filter);
  281. }
  282. if (bsize < BLOCK_8X8) {
  283. const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
  284. const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
  285. int idx, idy;
  286. for (idy = 0; idy < 2; idy += num_4x4_h) {
  287. for (idx = 0; idx < 2; idx += num_4x4_w) {
  288. const int j = idy * 2 + idx;
  289. const PREDICTION_MODE b_mode = mi->bmi[j].as_mode;
  290. write_inter_mode(w, b_mode, inter_probs);
  291. if (b_mode == NEWMV) {
  292. for (ref = 0; ref < 1 + is_compound; ++ref)
  293. vp9_encode_mv(cpi, w, &mi->bmi[j].as_mv[ref].as_mv,
  294. &mbmi_ext->ref_mvs[mi->ref_frame[ref]][0].as_mv,
  295. nmvc, allow_hp, max_mv_magnitude);
  296. }
  297. }
  298. }
  299. } else {
  300. if (mode == NEWMV) {
  301. for (ref = 0; ref < 1 + is_compound; ++ref)
  302. vp9_encode_mv(cpi, w, &mi->mv[ref].as_mv,
  303. &mbmi_ext->ref_mvs[mi->ref_frame[ref]][0].as_mv, nmvc,
  304. allow_hp, max_mv_magnitude);
  305. }
  306. }
  307. }
  308. }
  309. static void write_mb_modes_kf(const VP9_COMMON *cm, const MACROBLOCKD *xd,
  310. vpx_writer *w) {
  311. const struct segmentation *const seg = &cm->seg;
  312. const MODE_INFO *const mi = xd->mi[0];
  313. const MODE_INFO *const above_mi = xd->above_mi;
  314. const MODE_INFO *const left_mi = xd->left_mi;
  315. const BLOCK_SIZE bsize = mi->sb_type;
  316. if (seg->update_map) write_segment_id(w, seg, mi->segment_id);
  317. write_skip(cm, xd, mi->segment_id, mi, w);
  318. if (bsize >= BLOCK_8X8 && cm->tx_mode == TX_MODE_SELECT)
  319. write_selected_tx_size(cm, xd, w);
  320. if (bsize >= BLOCK_8X8) {
  321. write_intra_mode(w, mi->mode, get_y_mode_probs(mi, above_mi, left_mi, 0));
  322. } else {
  323. const int num_4x4_w = num_4x4_blocks_wide_lookup[bsize];
  324. const int num_4x4_h = num_4x4_blocks_high_lookup[bsize];
  325. int idx, idy;
  326. for (idy = 0; idy < 2; idy += num_4x4_h) {
  327. for (idx = 0; idx < 2; idx += num_4x4_w) {
  328. const int block = idy * 2 + idx;
  329. write_intra_mode(w, mi->bmi[block].as_mode,
  330. get_y_mode_probs(mi, above_mi, left_mi, block));
  331. }
  332. }
  333. }
  334. write_intra_mode(w, mi->uv_mode, vp9_kf_uv_mode_prob[mi->mode]);
  335. }
  336. static void write_modes_b(
  337. VP9_COMP *cpi, MACROBLOCKD *const xd, const TileInfo *const tile,
  338. vpx_writer *w, TOKENEXTRA **tok, const TOKENEXTRA *const tok_end,
  339. int mi_row, int mi_col, unsigned int *const max_mv_magnitude,
  340. int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE]) {
  341. const VP9_COMMON *const cm = &cpi->common;
  342. const MB_MODE_INFO_EXT *const mbmi_ext =
  343. cpi->td.mb.mbmi_ext_base + (mi_row * cm->mi_cols + mi_col);
  344. MODE_INFO *m;
  345. xd->mi = cm->mi_grid_visible + (mi_row * cm->mi_stride + mi_col);
  346. m = xd->mi[0];
  347. set_mi_row_col(xd, tile, mi_row, num_8x8_blocks_high_lookup[m->sb_type],
  348. mi_col, num_8x8_blocks_wide_lookup[m->sb_type], cm->mi_rows,
  349. cm->mi_cols);
  350. if (frame_is_intra_only(cm)) {
  351. write_mb_modes_kf(cm, xd, w);
  352. } else {
  353. pack_inter_mode_mvs(cpi, xd, mbmi_ext, w, max_mv_magnitude,
  354. interp_filter_selected);
  355. }
  356. assert(*tok < tok_end);
  357. pack_mb_tokens(w, tok, tok_end, cm->bit_depth);
  358. }
  359. static void write_partition(const VP9_COMMON *const cm,
  360. const MACROBLOCKD *const xd, int hbs, int mi_row,
  361. int mi_col, PARTITION_TYPE p, BLOCK_SIZE bsize,
  362. vpx_writer *w) {
  363. const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
  364. const vpx_prob *const probs = xd->partition_probs[ctx];
  365. const int has_rows = (mi_row + hbs) < cm->mi_rows;
  366. const int has_cols = (mi_col + hbs) < cm->mi_cols;
  367. if (has_rows && has_cols) {
  368. vp9_write_token(w, vp9_partition_tree, probs, &partition_encodings[p]);
  369. } else if (!has_rows && has_cols) {
  370. assert(p == PARTITION_SPLIT || p == PARTITION_HORZ);
  371. vpx_write(w, p == PARTITION_SPLIT, probs[1]);
  372. } else if (has_rows && !has_cols) {
  373. assert(p == PARTITION_SPLIT || p == PARTITION_VERT);
  374. vpx_write(w, p == PARTITION_SPLIT, probs[2]);
  375. } else {
  376. assert(p == PARTITION_SPLIT);
  377. }
  378. }
  379. static void write_modes_sb(
  380. VP9_COMP *cpi, MACROBLOCKD *const xd, const TileInfo *const tile,
  381. vpx_writer *w, TOKENEXTRA **tok, const TOKENEXTRA *const tok_end,
  382. int mi_row, int mi_col, BLOCK_SIZE bsize,
  383. unsigned int *const max_mv_magnitude,
  384. int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE]) {
  385. const VP9_COMMON *const cm = &cpi->common;
  386. const int bsl = b_width_log2_lookup[bsize];
  387. const int bs = (1 << bsl) / 4;
  388. PARTITION_TYPE partition;
  389. BLOCK_SIZE subsize;
  390. const MODE_INFO *m = NULL;
  391. if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols) return;
  392. m = cm->mi_grid_visible[mi_row * cm->mi_stride + mi_col];
  393. partition = partition_lookup[bsl][m->sb_type];
  394. write_partition(cm, xd, bs, mi_row, mi_col, partition, bsize, w);
  395. subsize = get_subsize(bsize, partition);
  396. if (subsize < BLOCK_8X8) {
  397. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
  398. max_mv_magnitude, interp_filter_selected);
  399. } else {
  400. switch (partition) {
  401. case PARTITION_NONE:
  402. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
  403. max_mv_magnitude, interp_filter_selected);
  404. break;
  405. case PARTITION_HORZ:
  406. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
  407. max_mv_magnitude, interp_filter_selected);
  408. if (mi_row + bs < cm->mi_rows)
  409. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col,
  410. max_mv_magnitude, interp_filter_selected);
  411. break;
  412. case PARTITION_VERT:
  413. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col,
  414. max_mv_magnitude, interp_filter_selected);
  415. if (mi_col + bs < cm->mi_cols)
  416. write_modes_b(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col + bs,
  417. max_mv_magnitude, interp_filter_selected);
  418. break;
  419. default:
  420. assert(partition == PARTITION_SPLIT);
  421. write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col, subsize,
  422. max_mv_magnitude, interp_filter_selected);
  423. write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row, mi_col + bs,
  424. subsize, max_mv_magnitude, interp_filter_selected);
  425. write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col,
  426. subsize, max_mv_magnitude, interp_filter_selected);
  427. write_modes_sb(cpi, xd, tile, w, tok, tok_end, mi_row + bs, mi_col + bs,
  428. subsize, max_mv_magnitude, interp_filter_selected);
  429. break;
  430. }
  431. }
  432. // update partition context
  433. if (bsize >= BLOCK_8X8 &&
  434. (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
  435. update_partition_context(xd, mi_row, mi_col, subsize, bsize);
  436. }
  437. static void write_modes(
  438. VP9_COMP *cpi, MACROBLOCKD *const xd, const TileInfo *const tile,
  439. vpx_writer *w, int tile_row, int tile_col,
  440. unsigned int *const max_mv_magnitude,
  441. int interp_filter_selected[MAX_REF_FRAMES][SWITCHABLE]) {
  442. const VP9_COMMON *const cm = &cpi->common;
  443. int mi_row, mi_col, tile_sb_row;
  444. TOKENEXTRA *tok = NULL;
  445. TOKENEXTRA *tok_end = NULL;
  446. set_partition_probs(cm, xd);
  447. for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
  448. mi_row += MI_BLOCK_SIZE) {
  449. tile_sb_row = mi_cols_aligned_to_sb(mi_row - tile->mi_row_start) >>
  450. MI_BLOCK_SIZE_LOG2;
  451. tok = cpi->tplist[tile_row][tile_col][tile_sb_row].start;
  452. tok_end = tok + cpi->tplist[tile_row][tile_col][tile_sb_row].count;
  453. vp9_zero(xd->left_seg_context);
  454. for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
  455. mi_col += MI_BLOCK_SIZE)
  456. write_modes_sb(cpi, xd, tile, w, &tok, tok_end, mi_row, mi_col,
  457. BLOCK_64X64, max_mv_magnitude, interp_filter_selected);
  458. assert(tok == cpi->tplist[tile_row][tile_col][tile_sb_row].stop);
  459. }
  460. }
  461. static void build_tree_distribution(VP9_COMP *cpi, TX_SIZE tx_size,
  462. vp9_coeff_stats *coef_branch_ct,
  463. vp9_coeff_probs_model *coef_probs) {
  464. vp9_coeff_count *coef_counts = cpi->td.rd_counts.coef_counts[tx_size];
  465. unsigned int(*eob_branch_ct)[REF_TYPES][COEF_BANDS][COEFF_CONTEXTS] =
  466. cpi->common.counts.eob_branch[tx_size];
  467. int i, j, k, l, m;
  468. for (i = 0; i < PLANE_TYPES; ++i) {
  469. for (j = 0; j < REF_TYPES; ++j) {
  470. for (k = 0; k < COEF_BANDS; ++k) {
  471. for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
  472. vp9_tree_probs_from_distribution(vp9_coef_tree,
  473. coef_branch_ct[i][j][k][l],
  474. coef_counts[i][j][k][l]);
  475. coef_branch_ct[i][j][k][l][0][1] =
  476. eob_branch_ct[i][j][k][l] - coef_branch_ct[i][j][k][l][0][0];
  477. for (m = 0; m < UNCONSTRAINED_NODES; ++m)
  478. coef_probs[i][j][k][l][m] =
  479. get_binary_prob(coef_branch_ct[i][j][k][l][m][0],
  480. coef_branch_ct[i][j][k][l][m][1]);
  481. }
  482. }
  483. }
  484. }
  485. }
  486. static void update_coef_probs_common(vpx_writer *const bc, VP9_COMP *cpi,
  487. TX_SIZE tx_size,
  488. vp9_coeff_stats *frame_branch_ct,
  489. vp9_coeff_probs_model *new_coef_probs) {
  490. vp9_coeff_probs_model *old_coef_probs = cpi->common.fc->coef_probs[tx_size];
  491. const vpx_prob upd = DIFF_UPDATE_PROB;
  492. const int entropy_nodes_update = UNCONSTRAINED_NODES;
  493. int i, j, k, l, t;
  494. int stepsize = cpi->sf.coeff_prob_appx_step;
  495. switch (cpi->sf.use_fast_coef_updates) {
  496. case TWO_LOOP: {
  497. /* dry run to see if there is any update at all needed */
  498. int savings = 0;
  499. int update[2] = { 0, 0 };
  500. for (i = 0; i < PLANE_TYPES; ++i) {
  501. for (j = 0; j < REF_TYPES; ++j) {
  502. for (k = 0; k < COEF_BANDS; ++k) {
  503. for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
  504. for (t = 0; t < entropy_nodes_update; ++t) {
  505. vpx_prob newp = new_coef_probs[i][j][k][l][t];
  506. const vpx_prob oldp = old_coef_probs[i][j][k][l][t];
  507. int s;
  508. int u = 0;
  509. if (t == PIVOT_NODE)
  510. s = vp9_prob_diff_update_savings_search_model(
  511. frame_branch_ct[i][j][k][l][0], oldp, &newp, upd,
  512. stepsize);
  513. else
  514. s = vp9_prob_diff_update_savings_search(
  515. frame_branch_ct[i][j][k][l][t], oldp, &newp, upd);
  516. if (s > 0 && newp != oldp) u = 1;
  517. if (u)
  518. savings += s - (int)(vp9_cost_zero(upd));
  519. else
  520. savings -= (int)(vp9_cost_zero(upd));
  521. update[u]++;
  522. }
  523. }
  524. }
  525. }
  526. }
  527. // printf("Update %d %d, savings %d\n", update[0], update[1], savings);
  528. /* Is coef updated at all */
  529. if (update[1] == 0 || savings < 0) {
  530. vpx_write_bit(bc, 0);
  531. return;
  532. }
  533. vpx_write_bit(bc, 1);
  534. for (i = 0; i < PLANE_TYPES; ++i) {
  535. for (j = 0; j < REF_TYPES; ++j) {
  536. for (k = 0; k < COEF_BANDS; ++k) {
  537. for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
  538. // calc probs and branch cts for this frame only
  539. for (t = 0; t < entropy_nodes_update; ++t) {
  540. vpx_prob newp = new_coef_probs[i][j][k][l][t];
  541. vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
  542. const vpx_prob upd = DIFF_UPDATE_PROB;
  543. int s;
  544. int u = 0;
  545. if (t == PIVOT_NODE)
  546. s = vp9_prob_diff_update_savings_search_model(
  547. frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd,
  548. stepsize);
  549. else
  550. s = vp9_prob_diff_update_savings_search(
  551. frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd);
  552. if (s > 0 && newp != *oldp) u = 1;
  553. vpx_write(bc, u, upd);
  554. if (u) {
  555. /* send/use new probability */
  556. vp9_write_prob_diff_update(bc, newp, *oldp);
  557. *oldp = newp;
  558. }
  559. }
  560. }
  561. }
  562. }
  563. }
  564. return;
  565. }
  566. default: {
  567. int updates = 0;
  568. int noupdates_before_first = 0;
  569. assert(cpi->sf.use_fast_coef_updates == ONE_LOOP_REDUCED);
  570. for (i = 0; i < PLANE_TYPES; ++i) {
  571. for (j = 0; j < REF_TYPES; ++j) {
  572. for (k = 0; k < COEF_BANDS; ++k) {
  573. for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l) {
  574. // calc probs and branch cts for this frame only
  575. for (t = 0; t < entropy_nodes_update; ++t) {
  576. vpx_prob newp = new_coef_probs[i][j][k][l][t];
  577. vpx_prob *oldp = old_coef_probs[i][j][k][l] + t;
  578. int s;
  579. int u = 0;
  580. if (t == PIVOT_NODE) {
  581. s = vp9_prob_diff_update_savings_search_model(
  582. frame_branch_ct[i][j][k][l][0], *oldp, &newp, upd,
  583. stepsize);
  584. } else {
  585. s = vp9_prob_diff_update_savings_search(
  586. frame_branch_ct[i][j][k][l][t], *oldp, &newp, upd);
  587. }
  588. if (s > 0 && newp != *oldp) u = 1;
  589. updates += u;
  590. if (u == 0 && updates == 0) {
  591. noupdates_before_first++;
  592. continue;
  593. }
  594. if (u == 1 && updates == 1) {
  595. int v;
  596. // first update
  597. vpx_write_bit(bc, 1);
  598. for (v = 0; v < noupdates_before_first; ++v)
  599. vpx_write(bc, 0, upd);
  600. }
  601. vpx_write(bc, u, upd);
  602. if (u) {
  603. /* send/use new probability */
  604. vp9_write_prob_diff_update(bc, newp, *oldp);
  605. *oldp = newp;
  606. }
  607. }
  608. }
  609. }
  610. }
  611. }
  612. if (updates == 0) {
  613. vpx_write_bit(bc, 0); // no updates
  614. }
  615. return;
  616. }
  617. }
  618. }
  619. static void update_coef_probs(VP9_COMP *cpi, vpx_writer *w) {
  620. const TX_MODE tx_mode = cpi->common.tx_mode;
  621. const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
  622. TX_SIZE tx_size;
  623. for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size) {
  624. vp9_coeff_stats frame_branch_ct[PLANE_TYPES];
  625. vp9_coeff_probs_model frame_coef_probs[PLANE_TYPES];
  626. if (cpi->td.counts->tx.tx_totals[tx_size] <= 20 ||
  627. (tx_size >= TX_16X16 && cpi->sf.tx_size_search_method == USE_TX_8X8)) {
  628. vpx_write_bit(w, 0);
  629. } else {
  630. build_tree_distribution(cpi, tx_size, frame_branch_ct, frame_coef_probs);
  631. update_coef_probs_common(w, cpi, tx_size, frame_branch_ct,
  632. frame_coef_probs);
  633. }
  634. }
  635. }
  636. static void encode_loopfilter(struct loopfilter *lf,
  637. struct vpx_write_bit_buffer *wb) {
  638. int i;
  639. // Encode the loop filter level and type
  640. vpx_wb_write_literal(wb, lf->filter_level, 6);
  641. vpx_wb_write_literal(wb, lf->sharpness_level, 3);
  642. // Write out loop filter deltas applied at the MB level based on mode or
  643. // ref frame (if they are enabled).
  644. vpx_wb_write_bit(wb, lf->mode_ref_delta_enabled);
  645. if (lf->mode_ref_delta_enabled) {
  646. vpx_wb_write_bit(wb, lf->mode_ref_delta_update);
  647. if (lf->mode_ref_delta_update) {
  648. for (i = 0; i < MAX_REF_LF_DELTAS; i++) {
  649. const int delta = lf->ref_deltas[i];
  650. const int changed = delta != lf->last_ref_deltas[i];
  651. vpx_wb_write_bit(wb, changed);
  652. if (changed) {
  653. lf->last_ref_deltas[i] = delta;
  654. vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
  655. vpx_wb_write_bit(wb, delta < 0);
  656. }
  657. }
  658. for (i = 0; i < MAX_MODE_LF_DELTAS; i++) {
  659. const int delta = lf->mode_deltas[i];
  660. const int changed = delta != lf->last_mode_deltas[i];
  661. vpx_wb_write_bit(wb, changed);
  662. if (changed) {
  663. lf->last_mode_deltas[i] = delta;
  664. vpx_wb_write_literal(wb, abs(delta) & 0x3F, 6);
  665. vpx_wb_write_bit(wb, delta < 0);
  666. }
  667. }
  668. }
  669. }
  670. }
  671. static void write_delta_q(struct vpx_write_bit_buffer *wb, int delta_q) {
  672. if (delta_q != 0) {
  673. vpx_wb_write_bit(wb, 1);
  674. vpx_wb_write_literal(wb, abs(delta_q), 4);
  675. vpx_wb_write_bit(wb, delta_q < 0);
  676. } else {
  677. vpx_wb_write_bit(wb, 0);
  678. }
  679. }
  680. static void encode_quantization(const VP9_COMMON *const cm,
  681. struct vpx_write_bit_buffer *wb) {
  682. vpx_wb_write_literal(wb, cm->base_qindex, QINDEX_BITS);
  683. write_delta_q(wb, cm->y_dc_delta_q);
  684. write_delta_q(wb, cm->uv_dc_delta_q);
  685. write_delta_q(wb, cm->uv_ac_delta_q);
  686. }
  687. static void encode_segmentation(VP9_COMMON *cm, MACROBLOCKD *xd,
  688. struct vpx_write_bit_buffer *wb) {
  689. int i, j;
  690. const struct segmentation *seg = &cm->seg;
  691. vpx_wb_write_bit(wb, seg->enabled);
  692. if (!seg->enabled) return;
  693. // Segmentation map
  694. vpx_wb_write_bit(wb, seg->update_map);
  695. if (seg->update_map) {
  696. // Select the coding strategy (temporal or spatial)
  697. vp9_choose_segmap_coding_method(cm, xd);
  698. // Write out probabilities used to decode unpredicted macro-block segments
  699. for (i = 0; i < SEG_TREE_PROBS; i++) {
  700. const int prob = seg->tree_probs[i];
  701. const int update = prob != MAX_PROB;
  702. vpx_wb_write_bit(wb, update);
  703. if (update) vpx_wb_write_literal(wb, prob, 8);
  704. }
  705. // Write out the chosen coding method.
  706. vpx_wb_write_bit(wb, seg->temporal_update);
  707. if (seg->temporal_update) {
  708. for (i = 0; i < PREDICTION_PROBS; i++) {
  709. const int prob = seg->pred_probs[i];
  710. const int update = prob != MAX_PROB;
  711. vpx_wb_write_bit(wb, update);
  712. if (update) vpx_wb_write_literal(wb, prob, 8);
  713. }
  714. }
  715. }
  716. // Segmentation data
  717. vpx_wb_write_bit(wb, seg->update_data);
  718. if (seg->update_data) {
  719. vpx_wb_write_bit(wb, seg->abs_delta);
  720. for (i = 0; i < MAX_SEGMENTS; i++) {
  721. for (j = 0; j < SEG_LVL_MAX; j++) {
  722. const int active = segfeature_active(seg, i, j);
  723. vpx_wb_write_bit(wb, active);
  724. if (active) {
  725. const int data = get_segdata(seg, i, j);
  726. const int data_max = vp9_seg_feature_data_max(j);
  727. if (vp9_is_segfeature_signed(j)) {
  728. encode_unsigned_max(wb, abs(data), data_max);
  729. vpx_wb_write_bit(wb, data < 0);
  730. } else {
  731. encode_unsigned_max(wb, data, data_max);
  732. }
  733. }
  734. }
  735. }
  736. }
  737. }
  738. static void encode_txfm_probs(VP9_COMMON *cm, vpx_writer *w,
  739. FRAME_COUNTS *counts) {
  740. // Mode
  741. vpx_write_literal(w, VPXMIN(cm->tx_mode, ALLOW_32X32), 2);
  742. if (cm->tx_mode >= ALLOW_32X32)
  743. vpx_write_bit(w, cm->tx_mode == TX_MODE_SELECT);
  744. // Probabilities
  745. if (cm->tx_mode == TX_MODE_SELECT) {
  746. int i, j;
  747. unsigned int ct_8x8p[TX_SIZES - 3][2];
  748. unsigned int ct_16x16p[TX_SIZES - 2][2];
  749. unsigned int ct_32x32p[TX_SIZES - 1][2];
  750. for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
  751. tx_counts_to_branch_counts_8x8(counts->tx.p8x8[i], ct_8x8p);
  752. for (j = 0; j < TX_SIZES - 3; j++)
  753. vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p8x8[i][j], ct_8x8p[j]);
  754. }
  755. for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
  756. tx_counts_to_branch_counts_16x16(counts->tx.p16x16[i], ct_16x16p);
  757. for (j = 0; j < TX_SIZES - 2; j++)
  758. vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p16x16[i][j],
  759. ct_16x16p[j]);
  760. }
  761. for (i = 0; i < TX_SIZE_CONTEXTS; i++) {
  762. tx_counts_to_branch_counts_32x32(counts->tx.p32x32[i], ct_32x32p);
  763. for (j = 0; j < TX_SIZES - 1; j++)
  764. vp9_cond_prob_diff_update(w, &cm->fc->tx_probs.p32x32[i][j],
  765. ct_32x32p[j]);
  766. }
  767. }
  768. }
  769. static void write_interp_filter(INTERP_FILTER filter,
  770. struct vpx_write_bit_buffer *wb) {
  771. const int filter_to_literal[] = { 1, 0, 2, 3 };
  772. vpx_wb_write_bit(wb, filter == SWITCHABLE);
  773. if (filter != SWITCHABLE)
  774. vpx_wb_write_literal(wb, filter_to_literal[filter], 2);
  775. }
  776. static void fix_interp_filter(VP9_COMMON *cm, FRAME_COUNTS *counts) {
  777. if (cm->interp_filter == SWITCHABLE) {
  778. // Check to see if only one of the filters is actually used
  779. int count[SWITCHABLE_FILTERS];
  780. int i, j, c = 0;
  781. for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
  782. count[i] = 0;
  783. for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
  784. count[i] += counts->switchable_interp[j][i];
  785. c += (count[i] > 0);
  786. }
  787. if (c == 1) {
  788. // Only one filter is used. So set the filter at frame level
  789. for (i = 0; i < SWITCHABLE_FILTERS; ++i) {
  790. if (count[i]) {
  791. cm->interp_filter = i;
  792. break;
  793. }
  794. }
  795. }
  796. }
  797. }
  798. static void write_tile_info(const VP9_COMMON *const cm,
  799. struct vpx_write_bit_buffer *wb) {
  800. int min_log2_tile_cols, max_log2_tile_cols, ones;
  801. vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
  802. // columns
  803. ones = cm->log2_tile_cols - min_log2_tile_cols;
  804. while (ones--) vpx_wb_write_bit(wb, 1);
  805. if (cm->log2_tile_cols < max_log2_tile_cols) vpx_wb_write_bit(wb, 0);
  806. // rows
  807. vpx_wb_write_bit(wb, cm->log2_tile_rows != 0);
  808. if (cm->log2_tile_rows != 0) vpx_wb_write_bit(wb, cm->log2_tile_rows != 1);
  809. }
  810. int vp9_get_refresh_mask(VP9_COMP *cpi) {
  811. if (vp9_preserve_existing_gf(cpi)) {
  812. // We have decided to preserve the previously existing golden frame as our
  813. // new ARF frame. However, in the short term we leave it in the GF slot and,
  814. // if we're updating the GF with the current decoded frame, we save it
  815. // instead to the ARF slot.
  816. // Later, in the function vp9_encoder.c:vp9_update_reference_frames() we
  817. // will swap gld_fb_idx and alt_fb_idx to achieve our objective. We do it
  818. // there so that it can be done outside of the recode loop.
  819. // Note: This is highly specific to the use of ARF as a forward reference,
  820. // and this needs to be generalized as other uses are implemented
  821. // (like RTC/temporal scalability).
  822. return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
  823. (cpi->refresh_golden_frame << cpi->alt_fb_idx);
  824. } else {
  825. int arf_idx = cpi->alt_fb_idx;
  826. GF_GROUP *const gf_group = &cpi->twopass.gf_group;
  827. if (cpi->multi_layer_arf) {
  828. for (arf_idx = 0; arf_idx < REF_FRAMES; ++arf_idx) {
  829. if (arf_idx != cpi->alt_fb_idx && arf_idx != cpi->lst_fb_idx &&
  830. arf_idx != cpi->gld_fb_idx) {
  831. int idx;
  832. for (idx = 0; idx < gf_group->stack_size; ++idx)
  833. if (arf_idx == gf_group->arf_index_stack[idx]) break;
  834. if (idx == gf_group->stack_size) break;
  835. }
  836. }
  837. }
  838. cpi->twopass.gf_group.top_arf_idx = arf_idx;
  839. if (cpi->use_svc && cpi->svc.use_set_ref_frame_config &&
  840. cpi->svc.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS)
  841. return cpi->svc.update_buffer_slot[cpi->svc.spatial_layer_id];
  842. return (cpi->refresh_last_frame << cpi->lst_fb_idx) |
  843. (cpi->refresh_golden_frame << cpi->gld_fb_idx) |
  844. (cpi->refresh_alt_ref_frame << arf_idx);
  845. }
  846. }
  847. static int encode_tile_worker(void *arg1, void *arg2) {
  848. VP9_COMP *cpi = (VP9_COMP *)arg1;
  849. VP9BitstreamWorkerData *data = (VP9BitstreamWorkerData *)arg2;
  850. MACROBLOCKD *const xd = &data->xd;
  851. const int tile_row = 0;
  852. vpx_start_encode(&data->bit_writer, data->dest);
  853. write_modes(cpi, xd, &cpi->tile_data[data->tile_idx].tile_info,
  854. &data->bit_writer, tile_row, data->tile_idx,
  855. &data->max_mv_magnitude, data->interp_filter_selected);
  856. vpx_stop_encode(&data->bit_writer);
  857. return 1;
  858. }
  859. void vp9_bitstream_encode_tiles_buffer_dealloc(VP9_COMP *const cpi) {
  860. if (cpi->vp9_bitstream_worker_data) {
  861. int i;
  862. for (i = 1; i < cpi->num_workers; ++i) {
  863. vpx_free(cpi->vp9_bitstream_worker_data[i].dest);
  864. }
  865. vpx_free(cpi->vp9_bitstream_worker_data);
  866. cpi->vp9_bitstream_worker_data = NULL;
  867. }
  868. }
  869. static int encode_tiles_buffer_alloc(VP9_COMP *const cpi) {
  870. int i;
  871. const size_t worker_data_size =
  872. cpi->num_workers * sizeof(*cpi->vp9_bitstream_worker_data);
  873. cpi->vp9_bitstream_worker_data = vpx_memalign(16, worker_data_size);
  874. memset(cpi->vp9_bitstream_worker_data, 0, worker_data_size);
  875. if (!cpi->vp9_bitstream_worker_data) return 1;
  876. for (i = 1; i < cpi->num_workers; ++i) {
  877. cpi->vp9_bitstream_worker_data[i].dest_size =
  878. cpi->oxcf.width * cpi->oxcf.height;
  879. cpi->vp9_bitstream_worker_data[i].dest =
  880. vpx_malloc(cpi->vp9_bitstream_worker_data[i].dest_size);
  881. if (!cpi->vp9_bitstream_worker_data[i].dest) return 1;
  882. }
  883. return 0;
  884. }
  885. static size_t encode_tiles_mt(VP9_COMP *cpi, uint8_t *data_ptr) {
  886. const VPxWorkerInterface *const winterface = vpx_get_worker_interface();
  887. VP9_COMMON *const cm = &cpi->common;
  888. const int tile_cols = 1 << cm->log2_tile_cols;
  889. const int num_workers = cpi->num_workers;
  890. size_t total_size = 0;
  891. int tile_col = 0;
  892. if (!cpi->vp9_bitstream_worker_data ||
  893. cpi->vp9_bitstream_worker_data[1].dest_size >
  894. (cpi->oxcf.width * cpi->oxcf.height)) {
  895. vp9_bitstream_encode_tiles_buffer_dealloc(cpi);
  896. if (encode_tiles_buffer_alloc(cpi)) return 0;
  897. }
  898. while (tile_col < tile_cols) {
  899. int i, j;
  900. for (i = 0; i < num_workers && tile_col < tile_cols; ++i) {
  901. VPxWorker *const worker = &cpi->workers[i];
  902. VP9BitstreamWorkerData *const data = &cpi->vp9_bitstream_worker_data[i];
  903. // Populate the worker data.
  904. data->xd = cpi->td.mb.e_mbd;
  905. data->tile_idx = tile_col;
  906. data->max_mv_magnitude = cpi->max_mv_magnitude;
  907. memset(data->interp_filter_selected, 0,
  908. sizeof(data->interp_filter_selected[0][0]) * SWITCHABLE);
  909. // First thread can directly write into the output buffer.
  910. if (i == 0) {
  911. // If this worker happens to be for the last tile, then do not offset it
  912. // by 4 for the tile size.
  913. data->dest =
  914. data_ptr + total_size + (tile_col == tile_cols - 1 ? 0 : 4);
  915. }
  916. worker->data1 = cpi;
  917. worker->data2 = data;
  918. worker->hook = encode_tile_worker;
  919. worker->had_error = 0;
  920. if (i < num_workers - 1) {
  921. winterface->launch(worker);
  922. } else {
  923. winterface->execute(worker);
  924. }
  925. ++tile_col;
  926. }
  927. for (j = 0; j < i; ++j) {
  928. VPxWorker *const worker = &cpi->workers[j];
  929. VP9BitstreamWorkerData *const data =
  930. (VP9BitstreamWorkerData *)worker->data2;
  931. uint32_t tile_size;
  932. int k;
  933. if (!winterface->sync(worker)) return 0;
  934. tile_size = data->bit_writer.pos;
  935. // Aggregate per-thread bitstream stats.
  936. cpi->max_mv_magnitude =
  937. VPXMAX(cpi->max_mv_magnitude, data->max_mv_magnitude);
  938. for (k = 0; k < SWITCHABLE; ++k) {
  939. cpi->interp_filter_selected[0][k] += data->interp_filter_selected[0][k];
  940. }
  941. // Prefix the size of the tile on all but the last.
  942. if (tile_col != tile_cols || j < i - 1) {
  943. mem_put_be32(data_ptr + total_size, tile_size);
  944. total_size += 4;
  945. }
  946. if (j > 0) {
  947. memcpy(data_ptr + total_size, data->dest, tile_size);
  948. }
  949. total_size += tile_size;
  950. }
  951. }
  952. return total_size;
  953. }
  954. static size_t encode_tiles(VP9_COMP *cpi, uint8_t *data_ptr) {
  955. VP9_COMMON *const cm = &cpi->common;
  956. MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
  957. vpx_writer residual_bc;
  958. int tile_row, tile_col;
  959. size_t total_size = 0;
  960. const int tile_cols = 1 << cm->log2_tile_cols;
  961. const int tile_rows = 1 << cm->log2_tile_rows;
  962. memset(cm->above_seg_context, 0,
  963. sizeof(*cm->above_seg_context) * mi_cols_aligned_to_sb(cm->mi_cols));
  964. // Encoding tiles in parallel is done only for realtime mode now. In other
  965. // modes the speed up is insignificant and requires further testing to ensure
  966. // that it does not make the overall process worse in any case.
  967. if (cpi->oxcf.mode == REALTIME && cpi->num_workers > 1 && tile_rows == 1 &&
  968. tile_cols > 1) {
  969. return encode_tiles_mt(cpi, data_ptr);
  970. }
  971. for (tile_row = 0; tile_row < tile_rows; tile_row++) {
  972. for (tile_col = 0; tile_col < tile_cols; tile_col++) {
  973. int tile_idx = tile_row * tile_cols + tile_col;
  974. if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1)
  975. vpx_start_encode(&residual_bc, data_ptr + total_size + 4);
  976. else
  977. vpx_start_encode(&residual_bc, data_ptr + total_size);
  978. write_modes(cpi, xd, &cpi->tile_data[tile_idx].tile_info, &residual_bc,
  979. tile_row, tile_col, &cpi->max_mv_magnitude,
  980. cpi->interp_filter_selected);
  981. vpx_stop_encode(&residual_bc);
  982. if (tile_col < tile_cols - 1 || tile_row < tile_rows - 1) {
  983. // size of this tile
  984. mem_put_be32(data_ptr + total_size, residual_bc.pos);
  985. total_size += 4;
  986. }
  987. total_size += residual_bc.pos;
  988. }
  989. }
  990. return total_size;
  991. }
  992. static void write_render_size(const VP9_COMMON *cm,
  993. struct vpx_write_bit_buffer *wb) {
  994. const int scaling_active =
  995. cm->width != cm->render_width || cm->height != cm->render_height;
  996. vpx_wb_write_bit(wb, scaling_active);
  997. if (scaling_active) {
  998. vpx_wb_write_literal(wb, cm->render_width - 1, 16);
  999. vpx_wb_write_literal(wb, cm->render_height - 1, 16);
  1000. }
  1001. }
  1002. static void write_frame_size(const VP9_COMMON *cm,
  1003. struct vpx_write_bit_buffer *wb) {
  1004. vpx_wb_write_literal(wb, cm->width - 1, 16);
  1005. vpx_wb_write_literal(wb, cm->height - 1, 16);
  1006. write_render_size(cm, wb);
  1007. }
  1008. static void write_frame_size_with_refs(VP9_COMP *cpi,
  1009. struct vpx_write_bit_buffer *wb) {
  1010. VP9_COMMON *const cm = &cpi->common;
  1011. int found = 0;
  1012. MV_REFERENCE_FRAME ref_frame;
  1013. for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
  1014. YV12_BUFFER_CONFIG *cfg = get_ref_frame_buffer(cpi, ref_frame);
  1015. // Set "found" to 0 for temporal svc and for spatial svc key frame
  1016. if (cpi->use_svc &&
  1017. ((cpi->svc.number_temporal_layers > 1 &&
  1018. cpi->oxcf.rc_mode == VPX_CBR) ||
  1019. (cpi->svc.number_spatial_layers > 1 &&
  1020. cpi->svc.layer_context[cpi->svc.spatial_layer_id].is_key_frame))) {
  1021. found = 0;
  1022. } else if (cfg != NULL) {
  1023. found =
  1024. cm->width == cfg->y_crop_width && cm->height == cfg->y_crop_height;
  1025. }
  1026. vpx_wb_write_bit(wb, found);
  1027. if (found) {
  1028. break;
  1029. }
  1030. }
  1031. if (!found) {
  1032. vpx_wb_write_literal(wb, cm->width - 1, 16);
  1033. vpx_wb_write_literal(wb, cm->height - 1, 16);
  1034. }
  1035. write_render_size(cm, wb);
  1036. }
  1037. static void write_sync_code(struct vpx_write_bit_buffer *wb) {
  1038. vpx_wb_write_literal(wb, VP9_SYNC_CODE_0, 8);
  1039. vpx_wb_write_literal(wb, VP9_SYNC_CODE_1, 8);
  1040. vpx_wb_write_literal(wb, VP9_SYNC_CODE_2, 8);
  1041. }
  1042. static void write_profile(BITSTREAM_PROFILE profile,
  1043. struct vpx_write_bit_buffer *wb) {
  1044. switch (profile) {
  1045. case PROFILE_0: vpx_wb_write_literal(wb, 0, 2); break;
  1046. case PROFILE_1: vpx_wb_write_literal(wb, 2, 2); break;
  1047. case PROFILE_2: vpx_wb_write_literal(wb, 1, 2); break;
  1048. default:
  1049. assert(profile == PROFILE_3);
  1050. vpx_wb_write_literal(wb, 6, 3);
  1051. break;
  1052. }
  1053. }
  1054. static void write_bitdepth_colorspace_sampling(
  1055. VP9_COMMON *const cm, struct vpx_write_bit_buffer *wb) {
  1056. if (cm->profile >= PROFILE_2) {
  1057. assert(cm->bit_depth > VPX_BITS_8);
  1058. vpx_wb_write_bit(wb, cm->bit_depth == VPX_BITS_10 ? 0 : 1);
  1059. }
  1060. vpx_wb_write_literal(wb, cm->color_space, 3);
  1061. if (cm->color_space != VPX_CS_SRGB) {
  1062. // 0: [16, 235] (i.e. xvYCC), 1: [0, 255]
  1063. vpx_wb_write_bit(wb, cm->color_range);
  1064. if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
  1065. assert(cm->subsampling_x != 1 || cm->subsampling_y != 1);
  1066. vpx_wb_write_bit(wb, cm->subsampling_x);
  1067. vpx_wb_write_bit(wb, cm->subsampling_y);
  1068. vpx_wb_write_bit(wb, 0); // unused
  1069. } else {
  1070. assert(cm->subsampling_x == 1 && cm->subsampling_y == 1);
  1071. }
  1072. } else {
  1073. assert(cm->profile == PROFILE_1 || cm->profile == PROFILE_3);
  1074. vpx_wb_write_bit(wb, 0); // unused
  1075. }
  1076. }
  1077. static void write_uncompressed_header(VP9_COMP *cpi,
  1078. struct vpx_write_bit_buffer *wb) {
  1079. VP9_COMMON *const cm = &cpi->common;
  1080. MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
  1081. vpx_wb_write_literal(wb, VP9_FRAME_MARKER, 2);
  1082. write_profile(cm->profile, wb);
  1083. // If to use show existing frame.
  1084. vpx_wb_write_bit(wb, cm->show_existing_frame);
  1085. if (cm->show_existing_frame) {
  1086. vpx_wb_write_literal(wb, cpi->alt_fb_idx, 3);
  1087. return;
  1088. }
  1089. vpx_wb_write_bit(wb, cm->frame_type);
  1090. vpx_wb_write_bit(wb, cm->show_frame);
  1091. vpx_wb_write_bit(wb, cm->error_resilient_mode);
  1092. if (cm->frame_type == KEY_FRAME) {
  1093. write_sync_code(wb);
  1094. write_bitdepth_colorspace_sampling(cm, wb);
  1095. write_frame_size(cm, wb);
  1096. } else {
  1097. if (!cm->show_frame) vpx_wb_write_bit(wb, cm->intra_only);
  1098. if (!cm->error_resilient_mode)
  1099. vpx_wb_write_literal(wb, cm->reset_frame_context, 2);
  1100. if (cm->intra_only) {
  1101. write_sync_code(wb);
  1102. // Note for profile 0, 420 8bpp is assumed.
  1103. if (cm->profile > PROFILE_0) {
  1104. write_bitdepth_colorspace_sampling(cm, wb);
  1105. }
  1106. vpx_wb_write_literal(wb, vp9_get_refresh_mask(cpi), REF_FRAMES);
  1107. write_frame_size(cm, wb);
  1108. } else {
  1109. MV_REFERENCE_FRAME ref_frame;
  1110. vpx_wb_write_literal(wb, vp9_get_refresh_mask(cpi), REF_FRAMES);
  1111. for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) {
  1112. assert(get_ref_frame_map_idx(cpi, ref_frame) != INVALID_IDX);
  1113. vpx_wb_write_literal(wb, get_ref_frame_map_idx(cpi, ref_frame),
  1114. REF_FRAMES_LOG2);
  1115. vpx_wb_write_bit(wb, cm->ref_frame_sign_bias[ref_frame]);
  1116. }
  1117. write_frame_size_with_refs(cpi, wb);
  1118. vpx_wb_write_bit(wb, cm->allow_high_precision_mv);
  1119. fix_interp_filter(cm, cpi->td.counts);
  1120. write_interp_filter(cm->interp_filter, wb);
  1121. }
  1122. }
  1123. if (!cm->error_resilient_mode) {
  1124. vpx_wb_write_bit(wb, cm->refresh_frame_context);
  1125. vpx_wb_write_bit(wb, cm->frame_parallel_decoding_mode);
  1126. }
  1127. vpx_wb_write_literal(wb, cm->frame_context_idx, FRAME_CONTEXTS_LOG2);
  1128. encode_loopfilter(&cm->lf, wb);
  1129. encode_quantization(cm, wb);
  1130. encode_segmentation(cm, xd, wb);
  1131. write_tile_info(cm, wb);
  1132. }
  1133. static size_t write_compressed_header(VP9_COMP *cpi, uint8_t *data) {
  1134. VP9_COMMON *const cm = &cpi->common;
  1135. MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
  1136. FRAME_CONTEXT *const fc = cm->fc;
  1137. FRAME_COUNTS *counts = cpi->td.counts;
  1138. vpx_writer header_bc;
  1139. vpx_start_encode(&header_bc, data);
  1140. if (xd->lossless)
  1141. cm->tx_mode = ONLY_4X4;
  1142. else
  1143. encode_txfm_probs(cm, &header_bc, counts);
  1144. update_coef_probs(cpi, &header_bc);
  1145. update_skip_probs(cm, &header_bc, counts);
  1146. if (!frame_is_intra_only(cm)) {
  1147. int i;
  1148. for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
  1149. prob_diff_update(vp9_inter_mode_tree, cm->fc->inter_mode_probs[i],
  1150. counts->inter_mode[i], INTER_MODES, &header_bc);
  1151. if (cm->interp_filter == SWITCHABLE)
  1152. update_switchable_interp_probs(cm, &header_bc, counts);
  1153. for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
  1154. vp9_cond_prob_diff_update(&header_bc, &fc->intra_inter_prob[i],
  1155. counts->intra_inter[i]);
  1156. if (cpi->allow_comp_inter_inter) {
  1157. const int use_compound_pred = cm->reference_mode != SINGLE_REFERENCE;
  1158. const int use_hybrid_pred = cm->reference_mode == REFERENCE_MODE_SELECT;
  1159. vpx_write_bit(&header_bc, use_compound_pred);
  1160. if (use_compound_pred) {
  1161. vpx_write_bit(&header_bc, use_hybrid_pred);
  1162. if (use_hybrid_pred)
  1163. for (i = 0; i < COMP_INTER_CONTEXTS; i++)
  1164. vp9_cond_prob_diff_update(&header_bc, &fc->comp_inter_prob[i],
  1165. counts->comp_inter[i]);
  1166. }
  1167. }
  1168. if (cm->reference_mode != COMPOUND_REFERENCE) {
  1169. for (i = 0; i < REF_CONTEXTS; i++) {
  1170. vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][0],
  1171. counts->single_ref[i][0]);
  1172. vp9_cond_prob_diff_update(&header_bc, &fc->single_ref_prob[i][1],
  1173. counts->single_ref[i][1]);
  1174. }
  1175. }
  1176. if (cm->reference_mode != SINGLE_REFERENCE)
  1177. for (i = 0; i < REF_CONTEXTS; i++)
  1178. vp9_cond_prob_diff_update(&header_bc, &fc->comp_ref_prob[i],
  1179. counts->comp_ref[i]);
  1180. for (i = 0; i < BLOCK_SIZE_GROUPS; ++i)
  1181. prob_diff_update(vp9_intra_mode_tree, cm->fc->y_mode_prob[i],
  1182. counts->y_mode[i], INTRA_MODES, &header_bc);
  1183. for (i = 0; i < PARTITION_CONTEXTS; ++i)
  1184. prob_diff_update(vp9_partition_tree, fc->partition_prob[i],
  1185. counts->partition[i], PARTITION_TYPES, &header_bc);
  1186. vp9_write_nmv_probs(cm, cm->allow_high_precision_mv, &header_bc,
  1187. &counts->mv);
  1188. }
  1189. vpx_stop_encode(&header_bc);
  1190. assert(header_bc.pos <= 0xffff);
  1191. return header_bc.pos;
  1192. }
  1193. void vp9_pack_bitstream(VP9_COMP *cpi, uint8_t *dest, size_t *size) {
  1194. uint8_t *data = dest;
  1195. size_t first_part_size, uncompressed_hdr_size;
  1196. struct vpx_write_bit_buffer wb = { data, 0 };
  1197. struct vpx_write_bit_buffer saved_wb;
  1198. #if CONFIG_BITSTREAM_DEBUG
  1199. bitstream_queue_reset_write();
  1200. #endif
  1201. write_uncompressed_header(cpi, &wb);
  1202. // Skip the rest coding process if use show existing frame.
  1203. if (cpi->common.show_existing_frame) {
  1204. uncompressed_hdr_size = vpx_wb_bytes_written(&wb);
  1205. data += uncompressed_hdr_size;
  1206. *size = data - dest;
  1207. return;
  1208. }
  1209. saved_wb = wb;
  1210. vpx_wb_write_literal(&wb, 0, 16); // don't know in advance first part. size
  1211. uncompressed_hdr_size = vpx_wb_bytes_written(&wb);
  1212. data += uncompressed_hdr_size;
  1213. vpx_clear_system_state();
  1214. first_part_size = write_compressed_header(cpi, data);
  1215. data += first_part_size;
  1216. // TODO(jbb): Figure out what to do if first_part_size > 16 bits.
  1217. vpx_wb_write_literal(&saved_wb, (int)first_part_size, 16);
  1218. data += encode_tiles(cpi, data);
  1219. *size = data - dest;
  1220. }