2
0

vp9_ratectrl.c 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  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 <limits.h>
  12. #include <math.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include "vpx_dsp/vpx_dsp_common.h"
  17. #include "vpx_mem/vpx_mem.h"
  18. #include "vpx_ports/mem.h"
  19. #include "vpx_ports/system_state.h"
  20. #include "vp9/common/vp9_alloccommon.h"
  21. #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
  22. #include "vp9/common/vp9_common.h"
  23. #include "vp9/common/vp9_entropymode.h"
  24. #include "vp9/common/vp9_quant_common.h"
  25. #include "vp9/common/vp9_seg_common.h"
  26. #include "vp9/encoder/vp9_encodemv.h"
  27. #include "vp9/encoder/vp9_ratectrl.h"
  28. // Max rate target for 1080P and below encodes under normal circumstances
  29. // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
  30. #define MAX_MB_RATE 250
  31. #define MAXRATE_1080P 2025000
  32. #define DEFAULT_KF_BOOST 2000
  33. #define DEFAULT_GF_BOOST 2000
  34. #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
  35. #define MIN_BPB_FACTOR 0.005
  36. #define MAX_BPB_FACTOR 50
  37. #define FRAME_OVERHEAD_BITS 200
  38. #if CONFIG_VP9_HIGHBITDEPTH
  39. #define ASSIGN_MINQ_TABLE(bit_depth, name) \
  40. do { \
  41. switch (bit_depth) { \
  42. case VPX_BITS_8: name = name##_8; break; \
  43. case VPX_BITS_10: name = name##_10; break; \
  44. case VPX_BITS_12: name = name##_12; break; \
  45. default: \
  46. assert(0 && \
  47. "bit_depth should be VPX_BITS_8, VPX_BITS_10" \
  48. " or VPX_BITS_12"); \
  49. name = NULL; \
  50. } \
  51. } while (0)
  52. #else
  53. #define ASSIGN_MINQ_TABLE(bit_depth, name) \
  54. do { \
  55. (void)bit_depth; \
  56. name = name##_8; \
  57. } while (0)
  58. #endif
  59. // Tables relating active max Q to active min Q
  60. static int kf_low_motion_minq_8[QINDEX_RANGE];
  61. static int kf_high_motion_minq_8[QINDEX_RANGE];
  62. static int arfgf_low_motion_minq_8[QINDEX_RANGE];
  63. static int arfgf_high_motion_minq_8[QINDEX_RANGE];
  64. static int inter_minq_8[QINDEX_RANGE];
  65. static int rtc_minq_8[QINDEX_RANGE];
  66. #if CONFIG_VP9_HIGHBITDEPTH
  67. static int kf_low_motion_minq_10[QINDEX_RANGE];
  68. static int kf_high_motion_minq_10[QINDEX_RANGE];
  69. static int arfgf_low_motion_minq_10[QINDEX_RANGE];
  70. static int arfgf_high_motion_minq_10[QINDEX_RANGE];
  71. static int inter_minq_10[QINDEX_RANGE];
  72. static int rtc_minq_10[QINDEX_RANGE];
  73. static int kf_low_motion_minq_12[QINDEX_RANGE];
  74. static int kf_high_motion_minq_12[QINDEX_RANGE];
  75. static int arfgf_low_motion_minq_12[QINDEX_RANGE];
  76. static int arfgf_high_motion_minq_12[QINDEX_RANGE];
  77. static int inter_minq_12[QINDEX_RANGE];
  78. static int rtc_minq_12[QINDEX_RANGE];
  79. #endif
  80. static int gf_high = 2000;
  81. static int gf_low = 400;
  82. static int kf_high = 5000;
  83. static int kf_low = 400;
  84. // Functions to compute the active minq lookup table entries based on a
  85. // formulaic approach to facilitate easier adjustment of the Q tables.
  86. // The formulae were derived from computing a 3rd order polynomial best
  87. // fit to the original data (after plotting real maxq vs minq (not q index))
  88. static int get_minq_index(double maxq, double x3, double x2, double x1,
  89. vpx_bit_depth_t bit_depth) {
  90. int i;
  91. const double minqtarget = VPXMIN(((x3 * maxq + x2) * maxq + x1) * maxq, maxq);
  92. // Special case handling to deal with the step from q2.0
  93. // down to lossless mode represented by q 1.0.
  94. if (minqtarget <= 2.0) return 0;
  95. for (i = 0; i < QINDEX_RANGE; i++) {
  96. if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth)) return i;
  97. }
  98. return QINDEX_RANGE - 1;
  99. }
  100. static void init_minq_luts(int *kf_low_m, int *kf_high_m, int *arfgf_low,
  101. int *arfgf_high, int *inter, int *rtc,
  102. vpx_bit_depth_t bit_depth) {
  103. int i;
  104. for (i = 0; i < QINDEX_RANGE; i++) {
  105. const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
  106. kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
  107. kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
  108. arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
  109. arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
  110. inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
  111. rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
  112. }
  113. }
  114. void vp9_rc_init_minq_luts(void) {
  115. init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
  116. arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
  117. inter_minq_8, rtc_minq_8, VPX_BITS_8);
  118. #if CONFIG_VP9_HIGHBITDEPTH
  119. init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
  120. arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
  121. inter_minq_10, rtc_minq_10, VPX_BITS_10);
  122. init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
  123. arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
  124. inter_minq_12, rtc_minq_12, VPX_BITS_12);
  125. #endif
  126. }
  127. // These functions use formulaic calculations to make playing with the
  128. // quantizer tables easier. If necessary they can be replaced by lookup
  129. // tables if and when things settle down in the experimental bitstream
  130. double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
  131. // Convert the index to a real Q value (scaled down to match old Q values)
  132. #if CONFIG_VP9_HIGHBITDEPTH
  133. switch (bit_depth) {
  134. case VPX_BITS_8: return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
  135. case VPX_BITS_10: return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
  136. case VPX_BITS_12: return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
  137. default:
  138. assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
  139. return -1.0;
  140. }
  141. #else
  142. return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
  143. #endif
  144. }
  145. int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
  146. double correction_factor, vpx_bit_depth_t bit_depth) {
  147. const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
  148. int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
  149. assert(correction_factor <= MAX_BPB_FACTOR &&
  150. correction_factor >= MIN_BPB_FACTOR);
  151. // q based adjustment to baseline enumerator
  152. enumerator += (int)(enumerator * q) >> 12;
  153. return (int)(enumerator * correction_factor / q);
  154. }
  155. int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
  156. double correction_factor,
  157. vpx_bit_depth_t bit_depth) {
  158. const int bpm =
  159. (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor, bit_depth));
  160. return VPXMAX(FRAME_OVERHEAD_BITS,
  161. (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
  162. }
  163. int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
  164. const RATE_CONTROL *rc = &cpi->rc;
  165. const VP9EncoderConfig *oxcf = &cpi->oxcf;
  166. const int min_frame_target =
  167. VPXMAX(rc->min_frame_bandwidth, rc->avg_frame_bandwidth >> 5);
  168. if (target < min_frame_target) target = min_frame_target;
  169. if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
  170. // If there is an active ARF at this location use the minimum
  171. // bits on this frame even if it is a constructed arf.
  172. // The active maximum quantizer insures that an appropriate
  173. // number of bits will be spent if needed for constructed ARFs.
  174. target = min_frame_target;
  175. }
  176. // Clip the frame target to the maximum allowed value.
  177. if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
  178. if (oxcf->rc_max_inter_bitrate_pct) {
  179. const int max_rate =
  180. rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
  181. target = VPXMIN(target, max_rate);
  182. }
  183. return target;
  184. }
  185. int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
  186. const RATE_CONTROL *rc = &cpi->rc;
  187. const VP9EncoderConfig *oxcf = &cpi->oxcf;
  188. if (oxcf->rc_max_intra_bitrate_pct) {
  189. const int max_rate =
  190. rc->avg_frame_bandwidth * oxcf->rc_max_intra_bitrate_pct / 100;
  191. target = VPXMIN(target, max_rate);
  192. }
  193. if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
  194. return target;
  195. }
  196. // Update the buffer level for higher temporal layers, given the encoded current
  197. // temporal layer.
  198. static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
  199. int i = 0;
  200. int current_temporal_layer = svc->temporal_layer_id;
  201. for (i = current_temporal_layer + 1; i < svc->number_temporal_layers; ++i) {
  202. const int layer =
  203. LAYER_IDS_TO_IDX(svc->spatial_layer_id, i, svc->number_temporal_layers);
  204. LAYER_CONTEXT *lc = &svc->layer_context[layer];
  205. RATE_CONTROL *lrc = &lc->rc;
  206. int bits_off_for_this_layer =
  207. (int)(lc->target_bandwidth / lc->framerate - encoded_frame_size);
  208. lrc->bits_off_target += bits_off_for_this_layer;
  209. // Clip buffer level to maximum buffer size for the layer.
  210. lrc->bits_off_target =
  211. VPXMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
  212. lrc->buffer_level = lrc->bits_off_target;
  213. }
  214. }
  215. // Update the buffer level: leaky bucket model.
  216. static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
  217. const VP9_COMMON *const cm = &cpi->common;
  218. RATE_CONTROL *const rc = &cpi->rc;
  219. // Non-viewable frames are a special case and are treated as pure overhead.
  220. if (!cm->show_frame) {
  221. rc->bits_off_target -= encoded_frame_size;
  222. } else {
  223. rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
  224. }
  225. // Clip the buffer level to the maximum specified buffer size.
  226. rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
  227. // For screen-content mode, and if frame-dropper is off, don't let buffer
  228. // level go below threshold, given here as -rc->maximum_ buffer_size.
  229. if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
  230. cpi->oxcf.drop_frames_water_mark == 0)
  231. rc->bits_off_target = VPXMAX(rc->bits_off_target, -rc->maximum_buffer_size);
  232. rc->buffer_level = rc->bits_off_target;
  233. if (is_one_pass_cbr_svc(cpi)) {
  234. update_layer_buffer_level(&cpi->svc, encoded_frame_size);
  235. }
  236. }
  237. int vp9_rc_get_default_min_gf_interval(int width, int height,
  238. double framerate) {
  239. // Assume we do not need any constraint lower than 4K 20 fps
  240. static const double factor_safe = 3840 * 2160 * 20.0;
  241. const double factor = width * height * framerate;
  242. const int default_interval =
  243. clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
  244. if (factor <= factor_safe)
  245. return default_interval;
  246. else
  247. return VPXMAX(default_interval,
  248. (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
  249. // Note this logic makes:
  250. // 4K24: 5
  251. // 4K30: 6
  252. // 4K60: 12
  253. }
  254. int vp9_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
  255. int interval = VPXMIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
  256. interval += (interval & 0x01); // Round to even value
  257. return VPXMAX(interval, min_gf_interval);
  258. }
  259. void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
  260. int i;
  261. if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
  262. rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
  263. rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
  264. } else {
  265. rc->avg_frame_qindex[KEY_FRAME] =
  266. (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
  267. rc->avg_frame_qindex[INTER_FRAME] =
  268. (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
  269. }
  270. rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
  271. rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
  272. rc->buffer_level = rc->starting_buffer_level;
  273. rc->bits_off_target = rc->starting_buffer_level;
  274. rc->rolling_target_bits = rc->avg_frame_bandwidth;
  275. rc->rolling_actual_bits = rc->avg_frame_bandwidth;
  276. rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
  277. rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
  278. rc->total_actual_bits = 0;
  279. rc->total_target_bits = 0;
  280. rc->total_target_vs_actual = 0;
  281. rc->avg_frame_low_motion = 0;
  282. rc->count_last_scene_change = 0;
  283. rc->af_ratio_onepass_vbr = 10;
  284. rc->prev_avg_source_sad_lag = 0;
  285. rc->high_source_sad = 0;
  286. rc->high_source_sad_lagindex = -1;
  287. rc->fac_active_worst_inter = 150;
  288. rc->fac_active_worst_gf = 100;
  289. rc->force_qpmin = 0;
  290. for (i = 0; i < MAX_LAG_BUFFERS; ++i) rc->avg_source_sad[i] = 0;
  291. rc->frames_since_key = 8; // Sensible default for first frame.
  292. rc->this_key_frame_forced = 0;
  293. rc->next_key_frame_forced = 0;
  294. rc->source_alt_ref_pending = 0;
  295. rc->source_alt_ref_active = 0;
  296. rc->frames_till_gf_update_due = 0;
  297. rc->ni_av_qi = oxcf->worst_allowed_q;
  298. rc->ni_tot_qi = 0;
  299. rc->ni_frames = 0;
  300. rc->tot_q = 0.0;
  301. rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
  302. for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
  303. rc->rate_correction_factors[i] = 1.0;
  304. }
  305. rc->min_gf_interval = oxcf->min_gf_interval;
  306. rc->max_gf_interval = oxcf->max_gf_interval;
  307. if (rc->min_gf_interval == 0)
  308. rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
  309. oxcf->width, oxcf->height, oxcf->init_framerate);
  310. if (rc->max_gf_interval == 0)
  311. rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
  312. oxcf->init_framerate, rc->min_gf_interval);
  313. rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
  314. }
  315. int vp9_rc_drop_frame(VP9_COMP *cpi) {
  316. const VP9EncoderConfig *oxcf = &cpi->oxcf;
  317. RATE_CONTROL *const rc = &cpi->rc;
  318. if (!oxcf->drop_frames_water_mark ||
  319. (is_one_pass_cbr_svc(cpi) &&
  320. cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode)) {
  321. return 0;
  322. } else {
  323. if (rc->buffer_level < 0) {
  324. // Always drop if buffer is below 0.
  325. return 1;
  326. } else {
  327. // If buffer is below drop_mark, for now just drop every other frame
  328. // (starting with the next frame) until it increases back over drop_mark.
  329. int drop_mark =
  330. (int)(oxcf->drop_frames_water_mark * rc->optimal_buffer_level / 100);
  331. if ((rc->buffer_level > drop_mark) && (rc->decimation_factor > 0)) {
  332. --rc->decimation_factor;
  333. } else if (rc->buffer_level <= drop_mark && rc->decimation_factor == 0) {
  334. rc->decimation_factor = 1;
  335. }
  336. if (rc->decimation_factor > 0) {
  337. if (rc->decimation_count > 0) {
  338. --rc->decimation_count;
  339. return 1;
  340. } else {
  341. rc->decimation_count = rc->decimation_factor;
  342. return 0;
  343. }
  344. } else {
  345. rc->decimation_count = 0;
  346. return 0;
  347. }
  348. }
  349. }
  350. }
  351. static double get_rate_correction_factor(const VP9_COMP *cpi) {
  352. const RATE_CONTROL *const rc = &cpi->rc;
  353. double rcf;
  354. if (cpi->common.frame_type == KEY_FRAME) {
  355. rcf = rc->rate_correction_factors[KF_STD];
  356. } else if (cpi->oxcf.pass == 2) {
  357. RATE_FACTOR_LEVEL rf_lvl =
  358. cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
  359. rcf = rc->rate_correction_factors[rf_lvl];
  360. } else {
  361. if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
  362. !rc->is_src_frame_alt_ref && !cpi->use_svc &&
  363. (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
  364. rcf = rc->rate_correction_factors[GF_ARF_STD];
  365. else
  366. rcf = rc->rate_correction_factors[INTER_NORMAL];
  367. }
  368. rcf *= rcf_mult[rc->frame_size_selector];
  369. return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
  370. }
  371. static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
  372. RATE_CONTROL *const rc = &cpi->rc;
  373. // Normalize RCF to account for the size-dependent scaling factor.
  374. factor /= rcf_mult[cpi->rc.frame_size_selector];
  375. factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
  376. if (cpi->common.frame_type == KEY_FRAME) {
  377. rc->rate_correction_factors[KF_STD] = factor;
  378. } else if (cpi->oxcf.pass == 2) {
  379. RATE_FACTOR_LEVEL rf_lvl =
  380. cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
  381. rc->rate_correction_factors[rf_lvl] = factor;
  382. } else {
  383. if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
  384. !rc->is_src_frame_alt_ref && !cpi->use_svc &&
  385. (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
  386. rc->rate_correction_factors[GF_ARF_STD] = factor;
  387. else
  388. rc->rate_correction_factors[INTER_NORMAL] = factor;
  389. }
  390. }
  391. void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
  392. const VP9_COMMON *const cm = &cpi->common;
  393. int correction_factor = 100;
  394. double rate_correction_factor = get_rate_correction_factor(cpi);
  395. double adjustment_limit;
  396. int projected_size_based_on_q = 0;
  397. // Do not update the rate factors for arf overlay frames.
  398. if (cpi->rc.is_src_frame_alt_ref) return;
  399. // Clear down mmx registers to allow floating point in what follows
  400. vpx_clear_system_state();
  401. // Work out how big we would have expected the frame to be at this Q given
  402. // the current correction factor.
  403. // Stay in double to avoid int overflow when values are large
  404. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
  405. projected_size_based_on_q =
  406. vp9_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
  407. } else {
  408. projected_size_based_on_q =
  409. vp9_estimate_bits_at_q(cpi->common.frame_type, cm->base_qindex, cm->MBs,
  410. rate_correction_factor, cm->bit_depth);
  411. }
  412. // Work out a size correction factor.
  413. if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
  414. correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
  415. projected_size_based_on_q);
  416. // More heavily damped adjustment used if we have been oscillating either side
  417. // of target.
  418. adjustment_limit =
  419. 0.25 + 0.5 * VPXMIN(1, fabs(log10(0.01 * correction_factor)));
  420. cpi->rc.q_2_frame = cpi->rc.q_1_frame;
  421. cpi->rc.q_1_frame = cm->base_qindex;
  422. cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
  423. if (correction_factor > 110)
  424. cpi->rc.rc_1_frame = -1;
  425. else if (correction_factor < 90)
  426. cpi->rc.rc_1_frame = 1;
  427. else
  428. cpi->rc.rc_1_frame = 0;
  429. // Turn off oscilation detection in the case of massive overshoot.
  430. if (cpi->rc.rc_1_frame == -1 && cpi->rc.rc_2_frame == 1 &&
  431. correction_factor > 1000) {
  432. cpi->rc.rc_2_frame = 0;
  433. }
  434. if (correction_factor > 102) {
  435. // We are not already at the worst allowable quality
  436. correction_factor =
  437. (int)(100 + ((correction_factor - 100) * adjustment_limit));
  438. rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
  439. // Keep rate_correction_factor within limits
  440. if (rate_correction_factor > MAX_BPB_FACTOR)
  441. rate_correction_factor = MAX_BPB_FACTOR;
  442. } else if (correction_factor < 99) {
  443. // We are not already at the best allowable quality
  444. correction_factor =
  445. (int)(100 - ((100 - correction_factor) * adjustment_limit));
  446. rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
  447. // Keep rate_correction_factor within limits
  448. if (rate_correction_factor < MIN_BPB_FACTOR)
  449. rate_correction_factor = MIN_BPB_FACTOR;
  450. }
  451. set_rate_correction_factor(cpi, rate_correction_factor);
  452. }
  453. int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
  454. int active_best_quality, int active_worst_quality) {
  455. const VP9_COMMON *const cm = &cpi->common;
  456. int q = active_worst_quality;
  457. int last_error = INT_MAX;
  458. int i, target_bits_per_mb, bits_per_mb_at_this_q;
  459. const double correction_factor = get_rate_correction_factor(cpi);
  460. // Calculate required scaling factor based on target frame size and size of
  461. // frame produced using previous Q.
  462. target_bits_per_mb =
  463. (int)(((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs);
  464. i = active_best_quality;
  465. do {
  466. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
  467. cpi->svc.temporal_layer_id == 0) {
  468. bits_per_mb_at_this_q =
  469. (int)vp9_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
  470. } else {
  471. bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(
  472. cm->frame_type, i, correction_factor, cm->bit_depth);
  473. }
  474. if (bits_per_mb_at_this_q <= target_bits_per_mb) {
  475. if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
  476. q = i;
  477. else
  478. q = i - 1;
  479. break;
  480. } else {
  481. last_error = bits_per_mb_at_this_q - target_bits_per_mb;
  482. }
  483. } while (++i <= active_worst_quality);
  484. // In CBR mode, this makes sure q is between oscillating Qs to prevent
  485. // resonance.
  486. if (cpi->oxcf.rc_mode == VPX_CBR &&
  487. (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
  488. cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
  489. q = clamp(q, VPXMIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
  490. VPXMAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
  491. }
  492. return q;
  493. }
  494. static int get_active_quality(int q, int gfu_boost, int low, int high,
  495. int *low_motion_minq, int *high_motion_minq) {
  496. if (gfu_boost > high) {
  497. return low_motion_minq[q];
  498. } else if (gfu_boost < low) {
  499. return high_motion_minq[q];
  500. } else {
  501. const int gap = high - low;
  502. const int offset = high - gfu_boost;
  503. const int qdiff = high_motion_minq[q] - low_motion_minq[q];
  504. const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
  505. return low_motion_minq[q] + adjustment;
  506. }
  507. }
  508. static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
  509. vpx_bit_depth_t bit_depth) {
  510. int *kf_low_motion_minq;
  511. int *kf_high_motion_minq;
  512. ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
  513. ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
  514. return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
  515. kf_low_motion_minq, kf_high_motion_minq);
  516. }
  517. static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
  518. vpx_bit_depth_t bit_depth) {
  519. int *arfgf_low_motion_minq;
  520. int *arfgf_high_motion_minq;
  521. ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
  522. ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
  523. return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
  524. arfgf_low_motion_minq, arfgf_high_motion_minq);
  525. }
  526. static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
  527. const RATE_CONTROL *const rc = &cpi->rc;
  528. const unsigned int curr_frame = cpi->common.current_video_frame;
  529. int active_worst_quality;
  530. if (cpi->common.frame_type == KEY_FRAME) {
  531. active_worst_quality =
  532. curr_frame == 0 ? rc->worst_quality : rc->last_q[KEY_FRAME] << 1;
  533. } else {
  534. if (!rc->is_src_frame_alt_ref &&
  535. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
  536. active_worst_quality =
  537. curr_frame == 1
  538. ? rc->last_q[KEY_FRAME] * 5 >> 2
  539. : rc->last_q[INTER_FRAME] * rc->fac_active_worst_gf / 100;
  540. } else {
  541. active_worst_quality = curr_frame == 1
  542. ? rc->last_q[KEY_FRAME] << 1
  543. : rc->avg_frame_qindex[INTER_FRAME] *
  544. rc->fac_active_worst_inter / 100;
  545. }
  546. }
  547. return VPXMIN(active_worst_quality, rc->worst_quality);
  548. }
  549. // Adjust active_worst_quality level based on buffer level.
  550. static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
  551. // Adjust active_worst_quality: If buffer is above the optimal/target level,
  552. // bring active_worst_quality down depending on fullness of buffer.
  553. // If buffer is below the optimal level, let the active_worst_quality go from
  554. // ambient Q (at buffer = optimal level) to worst_quality level
  555. // (at buffer = critical level).
  556. const VP9_COMMON *const cm = &cpi->common;
  557. const RATE_CONTROL *rc = &cpi->rc;
  558. // Buffer level below which we push active_worst to worst_quality.
  559. int64_t critical_level = rc->optimal_buffer_level >> 3;
  560. int64_t buff_lvl_step = 0;
  561. int adjustment = 0;
  562. int active_worst_quality;
  563. int ambient_qp;
  564. unsigned int num_frames_weight_key = 5 * cpi->svc.number_temporal_layers;
  565. if (cm->frame_type == KEY_FRAME) return rc->worst_quality;
  566. // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
  567. // for the first few frames following key frame. These are both initialized
  568. // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
  569. // So for first few frames following key, the qp of that key frame is weighted
  570. // into the active_worst_quality setting.
  571. ambient_qp = (cm->current_video_frame < num_frames_weight_key)
  572. ? VPXMIN(rc->avg_frame_qindex[INTER_FRAME],
  573. rc->avg_frame_qindex[KEY_FRAME])
  574. : rc->avg_frame_qindex[INTER_FRAME];
  575. active_worst_quality = VPXMIN(rc->worst_quality, ambient_qp * 5 >> 2);
  576. if (rc->buffer_level > rc->optimal_buffer_level) {
  577. // Adjust down.
  578. // Maximum limit for down adjustment, ~30%.
  579. int max_adjustment_down = active_worst_quality / 3;
  580. if (max_adjustment_down) {
  581. buff_lvl_step = ((rc->maximum_buffer_size - rc->optimal_buffer_level) /
  582. max_adjustment_down);
  583. if (buff_lvl_step)
  584. adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
  585. buff_lvl_step);
  586. active_worst_quality -= adjustment;
  587. }
  588. } else if (rc->buffer_level > critical_level) {
  589. // Adjust up from ambient Q.
  590. if (critical_level) {
  591. buff_lvl_step = (rc->optimal_buffer_level - critical_level);
  592. if (buff_lvl_step) {
  593. adjustment = (int)((rc->worst_quality - ambient_qp) *
  594. (rc->optimal_buffer_level - rc->buffer_level) /
  595. buff_lvl_step);
  596. }
  597. active_worst_quality = ambient_qp + adjustment;
  598. }
  599. } else {
  600. // Set to worst_quality if buffer is below critical level.
  601. active_worst_quality = rc->worst_quality;
  602. }
  603. return active_worst_quality;
  604. }
  605. static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
  606. int *bottom_index,
  607. int *top_index) {
  608. const VP9_COMMON *const cm = &cpi->common;
  609. const RATE_CONTROL *const rc = &cpi->rc;
  610. int active_best_quality;
  611. int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
  612. int q;
  613. int *rtc_minq;
  614. ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
  615. if (frame_is_intra_only(cm)) {
  616. active_best_quality = rc->best_quality;
  617. // Handle the special case for key frames forced when we have reached
  618. // the maximum key frame interval. Here force the Q to a range
  619. // based on the ambient Q to reduce the risk of popping.
  620. if (rc->this_key_frame_forced) {
  621. int qindex = rc->last_boosted_qindex;
  622. double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  623. int delta_qindex = vp9_compute_qdelta(
  624. rc, last_boosted_q, (last_boosted_q * 0.75), cm->bit_depth);
  625. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  626. } else if (cm->current_video_frame > 0) {
  627. // not first frame of one pass and kf_boost is set
  628. double q_adj_factor = 1.0;
  629. double q_val;
  630. active_best_quality = get_kf_active_quality(
  631. rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
  632. // Allow somewhat lower kf minq with small image formats.
  633. if ((cm->width * cm->height) <= (352 * 288)) {
  634. q_adj_factor -= 0.25;
  635. }
  636. // Convert the adjustment factor to a qindex delta
  637. // on active_best_quality.
  638. q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
  639. active_best_quality +=
  640. vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
  641. }
  642. } else if (!rc->is_src_frame_alt_ref && !cpi->use_svc &&
  643. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
  644. // Use the lower of active_worst_quality and recent
  645. // average Q as basis for GF/ARF best Q limit unless last frame was
  646. // a key frame.
  647. if (rc->frames_since_key > 1 &&
  648. rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
  649. q = rc->avg_frame_qindex[INTER_FRAME];
  650. } else {
  651. q = active_worst_quality;
  652. }
  653. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  654. } else {
  655. // Use the lower of active_worst_quality and recent/average Q.
  656. if (cm->current_video_frame > 1) {
  657. if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
  658. active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
  659. else
  660. active_best_quality = rtc_minq[active_worst_quality];
  661. } else {
  662. if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
  663. active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
  664. else
  665. active_best_quality = rtc_minq[active_worst_quality];
  666. }
  667. }
  668. // Clip the active best and worst quality values to limits
  669. active_best_quality =
  670. clamp(active_best_quality, rc->best_quality, rc->worst_quality);
  671. active_worst_quality =
  672. clamp(active_worst_quality, active_best_quality, rc->worst_quality);
  673. *top_index = active_worst_quality;
  674. *bottom_index = active_best_quality;
  675. #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
  676. // Limit Q range for the adaptive loop.
  677. if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
  678. !(cm->current_video_frame == 0)) {
  679. int qdelta = 0;
  680. vpx_clear_system_state();
  681. qdelta = vp9_compute_qdelta_by_rate(
  682. &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
  683. *top_index = active_worst_quality + qdelta;
  684. *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
  685. }
  686. #endif
  687. // Special case code to try and match quality with forced key frames
  688. if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
  689. q = rc->last_boosted_qindex;
  690. } else {
  691. q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
  692. active_worst_quality);
  693. if (q > *top_index) {
  694. // Special case when we are targeting the max allowed rate
  695. if (rc->this_frame_target >= rc->max_frame_bandwidth)
  696. *top_index = q;
  697. else
  698. q = *top_index;
  699. }
  700. }
  701. assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
  702. assert(*bottom_index <= rc->worst_quality &&
  703. *bottom_index >= rc->best_quality);
  704. assert(q <= rc->worst_quality && q >= rc->best_quality);
  705. return q;
  706. }
  707. static int get_active_cq_level_one_pass(const RATE_CONTROL *rc,
  708. const VP9EncoderConfig *const oxcf) {
  709. static const double cq_adjust_threshold = 0.1;
  710. int active_cq_level = oxcf->cq_level;
  711. if (oxcf->rc_mode == VPX_CQ && rc->total_target_bits > 0) {
  712. const double x = (double)rc->total_actual_bits / rc->total_target_bits;
  713. if (x < cq_adjust_threshold) {
  714. active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
  715. }
  716. }
  717. return active_cq_level;
  718. }
  719. #define SMOOTH_PCT_MIN 0.1
  720. #define SMOOTH_PCT_DIV 0.05
  721. static int get_active_cq_level_two_pass(const TWO_PASS *twopass,
  722. const RATE_CONTROL *rc,
  723. const VP9EncoderConfig *const oxcf) {
  724. static const double cq_adjust_threshold = 0.1;
  725. int active_cq_level = oxcf->cq_level;
  726. if (oxcf->rc_mode == VPX_CQ) {
  727. if (twopass->mb_smooth_pct > SMOOTH_PCT_MIN) {
  728. active_cq_level -=
  729. (int)((twopass->mb_smooth_pct - SMOOTH_PCT_MIN) / SMOOTH_PCT_DIV);
  730. active_cq_level = VPXMAX(active_cq_level, 0);
  731. }
  732. if (rc->total_target_bits > 0) {
  733. const double x = (double)rc->total_actual_bits / rc->total_target_bits;
  734. if (x < cq_adjust_threshold) {
  735. active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
  736. }
  737. }
  738. }
  739. return active_cq_level;
  740. }
  741. static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
  742. int *bottom_index,
  743. int *top_index) {
  744. const VP9_COMMON *const cm = &cpi->common;
  745. const RATE_CONTROL *const rc = &cpi->rc;
  746. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  747. const int cq_level = get_active_cq_level_one_pass(rc, oxcf);
  748. int active_best_quality;
  749. int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
  750. int q;
  751. int *inter_minq;
  752. ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
  753. if (frame_is_intra_only(cm)) {
  754. if (oxcf->rc_mode == VPX_Q) {
  755. int qindex = cq_level;
  756. double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  757. int delta_qindex = vp9_compute_qdelta(rc, q, q * 0.25, cm->bit_depth);
  758. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  759. } else if (rc->this_key_frame_forced) {
  760. // Handle the special case for key frames forced when we have reached
  761. // the maximum key frame interval. Here force the Q to a range
  762. // based on the ambient Q to reduce the risk of popping.
  763. int qindex = rc->last_boosted_qindex;
  764. double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  765. int delta_qindex = vp9_compute_qdelta(
  766. rc, last_boosted_q, last_boosted_q * 0.75, cm->bit_depth);
  767. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  768. } else {
  769. // not first frame of one pass and kf_boost is set
  770. double q_adj_factor = 1.0;
  771. double q_val;
  772. active_best_quality = get_kf_active_quality(
  773. rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
  774. // Allow somewhat lower kf minq with small image formats.
  775. if ((cm->width * cm->height) <= (352 * 288)) {
  776. q_adj_factor -= 0.25;
  777. }
  778. // Convert the adjustment factor to a qindex delta
  779. // on active_best_quality.
  780. q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
  781. active_best_quality +=
  782. vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
  783. }
  784. } else if (!rc->is_src_frame_alt_ref &&
  785. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
  786. // Use the lower of active_worst_quality and recent
  787. // average Q as basis for GF/ARF best Q limit unless last frame was
  788. // a key frame.
  789. if (rc->frames_since_key > 1) {
  790. if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
  791. q = rc->avg_frame_qindex[INTER_FRAME];
  792. } else {
  793. q = active_worst_quality;
  794. }
  795. } else {
  796. q = rc->avg_frame_qindex[KEY_FRAME];
  797. }
  798. // For constrained quality dont allow Q less than the cq level
  799. if (oxcf->rc_mode == VPX_CQ) {
  800. if (q < cq_level) q = cq_level;
  801. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  802. // Constrained quality use slightly lower active best.
  803. active_best_quality = active_best_quality * 15 / 16;
  804. } else if (oxcf->rc_mode == VPX_Q) {
  805. int qindex = cq_level;
  806. double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  807. int delta_qindex;
  808. if (cpi->refresh_alt_ref_frame)
  809. delta_qindex = vp9_compute_qdelta(rc, q, q * 0.40, cm->bit_depth);
  810. else
  811. delta_qindex = vp9_compute_qdelta(rc, q, q * 0.50, cm->bit_depth);
  812. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  813. } else {
  814. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  815. }
  816. } else {
  817. if (oxcf->rc_mode == VPX_Q) {
  818. int qindex = cq_level;
  819. double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  820. double delta_rate[FIXED_GF_INTERVAL] = { 0.50, 1.0, 0.85, 1.0,
  821. 0.70, 1.0, 0.85, 1.0 };
  822. int delta_qindex = vp9_compute_qdelta(
  823. rc, q, q * delta_rate[cm->current_video_frame % FIXED_GF_INTERVAL],
  824. cm->bit_depth);
  825. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  826. } else {
  827. // Use the min of the average Q and active_worst_quality as basis for
  828. // active_best.
  829. if (cm->current_video_frame > 1) {
  830. q = VPXMIN(rc->avg_frame_qindex[INTER_FRAME], active_worst_quality);
  831. active_best_quality = inter_minq[q];
  832. } else {
  833. active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
  834. }
  835. // For the constrained quality mode we don't want
  836. // q to fall below the cq level.
  837. if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
  838. active_best_quality = cq_level;
  839. }
  840. }
  841. }
  842. // Clip the active best and worst quality values to limits
  843. active_best_quality =
  844. clamp(active_best_quality, rc->best_quality, rc->worst_quality);
  845. active_worst_quality =
  846. clamp(active_worst_quality, active_best_quality, rc->worst_quality);
  847. *top_index = active_worst_quality;
  848. *bottom_index = active_best_quality;
  849. #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
  850. {
  851. int qdelta = 0;
  852. vpx_clear_system_state();
  853. // Limit Q range for the adaptive loop.
  854. if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
  855. !(cm->current_video_frame == 0)) {
  856. qdelta = vp9_compute_qdelta_by_rate(
  857. &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
  858. } else if (!rc->is_src_frame_alt_ref &&
  859. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
  860. qdelta = vp9_compute_qdelta_by_rate(
  861. &cpi->rc, cm->frame_type, active_worst_quality, 1.75, cm->bit_depth);
  862. }
  863. *top_index = active_worst_quality + qdelta;
  864. *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
  865. }
  866. #endif
  867. if (oxcf->rc_mode == VPX_Q) {
  868. q = active_best_quality;
  869. // Special case code to try and match quality with forced key frames
  870. } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
  871. q = rc->last_boosted_qindex;
  872. } else {
  873. q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
  874. active_worst_quality);
  875. if (q > *top_index) {
  876. // Special case when we are targeting the max allowed rate
  877. if (rc->this_frame_target >= rc->max_frame_bandwidth)
  878. *top_index = q;
  879. else
  880. q = *top_index;
  881. }
  882. }
  883. assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
  884. assert(*bottom_index <= rc->worst_quality &&
  885. *bottom_index >= rc->best_quality);
  886. assert(q <= rc->worst_quality && q >= rc->best_quality);
  887. return q;
  888. }
  889. int vp9_frame_type_qdelta(const VP9_COMP *cpi, int rf_level, int q) {
  890. static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
  891. 1.00, // INTER_NORMAL
  892. 1.00, // INTER_HIGH
  893. 1.50, // GF_ARF_LOW
  894. 1.75, // GF_ARF_STD
  895. 2.00, // KF_STD
  896. };
  897. static const FRAME_TYPE frame_type[RATE_FACTOR_LEVELS] = {
  898. INTER_FRAME, INTER_FRAME, INTER_FRAME, INTER_FRAME, KEY_FRAME
  899. };
  900. const VP9_COMMON *const cm = &cpi->common;
  901. int qdelta =
  902. vp9_compute_qdelta_by_rate(&cpi->rc, frame_type[rf_level], q,
  903. rate_factor_deltas[rf_level], cm->bit_depth);
  904. return qdelta;
  905. }
  906. #define STATIC_MOTION_THRESH 95
  907. static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi, int *bottom_index,
  908. int *top_index) {
  909. const VP9_COMMON *const cm = &cpi->common;
  910. const RATE_CONTROL *const rc = &cpi->rc;
  911. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  912. const GF_GROUP *gf_group = &cpi->twopass.gf_group;
  913. const int cq_level = get_active_cq_level_two_pass(&cpi->twopass, rc, oxcf);
  914. int active_best_quality;
  915. int active_worst_quality = cpi->twopass.active_worst_quality;
  916. int q;
  917. int *inter_minq;
  918. ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
  919. if (frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) {
  920. // Handle the special case for key frames forced when we have reached
  921. // the maximum key frame interval. Here force the Q to a range
  922. // based on the ambient Q to reduce the risk of popping.
  923. if (rc->this_key_frame_forced) {
  924. double last_boosted_q;
  925. int delta_qindex;
  926. int qindex;
  927. if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
  928. qindex = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
  929. active_best_quality = qindex;
  930. last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  931. delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
  932. last_boosted_q * 1.25, cm->bit_depth);
  933. active_worst_quality =
  934. VPXMIN(qindex + delta_qindex, active_worst_quality);
  935. } else {
  936. qindex = rc->last_boosted_qindex;
  937. last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  938. delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
  939. last_boosted_q * 0.75, cm->bit_depth);
  940. active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
  941. }
  942. } else {
  943. // Not forced keyframe.
  944. double q_adj_factor = 1.0;
  945. double q_val;
  946. // Baseline value derived from cpi->active_worst_quality and kf boost.
  947. active_best_quality =
  948. get_kf_active_quality(rc, active_worst_quality, cm->bit_depth);
  949. // Allow somewhat lower kf minq with small image formats.
  950. if ((cm->width * cm->height) <= (352 * 288)) {
  951. q_adj_factor -= 0.25;
  952. }
  953. // Make a further adjustment based on the kf zero motion measure.
  954. q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
  955. // Convert the adjustment factor to a qindex delta
  956. // on active_best_quality.
  957. q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
  958. active_best_quality +=
  959. vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
  960. }
  961. } else if (!rc->is_src_frame_alt_ref &&
  962. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
  963. // Use the lower of active_worst_quality and recent
  964. // average Q as basis for GF/ARF best Q limit unless last frame was
  965. // a key frame.
  966. if (rc->frames_since_key > 1 &&
  967. rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
  968. q = rc->avg_frame_qindex[INTER_FRAME];
  969. } else {
  970. q = active_worst_quality;
  971. }
  972. // For constrained quality dont allow Q less than the cq level
  973. if (oxcf->rc_mode == VPX_CQ) {
  974. if (q < cq_level) q = cq_level;
  975. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  976. // Constrained quality use slightly lower active best.
  977. active_best_quality = active_best_quality * 15 / 16;
  978. } else if (oxcf->rc_mode == VPX_Q) {
  979. if (!cpi->refresh_alt_ref_frame) {
  980. active_best_quality = cq_level;
  981. } else {
  982. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  983. // Modify best quality for second level arfs. For mode VPX_Q this
  984. // becomes the baseline frame q.
  985. if (gf_group->rf_level[gf_group->index] == GF_ARF_LOW)
  986. active_best_quality = (active_best_quality + cq_level + 1) / 2;
  987. }
  988. } else {
  989. active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
  990. }
  991. } else {
  992. if (oxcf->rc_mode == VPX_Q) {
  993. active_best_quality = cq_level;
  994. } else {
  995. active_best_quality = inter_minq[active_worst_quality];
  996. // For the constrained quality mode we don't want
  997. // q to fall below the cq level.
  998. if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
  999. active_best_quality = cq_level;
  1000. }
  1001. }
  1002. }
  1003. // Extension to max or min Q if undershoot or overshoot is outside
  1004. // the permitted range.
  1005. if (cpi->oxcf.rc_mode != VPX_Q) {
  1006. if (frame_is_intra_only(cm) ||
  1007. (!rc->is_src_frame_alt_ref &&
  1008. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
  1009. active_best_quality -=
  1010. (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
  1011. active_worst_quality += (cpi->twopass.extend_maxq / 2);
  1012. } else {
  1013. active_best_quality -=
  1014. (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
  1015. active_worst_quality += cpi->twopass.extend_maxq;
  1016. }
  1017. }
  1018. #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
  1019. vpx_clear_system_state();
  1020. // Static forced key frames Q restrictions dealt with elsewhere.
  1021. if (!((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi))) ||
  1022. !rc->this_key_frame_forced ||
  1023. (cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
  1024. int qdelta = vp9_frame_type_qdelta(cpi, gf_group->rf_level[gf_group->index],
  1025. active_worst_quality);
  1026. active_worst_quality =
  1027. VPXMAX(active_worst_quality + qdelta, active_best_quality);
  1028. }
  1029. #endif
  1030. // Modify active_best_quality for downscaled normal frames.
  1031. if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
  1032. int qdelta = vp9_compute_qdelta_by_rate(
  1033. rc, cm->frame_type, active_best_quality, 2.0, cm->bit_depth);
  1034. active_best_quality =
  1035. VPXMAX(active_best_quality + qdelta, rc->best_quality);
  1036. }
  1037. active_best_quality =
  1038. clamp(active_best_quality, rc->best_quality, rc->worst_quality);
  1039. active_worst_quality =
  1040. clamp(active_worst_quality, active_best_quality, rc->worst_quality);
  1041. if (oxcf->rc_mode == VPX_Q) {
  1042. q = active_best_quality;
  1043. // Special case code to try and match quality with forced key frames.
  1044. } else if ((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) &&
  1045. rc->this_key_frame_forced) {
  1046. // If static since last kf use better of last boosted and last kf q.
  1047. if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
  1048. q = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
  1049. } else {
  1050. q = rc->last_boosted_qindex;
  1051. }
  1052. } else {
  1053. q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
  1054. active_worst_quality);
  1055. if (q > active_worst_quality) {
  1056. // Special case when we are targeting the max allowed rate.
  1057. if (rc->this_frame_target >= rc->max_frame_bandwidth)
  1058. active_worst_quality = q;
  1059. else
  1060. q = active_worst_quality;
  1061. }
  1062. }
  1063. clamp(q, active_best_quality, active_worst_quality);
  1064. *top_index = active_worst_quality;
  1065. *bottom_index = active_best_quality;
  1066. assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
  1067. assert(*bottom_index <= rc->worst_quality &&
  1068. *bottom_index >= rc->best_quality);
  1069. assert(q <= rc->worst_quality && q >= rc->best_quality);
  1070. return q;
  1071. }
  1072. int vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi, int *bottom_index,
  1073. int *top_index) {
  1074. int q;
  1075. if (cpi->oxcf.pass == 0) {
  1076. if (cpi->oxcf.rc_mode == VPX_CBR)
  1077. q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
  1078. else
  1079. q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
  1080. } else {
  1081. q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
  1082. }
  1083. if (cpi->sf.use_nonrd_pick_mode) {
  1084. if (cpi->sf.force_frame_boost == 1) q -= cpi->sf.max_delta_qindex;
  1085. if (q < *bottom_index)
  1086. *bottom_index = q;
  1087. else if (q > *top_index)
  1088. *top_index = q;
  1089. }
  1090. return q;
  1091. }
  1092. void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi, int frame_target,
  1093. int *frame_under_shoot_limit,
  1094. int *frame_over_shoot_limit) {
  1095. if (cpi->oxcf.rc_mode == VPX_Q) {
  1096. *frame_under_shoot_limit = 0;
  1097. *frame_over_shoot_limit = INT_MAX;
  1098. } else {
  1099. // For very small rate targets where the fractional adjustment
  1100. // may be tiny make sure there is at least a minimum range.
  1101. const int tol_low = (cpi->sf.recode_tolerance_low * frame_target) / 100;
  1102. const int tol_high = (cpi->sf.recode_tolerance_high * frame_target) / 100;
  1103. *frame_under_shoot_limit = VPXMAX(frame_target - tol_low - 100, 0);
  1104. *frame_over_shoot_limit =
  1105. VPXMIN(frame_target + tol_high + 100, cpi->rc.max_frame_bandwidth);
  1106. }
  1107. }
  1108. void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
  1109. const VP9_COMMON *const cm = &cpi->common;
  1110. RATE_CONTROL *const rc = &cpi->rc;
  1111. rc->this_frame_target = target;
  1112. // Modify frame size target when down-scaling.
  1113. if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
  1114. rc->frame_size_selector != UNSCALED)
  1115. rc->this_frame_target = (int)(rc->this_frame_target *
  1116. rate_thresh_mult[rc->frame_size_selector]);
  1117. // Target rate per SB64 (including partial SB64s.
  1118. rc->sb64_target_rate = (int)(((int64_t)rc->this_frame_target * 64 * 64) /
  1119. (cm->width * cm->height));
  1120. }
  1121. static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
  1122. // this frame refreshes means next frames don't unless specified by user
  1123. RATE_CONTROL *const rc = &cpi->rc;
  1124. rc->frames_since_golden = 0;
  1125. // Mark the alt ref as done (setting to 0 means no further alt refs pending).
  1126. rc->source_alt_ref_pending = 0;
  1127. // Set the alternate reference frame active flag
  1128. rc->source_alt_ref_active = 1;
  1129. }
  1130. static void update_golden_frame_stats(VP9_COMP *cpi) {
  1131. RATE_CONTROL *const rc = &cpi->rc;
  1132. // Update the Golden frame usage counts.
  1133. if (cpi->refresh_golden_frame) {
  1134. // this frame refreshes means next frames don't unless specified by user
  1135. rc->frames_since_golden = 0;
  1136. // If we are not using alt ref in the up and coming group clear the arf
  1137. // active flag. In multi arf group case, if the index is not 0 then
  1138. // we are overlaying a mid group arf so should not reset the flag.
  1139. if (cpi->oxcf.pass == 2) {
  1140. if (!rc->source_alt_ref_pending && (cpi->twopass.gf_group.index == 0))
  1141. rc->source_alt_ref_active = 0;
  1142. } else if (!rc->source_alt_ref_pending) {
  1143. rc->source_alt_ref_active = 0;
  1144. }
  1145. // Decrement count down till next gf
  1146. if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
  1147. } else if (!cpi->refresh_alt_ref_frame) {
  1148. // Decrement count down till next gf
  1149. if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
  1150. rc->frames_since_golden++;
  1151. }
  1152. }
  1153. static void compute_frame_low_motion(VP9_COMP *const cpi) {
  1154. VP9_COMMON *const cm = &cpi->common;
  1155. int mi_row, mi_col;
  1156. MODE_INFO **mi = cm->mi_grid_visible;
  1157. RATE_CONTROL *const rc = &cpi->rc;
  1158. const int rows = cm->mi_rows, cols = cm->mi_cols;
  1159. int cnt_zeromv = 0;
  1160. for (mi_row = 0; mi_row < rows; mi_row++) {
  1161. for (mi_col = 0; mi_col < cols; mi_col++) {
  1162. if (abs(mi[0]->mv[0].as_mv.row) < 16 && abs(mi[0]->mv[0].as_mv.col) < 16)
  1163. cnt_zeromv++;
  1164. mi++;
  1165. }
  1166. mi += 8;
  1167. }
  1168. cnt_zeromv = 100 * cnt_zeromv / (rows * cols);
  1169. rc->avg_frame_low_motion = (3 * rc->avg_frame_low_motion + cnt_zeromv) >> 2;
  1170. }
  1171. void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
  1172. const VP9_COMMON *const cm = &cpi->common;
  1173. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1174. RATE_CONTROL *const rc = &cpi->rc;
  1175. const int qindex = cm->base_qindex;
  1176. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
  1177. vp9_cyclic_refresh_postencode(cpi);
  1178. }
  1179. // Update rate control heuristics
  1180. rc->projected_frame_size = (int)(bytes_used << 3);
  1181. // Post encode loop adjustment of Q prediction.
  1182. vp9_rc_update_rate_correction_factors(cpi);
  1183. // Keep a record of last Q and ambient average Q.
  1184. if (cm->frame_type == KEY_FRAME) {
  1185. rc->last_q[KEY_FRAME] = qindex;
  1186. rc->avg_frame_qindex[KEY_FRAME] =
  1187. ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
  1188. if (cpi->use_svc) {
  1189. int i = 0;
  1190. SVC *svc = &cpi->svc;
  1191. for (i = 0; i < svc->number_temporal_layers; ++i) {
  1192. const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
  1193. svc->number_temporal_layers);
  1194. LAYER_CONTEXT *lc = &svc->layer_context[layer];
  1195. RATE_CONTROL *lrc = &lc->rc;
  1196. lrc->last_q[KEY_FRAME] = rc->last_q[KEY_FRAME];
  1197. lrc->avg_frame_qindex[KEY_FRAME] = rc->avg_frame_qindex[KEY_FRAME];
  1198. }
  1199. }
  1200. } else {
  1201. if ((cpi->use_svc && oxcf->rc_mode == VPX_CBR) ||
  1202. (!rc->is_src_frame_alt_ref &&
  1203. !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
  1204. rc->last_q[INTER_FRAME] = qindex;
  1205. rc->avg_frame_qindex[INTER_FRAME] =
  1206. ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
  1207. rc->ni_frames++;
  1208. rc->tot_q += vp9_convert_qindex_to_q(qindex, cm->bit_depth);
  1209. rc->avg_q = rc->tot_q / rc->ni_frames;
  1210. // Calculate the average Q for normal inter frames (not key or GFU
  1211. // frames).
  1212. rc->ni_tot_qi += qindex;
  1213. rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
  1214. }
  1215. }
  1216. // Keep record of last boosted (KF/KF/ARF) Q value.
  1217. // If the current frame is coded at a lower Q then we also update it.
  1218. // If all mbs in this group are skipped only update if the Q value is
  1219. // better than that already stored.
  1220. // This is used to help set quality in forced key frames to reduce popping
  1221. if ((qindex < rc->last_boosted_qindex) || (cm->frame_type == KEY_FRAME) ||
  1222. (!rc->constrained_gf_group &&
  1223. (cpi->refresh_alt_ref_frame ||
  1224. (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
  1225. rc->last_boosted_qindex = qindex;
  1226. }
  1227. if (cm->frame_type == KEY_FRAME) rc->last_kf_qindex = qindex;
  1228. update_buffer_level(cpi, rc->projected_frame_size);
  1229. // Rolling monitors of whether we are over or underspending used to help
  1230. // regulate min and Max Q in two pass.
  1231. if (cm->frame_type != KEY_FRAME) {
  1232. rc->rolling_target_bits = ROUND_POWER_OF_TWO(
  1233. rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
  1234. rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
  1235. rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
  1236. rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
  1237. rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
  1238. rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
  1239. rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
  1240. }
  1241. // Actual bits spent
  1242. rc->total_actual_bits += rc->projected_frame_size;
  1243. rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
  1244. rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
  1245. if (!cpi->use_svc || is_two_pass_svc(cpi)) {
  1246. if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
  1247. (cm->frame_type != KEY_FRAME))
  1248. // Update the alternate reference frame stats as appropriate.
  1249. update_alt_ref_frame_stats(cpi);
  1250. else
  1251. // Update the Golden frame stats as appropriate.
  1252. update_golden_frame_stats(cpi);
  1253. }
  1254. if (cm->frame_type == KEY_FRAME) rc->frames_since_key = 0;
  1255. if (cm->show_frame) {
  1256. rc->frames_since_key++;
  1257. rc->frames_to_key--;
  1258. }
  1259. // Trigger the resizing of the next frame if it is scaled.
  1260. if (oxcf->pass != 0) {
  1261. cpi->resize_pending =
  1262. rc->next_frame_size_selector != rc->frame_size_selector;
  1263. rc->frame_size_selector = rc->next_frame_size_selector;
  1264. }
  1265. if (oxcf->pass == 0) {
  1266. if (cm->frame_type != KEY_FRAME) compute_frame_low_motion(cpi);
  1267. }
  1268. }
  1269. void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
  1270. // Update buffer level with zero size, update frame counters, and return.
  1271. update_buffer_level(cpi, 0);
  1272. cpi->rc.frames_since_key++;
  1273. cpi->rc.frames_to_key--;
  1274. cpi->rc.rc_2_frame = 0;
  1275. cpi->rc.rc_1_frame = 0;
  1276. }
  1277. // Use this macro to turn on/off use of alt-refs in one-pass mode.
  1278. #define USE_ALTREF_FOR_ONE_PASS 1
  1279. static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
  1280. const RATE_CONTROL *const rc = &cpi->rc;
  1281. int target;
  1282. const int af_ratio = rc->af_ratio_onepass_vbr;
  1283. #if USE_ALTREF_FOR_ONE_PASS
  1284. target =
  1285. (!rc->is_src_frame_alt_ref &&
  1286. (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))
  1287. ? (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
  1288. (rc->baseline_gf_interval + af_ratio - 1)
  1289. : (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
  1290. (rc->baseline_gf_interval + af_ratio - 1);
  1291. #else
  1292. target = rc->avg_frame_bandwidth;
  1293. #endif
  1294. return vp9_rc_clamp_pframe_target_size(cpi, target);
  1295. }
  1296. static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
  1297. static const int kf_ratio = 25;
  1298. const RATE_CONTROL *rc = &cpi->rc;
  1299. const int target = rc->avg_frame_bandwidth * kf_ratio;
  1300. return vp9_rc_clamp_iframe_target_size(cpi, target);
  1301. }
  1302. static void adjust_gfint_frame_constraint(VP9_COMP *cpi, int frame_constraint) {
  1303. RATE_CONTROL *const rc = &cpi->rc;
  1304. rc->constrained_gf_group = 0;
  1305. // Reset gf interval to make more equal spacing for frame_constraint.
  1306. if ((frame_constraint <= 7 * rc->baseline_gf_interval >> 2) &&
  1307. (frame_constraint > rc->baseline_gf_interval)) {
  1308. rc->baseline_gf_interval = frame_constraint >> 1;
  1309. if (rc->baseline_gf_interval < 5)
  1310. rc->baseline_gf_interval = frame_constraint;
  1311. rc->constrained_gf_group = 1;
  1312. } else {
  1313. // Reset to keep gf_interval <= frame_constraint.
  1314. if (rc->baseline_gf_interval > frame_constraint) {
  1315. rc->baseline_gf_interval = frame_constraint;
  1316. rc->constrained_gf_group = 1;
  1317. }
  1318. }
  1319. }
  1320. void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
  1321. VP9_COMMON *const cm = &cpi->common;
  1322. RATE_CONTROL *const rc = &cpi->rc;
  1323. int target;
  1324. // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
  1325. if (!cpi->refresh_alt_ref_frame &&
  1326. (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
  1327. rc->frames_to_key == 0 || (cpi->oxcf.auto_key && 0))) {
  1328. cm->frame_type = KEY_FRAME;
  1329. rc->this_key_frame_forced =
  1330. cm->current_video_frame != 0 && rc->frames_to_key == 0;
  1331. rc->frames_to_key = cpi->oxcf.key_freq;
  1332. rc->kf_boost = DEFAULT_KF_BOOST;
  1333. rc->source_alt_ref_active = 0;
  1334. } else {
  1335. cm->frame_type = INTER_FRAME;
  1336. }
  1337. if (rc->frames_till_gf_update_due == 0) {
  1338. double rate_err = 1.0;
  1339. rc->gfu_boost = DEFAULT_GF_BOOST;
  1340. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0) {
  1341. vp9_cyclic_refresh_set_golden_update(cpi);
  1342. } else {
  1343. rc->baseline_gf_interval =
  1344. (rc->min_gf_interval + rc->max_gf_interval) / 2;
  1345. }
  1346. rc->af_ratio_onepass_vbr = 10;
  1347. if (rc->rolling_target_bits > 0)
  1348. rate_err =
  1349. (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
  1350. if (cm->current_video_frame > 30) {
  1351. if (rc->avg_frame_qindex[INTER_FRAME] > (7 * rc->worst_quality) >> 3 &&
  1352. rate_err > 3.5) {
  1353. rc->baseline_gf_interval =
  1354. VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
  1355. } else if (rc->avg_frame_low_motion < 20) {
  1356. // Decrease gf interval for high motion case.
  1357. rc->baseline_gf_interval = VPXMAX(6, rc->baseline_gf_interval >> 1);
  1358. }
  1359. // Adjust boost and af_ratio based on avg_frame_low_motion, which varies
  1360. // between 0 and 100 (stationary, 100% zero/small motion).
  1361. rc->gfu_boost =
  1362. VPXMAX(500, DEFAULT_GF_BOOST * (rc->avg_frame_low_motion << 1) /
  1363. (rc->avg_frame_low_motion + 100));
  1364. rc->af_ratio_onepass_vbr = VPXMIN(15, VPXMAX(5, 3 * rc->gfu_boost / 400));
  1365. }
  1366. adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
  1367. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  1368. cpi->refresh_golden_frame = 1;
  1369. rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
  1370. }
  1371. if (cm->frame_type == KEY_FRAME)
  1372. target = calc_iframe_target_size_one_pass_vbr(cpi);
  1373. else
  1374. target = calc_pframe_target_size_one_pass_vbr(cpi);
  1375. vp9_rc_set_frame_target(cpi, target);
  1376. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0)
  1377. vp9_cyclic_refresh_update_parameters(cpi);
  1378. }
  1379. static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
  1380. const VP9EncoderConfig *oxcf = &cpi->oxcf;
  1381. const RATE_CONTROL *rc = &cpi->rc;
  1382. const SVC *const svc = &cpi->svc;
  1383. const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
  1384. const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
  1385. int min_frame_target =
  1386. VPXMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
  1387. int target;
  1388. if (oxcf->gf_cbr_boost_pct) {
  1389. const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
  1390. target = cpi->refresh_golden_frame
  1391. ? (rc->avg_frame_bandwidth * rc->baseline_gf_interval *
  1392. af_ratio_pct) /
  1393. (rc->baseline_gf_interval * 100 + af_ratio_pct - 100)
  1394. : (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
  1395. (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
  1396. } else {
  1397. target = rc->avg_frame_bandwidth;
  1398. }
  1399. if (is_one_pass_cbr_svc(cpi)) {
  1400. // Note that for layers, avg_frame_bandwidth is the cumulative
  1401. // per-frame-bandwidth. For the target size of this frame, use the
  1402. // layer average frame size (i.e., non-cumulative per-frame-bw).
  1403. int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
  1404. svc->number_temporal_layers);
  1405. const LAYER_CONTEXT *lc = &svc->layer_context[layer];
  1406. target = lc->avg_frame_size;
  1407. min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
  1408. }
  1409. if (diff > 0) {
  1410. // Lower the target bandwidth for this frame.
  1411. const int pct_low = (int)VPXMIN(diff / one_pct_bits, oxcf->under_shoot_pct);
  1412. target -= (target * pct_low) / 200;
  1413. } else if (diff < 0) {
  1414. // Increase the target bandwidth for this frame.
  1415. const int pct_high =
  1416. (int)VPXMIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
  1417. target += (target * pct_high) / 200;
  1418. }
  1419. if (oxcf->rc_max_inter_bitrate_pct) {
  1420. const int max_rate =
  1421. rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
  1422. target = VPXMIN(target, max_rate);
  1423. }
  1424. return VPXMAX(min_frame_target, target);
  1425. }
  1426. static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
  1427. const RATE_CONTROL *rc = &cpi->rc;
  1428. const VP9EncoderConfig *oxcf = &cpi->oxcf;
  1429. const SVC *const svc = &cpi->svc;
  1430. int target;
  1431. if (cpi->common.current_video_frame == 0) {
  1432. target = ((rc->starting_buffer_level / 2) > INT_MAX)
  1433. ? INT_MAX
  1434. : (int)(rc->starting_buffer_level / 2);
  1435. } else {
  1436. int kf_boost = 32;
  1437. double framerate = cpi->framerate;
  1438. if (svc->number_temporal_layers > 1 && oxcf->rc_mode == VPX_CBR) {
  1439. // Use the layer framerate for temporal layers CBR mode.
  1440. const int layer =
  1441. LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
  1442. svc->number_temporal_layers);
  1443. const LAYER_CONTEXT *lc = &svc->layer_context[layer];
  1444. framerate = lc->framerate;
  1445. }
  1446. kf_boost = VPXMAX(kf_boost, (int)(2 * framerate - 16));
  1447. if (rc->frames_since_key < framerate / 2) {
  1448. kf_boost = (int)(kf_boost * rc->frames_since_key / (framerate / 2));
  1449. }
  1450. target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
  1451. }
  1452. return vp9_rc_clamp_iframe_target_size(cpi, target);
  1453. }
  1454. void vp9_rc_get_svc_params(VP9_COMP *cpi) {
  1455. VP9_COMMON *const cm = &cpi->common;
  1456. RATE_CONTROL *const rc = &cpi->rc;
  1457. int target = rc->avg_frame_bandwidth;
  1458. int layer =
  1459. LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id, cpi->svc.temporal_layer_id,
  1460. cpi->svc.number_temporal_layers);
  1461. // Periodic key frames is based on the super-frame counter
  1462. // (svc.current_superframe), also only base spatial layer is key frame.
  1463. if ((cm->current_video_frame == 0) || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
  1464. (cpi->oxcf.auto_key &&
  1465. (cpi->svc.current_superframe % cpi->oxcf.key_freq == 0) &&
  1466. cpi->svc.spatial_layer_id == 0)) {
  1467. cm->frame_type = KEY_FRAME;
  1468. rc->source_alt_ref_active = 0;
  1469. if (is_two_pass_svc(cpi)) {
  1470. cpi->svc.layer_context[layer].is_key_frame = 1;
  1471. cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
  1472. } else if (is_one_pass_cbr_svc(cpi)) {
  1473. if (cm->current_video_frame > 0) vp9_svc_reset_key_frame(cpi);
  1474. layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
  1475. cpi->svc.temporal_layer_id,
  1476. cpi->svc.number_temporal_layers);
  1477. cpi->svc.layer_context[layer].is_key_frame = 1;
  1478. cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
  1479. // Assumption here is that LAST_FRAME is being updated for a keyframe.
  1480. // Thus no change in update flags.
  1481. target = calc_iframe_target_size_one_pass_cbr(cpi);
  1482. }
  1483. } else {
  1484. cm->frame_type = INTER_FRAME;
  1485. if (is_two_pass_svc(cpi)) {
  1486. LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
  1487. if (cpi->svc.spatial_layer_id == 0) {
  1488. lc->is_key_frame = 0;
  1489. } else {
  1490. lc->is_key_frame =
  1491. cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
  1492. if (lc->is_key_frame) cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
  1493. }
  1494. cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
  1495. } else if (is_one_pass_cbr_svc(cpi)) {
  1496. LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
  1497. if (cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode) {
  1498. lc->is_key_frame = 0;
  1499. } else {
  1500. lc->is_key_frame =
  1501. cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
  1502. }
  1503. target = calc_pframe_target_size_one_pass_cbr(cpi);
  1504. }
  1505. }
  1506. // Any update/change of global cyclic refresh parameters (amount/delta-qp)
  1507. // should be done here, before the frame qp is selected.
  1508. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
  1509. vp9_cyclic_refresh_update_parameters(cpi);
  1510. vp9_rc_set_frame_target(cpi, target);
  1511. rc->frames_till_gf_update_due = INT_MAX;
  1512. rc->baseline_gf_interval = INT_MAX;
  1513. }
  1514. void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
  1515. VP9_COMMON *const cm = &cpi->common;
  1516. RATE_CONTROL *const rc = &cpi->rc;
  1517. int target;
  1518. // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
  1519. if ((cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
  1520. rc->frames_to_key == 0 || (cpi->oxcf.auto_key && 0))) {
  1521. cm->frame_type = KEY_FRAME;
  1522. rc->this_key_frame_forced =
  1523. cm->current_video_frame != 0 && rc->frames_to_key == 0;
  1524. rc->frames_to_key = cpi->oxcf.key_freq;
  1525. rc->kf_boost = DEFAULT_KF_BOOST;
  1526. rc->source_alt_ref_active = 0;
  1527. } else {
  1528. cm->frame_type = INTER_FRAME;
  1529. }
  1530. if (rc->frames_till_gf_update_due == 0) {
  1531. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
  1532. vp9_cyclic_refresh_set_golden_update(cpi);
  1533. else
  1534. rc->baseline_gf_interval =
  1535. (rc->min_gf_interval + rc->max_gf_interval) / 2;
  1536. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  1537. // NOTE: frames_till_gf_update_due must be <= frames_to_key.
  1538. if (rc->frames_till_gf_update_due > rc->frames_to_key)
  1539. rc->frames_till_gf_update_due = rc->frames_to_key;
  1540. cpi->refresh_golden_frame = 1;
  1541. rc->gfu_boost = DEFAULT_GF_BOOST;
  1542. }
  1543. // Any update/change of global cyclic refresh parameters (amount/delta-qp)
  1544. // should be done here, before the frame qp is selected.
  1545. if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
  1546. vp9_cyclic_refresh_update_parameters(cpi);
  1547. if (cm->frame_type == KEY_FRAME)
  1548. target = calc_iframe_target_size_one_pass_cbr(cpi);
  1549. else
  1550. target = calc_pframe_target_size_one_pass_cbr(cpi);
  1551. vp9_rc_set_frame_target(cpi, target);
  1552. if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
  1553. cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
  1554. else
  1555. cpi->resize_pending = 0;
  1556. }
  1557. int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
  1558. vpx_bit_depth_t bit_depth) {
  1559. int start_index = rc->worst_quality;
  1560. int target_index = rc->worst_quality;
  1561. int i;
  1562. // Convert the average q value to an index.
  1563. for (i = rc->best_quality; i < rc->worst_quality; ++i) {
  1564. start_index = i;
  1565. if (vp9_convert_qindex_to_q(i, bit_depth) >= qstart) break;
  1566. }
  1567. // Convert the q target to an index
  1568. for (i = rc->best_quality; i < rc->worst_quality; ++i) {
  1569. target_index = i;
  1570. if (vp9_convert_qindex_to_q(i, bit_depth) >= qtarget) break;
  1571. }
  1572. return target_index - start_index;
  1573. }
  1574. int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
  1575. int qindex, double rate_target_ratio,
  1576. vpx_bit_depth_t bit_depth) {
  1577. int target_index = rc->worst_quality;
  1578. int i;
  1579. // Look up the current projected bits per block for the base index
  1580. const int base_bits_per_mb =
  1581. vp9_rc_bits_per_mb(frame_type, qindex, 1.0, bit_depth);
  1582. // Find the target bits per mb based on the base value and given ratio.
  1583. const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
  1584. // Convert the q target to an index
  1585. for (i = rc->best_quality; i < rc->worst_quality; ++i) {
  1586. if (vp9_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
  1587. target_bits_per_mb) {
  1588. target_index = i;
  1589. break;
  1590. }
  1591. }
  1592. return target_index - qindex;
  1593. }
  1594. void vp9_rc_set_gf_interval_range(const VP9_COMP *const cpi,
  1595. RATE_CONTROL *const rc) {
  1596. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1597. // Special case code for 1 pass fixed Q mode tests
  1598. if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
  1599. rc->max_gf_interval = FIXED_GF_INTERVAL;
  1600. rc->min_gf_interval = FIXED_GF_INTERVAL;
  1601. rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
  1602. } else {
  1603. // Set Maximum gf/arf interval
  1604. rc->max_gf_interval = oxcf->max_gf_interval;
  1605. rc->min_gf_interval = oxcf->min_gf_interval;
  1606. if (rc->min_gf_interval == 0)
  1607. rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
  1608. oxcf->width, oxcf->height, cpi->framerate);
  1609. if (rc->max_gf_interval == 0)
  1610. rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
  1611. cpi->framerate, rc->min_gf_interval);
  1612. // Extended interval for genuinely static scenes
  1613. rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
  1614. if (is_altref_enabled(cpi)) {
  1615. if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
  1616. rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
  1617. }
  1618. if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
  1619. rc->max_gf_interval = rc->static_scene_max_gf_interval;
  1620. // Clamp min to max
  1621. rc->min_gf_interval = VPXMIN(rc->min_gf_interval, rc->max_gf_interval);
  1622. }
  1623. }
  1624. void vp9_rc_update_framerate(VP9_COMP *cpi) {
  1625. const VP9_COMMON *const cm = &cpi->common;
  1626. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1627. RATE_CONTROL *const rc = &cpi->rc;
  1628. int vbr_max_bits;
  1629. rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
  1630. rc->min_frame_bandwidth =
  1631. (int)(rc->avg_frame_bandwidth * oxcf->two_pass_vbrmin_section / 100);
  1632. rc->min_frame_bandwidth =
  1633. VPXMAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
  1634. // A maximum bitrate for a frame is defined.
  1635. // The baseline for this aligns with HW implementations that
  1636. // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
  1637. // per 16x16 MB (averaged over a frame). However this limit is extended if
  1638. // a very high rate is given on the command line or the the rate cannnot
  1639. // be acheived because of a user specificed max q (e.g. when the user
  1640. // specifies lossless encode.
  1641. vbr_max_bits =
  1642. (int)(((int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmax_section) /
  1643. 100);
  1644. rc->max_frame_bandwidth =
  1645. VPXMAX(VPXMAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), vbr_max_bits);
  1646. vp9_rc_set_gf_interval_range(cpi, rc);
  1647. }
  1648. #define VBR_PCT_ADJUSTMENT_LIMIT 50
  1649. // For VBR...adjustment to the frame target based on error from previous frames
  1650. static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
  1651. RATE_CONTROL *const rc = &cpi->rc;
  1652. int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
  1653. int max_delta;
  1654. int frame_window = VPXMIN(16, ((int)cpi->twopass.total_stats.count -
  1655. cpi->common.current_video_frame));
  1656. // Calcluate the adjustment to rate for this frame.
  1657. if (frame_window > 0) {
  1658. max_delta = (vbr_bits_off_target > 0)
  1659. ? (int)(vbr_bits_off_target / frame_window)
  1660. : (int)(-vbr_bits_off_target / frame_window);
  1661. max_delta = VPXMIN(max_delta,
  1662. ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
  1663. // vbr_bits_off_target > 0 means we have extra bits to spend
  1664. if (vbr_bits_off_target > 0) {
  1665. *this_frame_target += (vbr_bits_off_target > max_delta)
  1666. ? max_delta
  1667. : (int)vbr_bits_off_target;
  1668. } else {
  1669. *this_frame_target -= (vbr_bits_off_target < -max_delta)
  1670. ? max_delta
  1671. : (int)-vbr_bits_off_target;
  1672. }
  1673. }
  1674. // Fast redistribution of bits arising from massive local undershoot.
  1675. // Dont do it for kf,arf,gf or overlay frames.
  1676. if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
  1677. rc->vbr_bits_off_target_fast) {
  1678. int one_frame_bits = VPXMAX(rc->avg_frame_bandwidth, *this_frame_target);
  1679. int fast_extra_bits;
  1680. fast_extra_bits = (int)VPXMIN(rc->vbr_bits_off_target_fast, one_frame_bits);
  1681. fast_extra_bits = (int)VPXMIN(
  1682. fast_extra_bits,
  1683. VPXMAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
  1684. *this_frame_target += (int)fast_extra_bits;
  1685. rc->vbr_bits_off_target_fast -= fast_extra_bits;
  1686. }
  1687. }
  1688. void vp9_set_target_rate(VP9_COMP *cpi) {
  1689. RATE_CONTROL *const rc = &cpi->rc;
  1690. int target_rate = rc->base_frame_target;
  1691. if (cpi->common.frame_type == KEY_FRAME)
  1692. target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
  1693. else
  1694. target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
  1695. // Correction to rate target based on prior over or under shoot.
  1696. if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
  1697. vbr_rate_correction(cpi, &target_rate);
  1698. vp9_rc_set_frame_target(cpi, target_rate);
  1699. }
  1700. // Check if we should resize, based on average QP from past x frames.
  1701. // Only allow for resize at most one scale down for now, scaling factor is 2.
  1702. int vp9_resize_one_pass_cbr(VP9_COMP *cpi) {
  1703. const VP9_COMMON *const cm = &cpi->common;
  1704. RATE_CONTROL *const rc = &cpi->rc;
  1705. RESIZE_ACTION resize_action = NO_RESIZE;
  1706. int avg_qp_thr1 = 70;
  1707. int avg_qp_thr2 = 50;
  1708. int min_width = 180;
  1709. int min_height = 180;
  1710. int down_size_on = 1;
  1711. cpi->resize_scale_num = 1;
  1712. cpi->resize_scale_den = 1;
  1713. // Don't resize on key frame; reset the counters on key frame.
  1714. if (cm->frame_type == KEY_FRAME) {
  1715. cpi->resize_avg_qp = 0;
  1716. cpi->resize_count = 0;
  1717. return 0;
  1718. }
  1719. // Check current frame reslution to avoid generating frames smaller than
  1720. // the minimum resolution.
  1721. if (ONEHALFONLY_RESIZE) {
  1722. if ((cm->width >> 1) < min_width || (cm->height >> 1) < min_height)
  1723. down_size_on = 0;
  1724. } else {
  1725. if (cpi->resize_state == ORIG &&
  1726. (cm->width * 3 / 4 < min_width || cm->height * 3 / 4 < min_height))
  1727. return 0;
  1728. else if (cpi->resize_state == THREE_QUARTER &&
  1729. ((cpi->oxcf.width >> 1) < min_width ||
  1730. (cpi->oxcf.height >> 1) < min_height))
  1731. down_size_on = 0;
  1732. }
  1733. #if CONFIG_VP9_TEMPORAL_DENOISING
  1734. // If denoiser is on, apply a smaller qp threshold.
  1735. if (cpi->oxcf.noise_sensitivity > 0) {
  1736. avg_qp_thr1 = 60;
  1737. avg_qp_thr2 = 40;
  1738. }
  1739. #endif
  1740. // Resize based on average buffer underflow and QP over some window.
  1741. // Ignore samples close to key frame, since QP is usually high after key.
  1742. if (cpi->rc.frames_since_key > 2 * cpi->framerate) {
  1743. const int window = (int)(4 * cpi->framerate);
  1744. cpi->resize_avg_qp += cm->base_qindex;
  1745. if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
  1746. ++cpi->resize_buffer_underflow;
  1747. ++cpi->resize_count;
  1748. // Check for resize action every "window" frames.
  1749. if (cpi->resize_count >= window) {
  1750. int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
  1751. // Resize down if buffer level has underflowed sufficient amount in past
  1752. // window, and we are at original or 3/4 of original resolution.
  1753. // Resize back up if average QP is low, and we are currently in a resized
  1754. // down state, i.e. 1/2 or 3/4 of original resolution.
  1755. // Currently, use a flag to turn 3/4 resizing feature on/off.
  1756. if (cpi->resize_buffer_underflow > (cpi->resize_count >> 2)) {
  1757. if (cpi->resize_state == THREE_QUARTER && down_size_on) {
  1758. resize_action = DOWN_ONEHALF;
  1759. cpi->resize_state = ONE_HALF;
  1760. } else if (cpi->resize_state == ORIG) {
  1761. resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
  1762. cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
  1763. }
  1764. } else if (cpi->resize_state != ORIG &&
  1765. avg_qp < avg_qp_thr1 * cpi->rc.worst_quality / 100) {
  1766. if (cpi->resize_state == THREE_QUARTER ||
  1767. avg_qp < avg_qp_thr2 * cpi->rc.worst_quality / 100 ||
  1768. ONEHALFONLY_RESIZE) {
  1769. resize_action = UP_ORIG;
  1770. cpi->resize_state = ORIG;
  1771. } else if (cpi->resize_state == ONE_HALF) {
  1772. resize_action = UP_THREEFOUR;
  1773. cpi->resize_state = THREE_QUARTER;
  1774. }
  1775. }
  1776. // Reset for next window measurement.
  1777. cpi->resize_avg_qp = 0;
  1778. cpi->resize_count = 0;
  1779. cpi->resize_buffer_underflow = 0;
  1780. }
  1781. }
  1782. // If decision is to resize, reset some quantities, and check is we should
  1783. // reduce rate correction factor,
  1784. if (resize_action != NO_RESIZE) {
  1785. int target_bits_per_frame;
  1786. int active_worst_quality;
  1787. int qindex;
  1788. int tot_scale_change;
  1789. if (resize_action == DOWN_THREEFOUR || resize_action == UP_THREEFOUR) {
  1790. cpi->resize_scale_num = 3;
  1791. cpi->resize_scale_den = 4;
  1792. } else if (resize_action == DOWN_ONEHALF) {
  1793. cpi->resize_scale_num = 1;
  1794. cpi->resize_scale_den = 2;
  1795. } else { // UP_ORIG or anything else
  1796. cpi->resize_scale_num = 1;
  1797. cpi->resize_scale_den = 1;
  1798. }
  1799. tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
  1800. (cpi->resize_scale_num * cpi->resize_scale_num);
  1801. // Reset buffer level to optimal, update target size.
  1802. rc->buffer_level = rc->optimal_buffer_level;
  1803. rc->bits_off_target = rc->optimal_buffer_level;
  1804. rc->this_frame_target = calc_pframe_target_size_one_pass_cbr(cpi);
  1805. // Get the projected qindex, based on the scaled target frame size (scaled
  1806. // so target_bits_per_mb in vp9_rc_regulate_q will be correct target).
  1807. target_bits_per_frame = (resize_action >= 0)
  1808. ? rc->this_frame_target * tot_scale_change
  1809. : rc->this_frame_target / tot_scale_change;
  1810. active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
  1811. qindex = vp9_rc_regulate_q(cpi, target_bits_per_frame, rc->best_quality,
  1812. active_worst_quality);
  1813. // If resize is down, check if projected q index is close to worst_quality,
  1814. // and if so, reduce the rate correction factor (since likely can afford
  1815. // lower q for resized frame).
  1816. if (resize_action > 0 && qindex > 90 * cpi->rc.worst_quality / 100) {
  1817. rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
  1818. }
  1819. // If resize is back up, check if projected q index is too much above the
  1820. // current base_qindex, and if so, reduce the rate correction factor
  1821. // (since prefer to keep q for resized frame at least close to previous q).
  1822. if (resize_action < 0 && qindex > 130 * cm->base_qindex / 100) {
  1823. rc->rate_correction_factors[INTER_NORMAL] *= 0.9;
  1824. }
  1825. }
  1826. return resize_action;
  1827. }
  1828. void adjust_gf_boost_lag_one_pass_vbr(VP9_COMP *cpi, uint64_t avg_sad_current) {
  1829. VP9_COMMON *const cm = &cpi->common;
  1830. RATE_CONTROL *const rc = &cpi->rc;
  1831. int target;
  1832. int found = 0;
  1833. int found2 = 0;
  1834. int frame;
  1835. int i;
  1836. uint64_t avg_source_sad_lag = avg_sad_current;
  1837. int high_source_sad_lagindex = -1;
  1838. int steady_sad_lagindex = -1;
  1839. uint32_t sad_thresh1 = 60000;
  1840. uint32_t sad_thresh2 = 120000;
  1841. int low_content = 0;
  1842. int high_content = 0;
  1843. double rate_err = 1.0;
  1844. // Get measure of complexity over the future frames, and get the first
  1845. // future frame with high_source_sad/scene-change.
  1846. int tot_frames = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
  1847. for (frame = tot_frames; frame >= 1; --frame) {
  1848. const int lagframe_idx = tot_frames - frame + 1;
  1849. uint64_t reference_sad = rc->avg_source_sad[0];
  1850. for (i = 1; i < lagframe_idx; ++i) {
  1851. if (rc->avg_source_sad[i] > 0)
  1852. reference_sad = (3 * reference_sad + rc->avg_source_sad[i]) >> 2;
  1853. }
  1854. // Detect up-coming scene change.
  1855. if (!found &&
  1856. (rc->avg_source_sad[lagframe_idx] >
  1857. VPXMAX(sad_thresh1, (unsigned int)(reference_sad << 1)) ||
  1858. rc->avg_source_sad[lagframe_idx] >
  1859. VPXMAX(3 * sad_thresh1 >> 2,
  1860. (unsigned int)(reference_sad << 2)))) {
  1861. high_source_sad_lagindex = lagframe_idx;
  1862. found = 1;
  1863. }
  1864. // Detect change from motion to steady.
  1865. if (!found2 && lagframe_idx > 1 && lagframe_idx < tot_frames &&
  1866. rc->avg_source_sad[lagframe_idx - 1] > (sad_thresh1 >> 2)) {
  1867. found2 = 1;
  1868. for (i = lagframe_idx; i < tot_frames; ++i) {
  1869. if (!(rc->avg_source_sad[i] > 0 &&
  1870. rc->avg_source_sad[i] < (sad_thresh1 >> 2) &&
  1871. rc->avg_source_sad[i] <
  1872. (rc->avg_source_sad[lagframe_idx - 1] >> 1))) {
  1873. found2 = 0;
  1874. i = tot_frames;
  1875. }
  1876. }
  1877. if (found2) steady_sad_lagindex = lagframe_idx;
  1878. }
  1879. avg_source_sad_lag += rc->avg_source_sad[lagframe_idx];
  1880. }
  1881. if (tot_frames > 0) avg_source_sad_lag = avg_source_sad_lag / tot_frames;
  1882. // Constrain distance between detected scene cuts.
  1883. if (high_source_sad_lagindex != -1 &&
  1884. high_source_sad_lagindex != rc->high_source_sad_lagindex - 1 &&
  1885. abs(high_source_sad_lagindex - rc->high_source_sad_lagindex) < 4)
  1886. rc->high_source_sad_lagindex = -1;
  1887. else
  1888. rc->high_source_sad_lagindex = high_source_sad_lagindex;
  1889. // Adjust some factors for the next GF group, ignore initial key frame,
  1890. // and only for lag_in_frames not too small.
  1891. if (cpi->refresh_golden_frame == 1 && cm->frame_type != KEY_FRAME &&
  1892. cm->current_video_frame > 30 && cpi->oxcf.lag_in_frames > 8) {
  1893. int frame_constraint;
  1894. if (rc->rolling_target_bits > 0)
  1895. rate_err =
  1896. (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
  1897. high_content = high_source_sad_lagindex != -1 ||
  1898. avg_source_sad_lag > (rc->prev_avg_source_sad_lag << 1) ||
  1899. avg_source_sad_lag > sad_thresh2;
  1900. low_content = high_source_sad_lagindex == -1 &&
  1901. ((avg_source_sad_lag < (rc->prev_avg_source_sad_lag >> 1)) ||
  1902. (avg_source_sad_lag < sad_thresh1));
  1903. if (low_content) {
  1904. rc->gfu_boost = DEFAULT_GF_BOOST;
  1905. rc->baseline_gf_interval =
  1906. VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
  1907. } else if (high_content) {
  1908. rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
  1909. rc->baseline_gf_interval = (rate_err > 3.0)
  1910. ? VPXMAX(10, rc->baseline_gf_interval >> 1)
  1911. : VPXMAX(6, rc->baseline_gf_interval >> 1);
  1912. }
  1913. // Check for constraining gf_interval for up-coming scene/content changes,
  1914. // or for up-coming key frame, whichever is closer.
  1915. frame_constraint = rc->frames_to_key;
  1916. if (rc->high_source_sad_lagindex > 0 &&
  1917. frame_constraint > rc->high_source_sad_lagindex)
  1918. frame_constraint = rc->high_source_sad_lagindex;
  1919. if (steady_sad_lagindex > 3 && frame_constraint > steady_sad_lagindex)
  1920. frame_constraint = steady_sad_lagindex;
  1921. adjust_gfint_frame_constraint(cpi, frame_constraint);
  1922. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  1923. // Adjust factors for active_worst setting & af_ratio for next gf interval.
  1924. rc->fac_active_worst_inter = 150; // corresponds to 3/2 (= 150 /100).
  1925. rc->fac_active_worst_gf = 100;
  1926. if (rate_err < 1.5 && !high_content) {
  1927. rc->fac_active_worst_inter = 120;
  1928. rc->fac_active_worst_gf = 90;
  1929. }
  1930. if (low_content && rc->avg_frame_low_motion > 80) {
  1931. rc->af_ratio_onepass_vbr = 15;
  1932. } else if (high_content || rc->avg_frame_low_motion < 30) {
  1933. rc->af_ratio_onepass_vbr = 5;
  1934. rc->gfu_boost = DEFAULT_GF_BOOST >> 2;
  1935. }
  1936. target = calc_pframe_target_size_one_pass_vbr(cpi);
  1937. vp9_rc_set_frame_target(cpi, target);
  1938. }
  1939. rc->prev_avg_source_sad_lag = avg_source_sad_lag;
  1940. }
  1941. // Compute average source sad (temporal sad: between current source and
  1942. // previous source) over a subset of superblocks. Use this is detect big changes
  1943. // in content and allow rate control to react.
  1944. // This function also handles special case of lag_in_frames, to measure content
  1945. // level in #future frames set by the lag_in_frames.
  1946. void vp9_avg_source_sad(VP9_COMP *cpi) {
  1947. VP9_COMMON *const cm = &cpi->common;
  1948. RATE_CONTROL *const rc = &cpi->rc;
  1949. rc->high_source_sad = 0;
  1950. if (cpi->Last_Source != NULL &&
  1951. cpi->Last_Source->y_width == cpi->Source->y_width &&
  1952. cpi->Last_Source->y_height == cpi->Source->y_height) {
  1953. YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS] = { NULL };
  1954. uint8_t *src_y = cpi->Source->y_buffer;
  1955. int src_ystride = cpi->Source->y_stride;
  1956. uint8_t *last_src_y = cpi->Last_Source->y_buffer;
  1957. int last_src_ystride = cpi->Last_Source->y_stride;
  1958. int start_frame = 0;
  1959. int frames_to_buffer = 1;
  1960. int frame = 0;
  1961. uint64_t avg_sad_current = 0;
  1962. uint32_t min_thresh = 4000;
  1963. float thresh = 8.0f;
  1964. if (cpi->oxcf.rc_mode == VPX_VBR) {
  1965. min_thresh = 60000;
  1966. thresh = 2.1f;
  1967. }
  1968. if (cpi->oxcf.lag_in_frames > 0) {
  1969. frames_to_buffer = (cm->current_video_frame == 1)
  1970. ? (int)vp9_lookahead_depth(cpi->lookahead) - 1
  1971. : 2;
  1972. start_frame = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
  1973. for (frame = 0; frame < frames_to_buffer; ++frame) {
  1974. const int lagframe_idx = start_frame - frame;
  1975. if (lagframe_idx >= 0) {
  1976. struct lookahead_entry *buf =
  1977. vp9_lookahead_peek(cpi->lookahead, lagframe_idx);
  1978. frames[frame] = &buf->img;
  1979. }
  1980. }
  1981. // The avg_sad for this current frame is the value of frame#1
  1982. // (first future frame) from previous frame.
  1983. avg_sad_current = rc->avg_source_sad[1];
  1984. if (avg_sad_current >
  1985. VPXMAX(min_thresh,
  1986. (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
  1987. cm->current_video_frame > (unsigned int)cpi->oxcf.lag_in_frames)
  1988. rc->high_source_sad = 1;
  1989. else
  1990. rc->high_source_sad = 0;
  1991. // Update recursive average for current frame.
  1992. if (avg_sad_current > 0)
  1993. rc->avg_source_sad[0] =
  1994. (3 * rc->avg_source_sad[0] + avg_sad_current) >> 2;
  1995. // Shift back data, starting at frame#1.
  1996. for (frame = 1; frame < cpi->oxcf.lag_in_frames - 1; ++frame)
  1997. rc->avg_source_sad[frame] = rc->avg_source_sad[frame + 1];
  1998. }
  1999. for (frame = 0; frame < frames_to_buffer; ++frame) {
  2000. if (cpi->oxcf.lag_in_frames == 0 ||
  2001. (frames[frame] != NULL && frames[frame + 1] != NULL &&
  2002. frames[frame]->y_width == frames[frame + 1]->y_width &&
  2003. frames[frame]->y_height == frames[frame + 1]->y_height)) {
  2004. int sbi_row, sbi_col;
  2005. const int lagframe_idx =
  2006. (cpi->oxcf.lag_in_frames == 0) ? 0 : start_frame - frame + 1;
  2007. const BLOCK_SIZE bsize = BLOCK_64X64;
  2008. // Loop over sub-sample of frame, compute average sad over 64x64 blocks.
  2009. uint64_t avg_sad = 0;
  2010. int num_samples = 0;
  2011. int sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  2012. int sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  2013. if (cpi->oxcf.lag_in_frames > 0) {
  2014. src_y = frames[frame]->y_buffer;
  2015. src_ystride = frames[frame]->y_stride;
  2016. last_src_y = frames[frame + 1]->y_buffer;
  2017. last_src_ystride = frames[frame + 1]->y_stride;
  2018. }
  2019. for (sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
  2020. for (sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
  2021. // Checker-board pattern, ignore boundary.
  2022. if ((sbi_row > 0 && sbi_col > 0) &&
  2023. (sbi_row < sb_rows - 1 && sbi_col < sb_cols - 1) &&
  2024. ((sbi_row % 2 == 0 && sbi_col % 2 == 0) ||
  2025. (sbi_row % 2 != 0 && sbi_col % 2 != 0))) {
  2026. num_samples++;
  2027. avg_sad += cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
  2028. last_src_ystride);
  2029. }
  2030. src_y += 64;
  2031. last_src_y += 64;
  2032. }
  2033. src_y += (src_ystride << 6) - (sb_cols << 6);
  2034. last_src_y += (last_src_ystride << 6) - (sb_cols << 6);
  2035. }
  2036. if (num_samples > 0) avg_sad = avg_sad / num_samples;
  2037. // Set high_source_sad flag if we detect very high increase in avg_sad
  2038. // between current and previous frame value(s). Use minimum threshold
  2039. // for cases where there is small change from content that is completely
  2040. // static.
  2041. if (lagframe_idx == 0) {
  2042. if (avg_sad >
  2043. VPXMAX(min_thresh,
  2044. (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
  2045. rc->frames_since_key > 1)
  2046. rc->high_source_sad = 1;
  2047. else
  2048. rc->high_source_sad = 0;
  2049. if (avg_sad > 0 || cpi->oxcf.rc_mode == VPX_CBR)
  2050. rc->avg_source_sad[0] = (3 * rc->avg_source_sad[0] + avg_sad) >> 2;
  2051. } else {
  2052. rc->avg_source_sad[lagframe_idx] = avg_sad;
  2053. }
  2054. }
  2055. }
  2056. // For VBR, under scene change/high content change, force golden refresh.
  2057. if (cpi->oxcf.rc_mode == VPX_VBR && cm->frame_type != KEY_FRAME &&
  2058. rc->high_source_sad && rc->frames_to_key > 3 &&
  2059. rc->count_last_scene_change > 4 &&
  2060. cpi->ext_refresh_frame_flags_pending == 0) {
  2061. int target;
  2062. cpi->refresh_golden_frame = 1;
  2063. rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
  2064. rc->baseline_gf_interval =
  2065. VPXMIN(20, VPXMAX(10, rc->baseline_gf_interval));
  2066. adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
  2067. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  2068. target = calc_pframe_target_size_one_pass_vbr(cpi);
  2069. vp9_rc_set_frame_target(cpi, target);
  2070. rc->count_last_scene_change = 0;
  2071. } else {
  2072. rc->count_last_scene_change++;
  2073. }
  2074. // If lag_in_frame is used, set the gf boost and interval.
  2075. if (cpi->oxcf.lag_in_frames > 0)
  2076. adjust_gf_boost_lag_one_pass_vbr(cpi, avg_sad_current);
  2077. }
  2078. }
  2079. // Test if encoded frame will significantly overshoot the target bitrate, and
  2080. // if so, set the QP, reset/adjust some rate control parameters, and return 1.
  2081. int vp9_encodedframe_overshoot(VP9_COMP *cpi, int frame_size, int *q) {
  2082. VP9_COMMON *const cm = &cpi->common;
  2083. RATE_CONTROL *const rc = &cpi->rc;
  2084. int thresh_qp = 3 * (rc->worst_quality >> 2);
  2085. int thresh_rate = rc->avg_frame_bandwidth * 10;
  2086. if (cm->base_qindex < thresh_qp && frame_size > thresh_rate) {
  2087. double rate_correction_factor =
  2088. cpi->rc.rate_correction_factors[INTER_NORMAL];
  2089. const int target_size = cpi->rc.avg_frame_bandwidth;
  2090. double new_correction_factor;
  2091. int target_bits_per_mb;
  2092. double q2;
  2093. int enumerator;
  2094. // Force a re-encode, and for now use max-QP.
  2095. *q = cpi->rc.worst_quality;
  2096. // Adjust avg_frame_qindex, buffer_level, and rate correction factors, as
  2097. // these parameters will affect QP selection for subsequent frames. If they
  2098. // have settled down to a very different (low QP) state, then not adjusting
  2099. // them may cause next frame to select low QP and overshoot again.
  2100. cpi->rc.avg_frame_qindex[INTER_FRAME] = *q;
  2101. rc->buffer_level = rc->optimal_buffer_level;
  2102. rc->bits_off_target = rc->optimal_buffer_level;
  2103. // Reset rate under/over-shoot flags.
  2104. cpi->rc.rc_1_frame = 0;
  2105. cpi->rc.rc_2_frame = 0;
  2106. // Adjust rate correction factor.
  2107. target_bits_per_mb =
  2108. (int)(((uint64_t)target_size << BPER_MB_NORMBITS) / cm->MBs);
  2109. // Rate correction factor based on target_bits_per_mb and qp (==max_QP).
  2110. // This comes from the inverse computation of vp9_rc_bits_per_mb().
  2111. q2 = vp9_convert_qindex_to_q(*q, cm->bit_depth);
  2112. enumerator = 1800000; // Factor for inter frame.
  2113. enumerator += (int)(enumerator * q2) >> 12;
  2114. new_correction_factor = (double)target_bits_per_mb * q2 / enumerator;
  2115. if (new_correction_factor > rate_correction_factor) {
  2116. rate_correction_factor =
  2117. VPXMIN(2.0 * rate_correction_factor, new_correction_factor);
  2118. if (rate_correction_factor > MAX_BPB_FACTOR)
  2119. rate_correction_factor = MAX_BPB_FACTOR;
  2120. cpi->rc.rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
  2121. }
  2122. // For temporal layers, reset the rate control parametes across all
  2123. // temporal layers.
  2124. if (cpi->use_svc) {
  2125. int i = 0;
  2126. SVC *svc = &cpi->svc;
  2127. for (i = 0; i < svc->number_temporal_layers; ++i) {
  2128. const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
  2129. svc->number_temporal_layers);
  2130. LAYER_CONTEXT *lc = &svc->layer_context[layer];
  2131. RATE_CONTROL *lrc = &lc->rc;
  2132. lrc->avg_frame_qindex[INTER_FRAME] = *q;
  2133. lrc->buffer_level = rc->optimal_buffer_level;
  2134. lrc->bits_off_target = rc->optimal_buffer_level;
  2135. lrc->rc_1_frame = 0;
  2136. lrc->rc_2_frame = 0;
  2137. lrc->rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
  2138. }
  2139. }
  2140. return 1;
  2141. } else {
  2142. return 0;
  2143. }
  2144. }