vp9_bitstream.c 48 KB

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