vp9_firstpass.c 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059
  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 <limits.h>
  11. #include <math.h>
  12. #include <stdio.h>
  13. #include "./vpx_dsp_rtcd.h"
  14. #include "./vpx_scale_rtcd.h"
  15. #include "vpx_dsp/vpx_dsp_common.h"
  16. #include "vpx_mem/vpx_mem.h"
  17. #include "vpx_ports/mem.h"
  18. #include "vpx_ports/system_state.h"
  19. #include "vpx_scale/vpx_scale.h"
  20. #include "vpx_scale/yv12config.h"
  21. #include "vp9/common/vp9_entropymv.h"
  22. #include "vp9/common/vp9_quant_common.h"
  23. #include "vp9/common/vp9_reconinter.h" // vp9_setup_dst_planes()
  24. #include "vp9/encoder/vp9_aq_variance.h"
  25. #include "vp9/encoder/vp9_block.h"
  26. #include "vp9/encoder/vp9_encodeframe.h"
  27. #include "vp9/encoder/vp9_encodemb.h"
  28. #include "vp9/encoder/vp9_encodemv.h"
  29. #include "vp9/encoder/vp9_encoder.h"
  30. #include "vp9/encoder/vp9_extend.h"
  31. #include "vp9/encoder/vp9_firstpass.h"
  32. #include "vp9/encoder/vp9_mcomp.h"
  33. #include "vp9/encoder/vp9_quantize.h"
  34. #include "vp9/encoder/vp9_rd.h"
  35. #include "vpx_dsp/variance.h"
  36. #define OUTPUT_FPF 0
  37. #define ARF_STATS_OUTPUT 0
  38. #define BOOST_BREAKOUT 12.5
  39. #define BOOST_FACTOR 12.5
  40. #define FACTOR_PT_LOW 0.70
  41. #define FACTOR_PT_HIGH 0.90
  42. #define FIRST_PASS_Q 10.0
  43. #define GF_MAX_BOOST 96.0
  44. #define INTRA_MODE_PENALTY 1024
  45. #define KF_MAX_BOOST 128.0
  46. #define MIN_ARF_GF_BOOST 240
  47. #define MIN_DECAY_FACTOR 0.01
  48. #define MIN_KF_BOOST 300
  49. #define NEW_MV_MODE_PENALTY 32
  50. #define SVC_FACTOR_PT_LOW 0.45
  51. #define DARK_THRESH 64
  52. #define DEFAULT_GRP_WEIGHT 1.0
  53. #define RC_FACTOR_MIN 0.75
  54. #define RC_FACTOR_MAX 1.75
  55. #define SECTION_NOISE_DEF 250.0
  56. #define LOW_I_THRESH 24000
  57. #define NCOUNT_INTRA_THRESH 8192
  58. #define NCOUNT_INTRA_FACTOR 3
  59. #define DOUBLE_DIVIDE_CHECK(x) ((x) < 0 ? (x)-0.000001 : (x) + 0.000001)
  60. #if ARF_STATS_OUTPUT
  61. unsigned int arf_count = 0;
  62. #endif
  63. // Resets the first pass file to the given position using a relative seek from
  64. // the current position.
  65. static void reset_fpf_position(TWO_PASS *p, const FIRSTPASS_STATS *position) {
  66. p->stats_in = position;
  67. }
  68. // Read frame stats at an offset from the current position.
  69. static const FIRSTPASS_STATS *read_frame_stats(const TWO_PASS *p, int offset) {
  70. if ((offset >= 0 && p->stats_in + offset >= p->stats_in_end) ||
  71. (offset < 0 && p->stats_in + offset < p->stats_in_start)) {
  72. return NULL;
  73. }
  74. return &p->stats_in[offset];
  75. }
  76. static int input_stats(TWO_PASS *p, FIRSTPASS_STATS *fps) {
  77. if (p->stats_in >= p->stats_in_end) return EOF;
  78. *fps = *p->stats_in;
  79. ++p->stats_in;
  80. return 1;
  81. }
  82. static void output_stats(FIRSTPASS_STATS *stats,
  83. struct vpx_codec_pkt_list *pktlist) {
  84. struct vpx_codec_cx_pkt pkt;
  85. pkt.kind = VPX_CODEC_STATS_PKT;
  86. pkt.data.twopass_stats.buf = stats;
  87. pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
  88. vpx_codec_pkt_list_add(pktlist, &pkt);
  89. // TEMP debug code
  90. #if OUTPUT_FPF
  91. {
  92. FILE *fpfile;
  93. fpfile = fopen("firstpass.stt", "a");
  94. fprintf(fpfile,
  95. "%12.0lf %12.4lf %12.0lf %12.0lf %12.0lf %12.0lf %12.4lf"
  96. "%12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf %12.4lf"
  97. "%12.4lf %12.4lf %12.4lf %12.4lf %12.0lf %12.0lf %12.0lf %12.4lf"
  98. "\n",
  99. stats->frame, stats->weight, stats->intra_error, stats->coded_error,
  100. stats->sr_coded_error, stats->frame_noise_energy, stats->pcnt_inter,
  101. stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
  102. stats->intra_skip_pct, stats->intra_smooth_pct,
  103. stats->inactive_zone_rows, stats->inactive_zone_cols, stats->MVr,
  104. stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
  105. stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
  106. stats->count, stats->duration);
  107. fclose(fpfile);
  108. }
  109. #endif
  110. }
  111. #if CONFIG_FP_MB_STATS
  112. static void output_fpmb_stats(uint8_t *this_frame_mb_stats, VP9_COMMON *cm,
  113. struct vpx_codec_pkt_list *pktlist) {
  114. struct vpx_codec_cx_pkt pkt;
  115. pkt.kind = VPX_CODEC_FPMB_STATS_PKT;
  116. pkt.data.firstpass_mb_stats.buf = this_frame_mb_stats;
  117. pkt.data.firstpass_mb_stats.sz = cm->initial_mbs * sizeof(uint8_t);
  118. vpx_codec_pkt_list_add(pktlist, &pkt);
  119. }
  120. #endif
  121. static void zero_stats(FIRSTPASS_STATS *section) {
  122. section->frame = 0.0;
  123. section->weight = 0.0;
  124. section->intra_error = 0.0;
  125. section->coded_error = 0.0;
  126. section->sr_coded_error = 0.0;
  127. section->frame_noise_energy = 0.0;
  128. section->pcnt_inter = 0.0;
  129. section->pcnt_motion = 0.0;
  130. section->pcnt_second_ref = 0.0;
  131. section->pcnt_neutral = 0.0;
  132. section->intra_skip_pct = 0.0;
  133. section->intra_smooth_pct = 0.0;
  134. section->inactive_zone_rows = 0.0;
  135. section->inactive_zone_cols = 0.0;
  136. section->MVr = 0.0;
  137. section->mvr_abs = 0.0;
  138. section->MVc = 0.0;
  139. section->mvc_abs = 0.0;
  140. section->MVrv = 0.0;
  141. section->MVcv = 0.0;
  142. section->mv_in_out_count = 0.0;
  143. section->new_mv_count = 0.0;
  144. section->count = 0.0;
  145. section->duration = 1.0;
  146. section->spatial_layer_id = 0;
  147. }
  148. static void accumulate_stats(FIRSTPASS_STATS *section,
  149. const FIRSTPASS_STATS *frame) {
  150. section->frame += frame->frame;
  151. section->weight += frame->weight;
  152. section->spatial_layer_id = frame->spatial_layer_id;
  153. section->intra_error += frame->intra_error;
  154. section->coded_error += frame->coded_error;
  155. section->sr_coded_error += frame->sr_coded_error;
  156. section->frame_noise_energy += frame->frame_noise_energy;
  157. section->pcnt_inter += frame->pcnt_inter;
  158. section->pcnt_motion += frame->pcnt_motion;
  159. section->pcnt_second_ref += frame->pcnt_second_ref;
  160. section->pcnt_neutral += frame->pcnt_neutral;
  161. section->intra_skip_pct += frame->intra_skip_pct;
  162. section->intra_smooth_pct += frame->intra_smooth_pct;
  163. section->inactive_zone_rows += frame->inactive_zone_rows;
  164. section->inactive_zone_cols += frame->inactive_zone_cols;
  165. section->MVr += frame->MVr;
  166. section->mvr_abs += frame->mvr_abs;
  167. section->MVc += frame->MVc;
  168. section->mvc_abs += frame->mvc_abs;
  169. section->MVrv += frame->MVrv;
  170. section->MVcv += frame->MVcv;
  171. section->mv_in_out_count += frame->mv_in_out_count;
  172. section->new_mv_count += frame->new_mv_count;
  173. section->count += frame->count;
  174. section->duration += frame->duration;
  175. }
  176. static void subtract_stats(FIRSTPASS_STATS *section,
  177. const FIRSTPASS_STATS *frame) {
  178. section->frame -= frame->frame;
  179. section->weight -= frame->weight;
  180. section->intra_error -= frame->intra_error;
  181. section->coded_error -= frame->coded_error;
  182. section->sr_coded_error -= frame->sr_coded_error;
  183. section->frame_noise_energy -= frame->frame_noise_energy;
  184. section->pcnt_inter -= frame->pcnt_inter;
  185. section->pcnt_motion -= frame->pcnt_motion;
  186. section->pcnt_second_ref -= frame->pcnt_second_ref;
  187. section->pcnt_neutral -= frame->pcnt_neutral;
  188. section->intra_skip_pct -= frame->intra_skip_pct;
  189. section->intra_smooth_pct -= frame->intra_smooth_pct;
  190. section->inactive_zone_rows -= frame->inactive_zone_rows;
  191. section->inactive_zone_cols -= frame->inactive_zone_cols;
  192. section->MVr -= frame->MVr;
  193. section->mvr_abs -= frame->mvr_abs;
  194. section->MVc -= frame->MVc;
  195. section->mvc_abs -= frame->mvc_abs;
  196. section->MVrv -= frame->MVrv;
  197. section->MVcv -= frame->MVcv;
  198. section->mv_in_out_count -= frame->mv_in_out_count;
  199. section->new_mv_count -= frame->new_mv_count;
  200. section->count -= frame->count;
  201. section->duration -= frame->duration;
  202. }
  203. // Calculate an active area of the image that discounts formatting
  204. // bars and partially discounts other 0 energy areas.
  205. #define MIN_ACTIVE_AREA 0.5
  206. #define MAX_ACTIVE_AREA 1.0
  207. static double calculate_active_area(const VP9_COMP *cpi,
  208. const FIRSTPASS_STATS *this_frame) {
  209. double active_pct;
  210. active_pct =
  211. 1.0 -
  212. ((this_frame->intra_skip_pct / 2) +
  213. ((this_frame->inactive_zone_rows * 2) / (double)cpi->common.mb_rows));
  214. return fclamp(active_pct, MIN_ACTIVE_AREA, MAX_ACTIVE_AREA);
  215. }
  216. // Calculate a modified Error used in distributing bits between easier and
  217. // harder frames.
  218. #define ACT_AREA_CORRECTION 0.5
  219. static double calculate_modified_err(const VP9_COMP *cpi,
  220. const TWO_PASS *twopass,
  221. const VP9EncoderConfig *oxcf,
  222. const FIRSTPASS_STATS *this_frame) {
  223. const FIRSTPASS_STATS *const stats = &twopass->total_stats;
  224. const double av_weight = stats->weight / stats->count;
  225. const double av_err = (stats->coded_error * av_weight) / stats->count;
  226. double modified_error =
  227. av_err * pow(this_frame->coded_error * this_frame->weight /
  228. DOUBLE_DIVIDE_CHECK(av_err),
  229. oxcf->two_pass_vbrbias / 100.0);
  230. // Correction for active area. Frames with a reduced active area
  231. // (eg due to formatting bars) have a higher error per mb for the
  232. // remaining active MBs. The correction here assumes that coding
  233. // 0.5N blocks of complexity 2X is a little easier than coding N
  234. // blocks of complexity X.
  235. modified_error *=
  236. pow(calculate_active_area(cpi, this_frame), ACT_AREA_CORRECTION);
  237. return fclamp(modified_error, twopass->modified_error_min,
  238. twopass->modified_error_max);
  239. }
  240. // This function returns the maximum target rate per frame.
  241. static int frame_max_bits(const RATE_CONTROL *rc,
  242. const VP9EncoderConfig *oxcf) {
  243. int64_t max_bits = ((int64_t)rc->avg_frame_bandwidth *
  244. (int64_t)oxcf->two_pass_vbrmax_section) /
  245. 100;
  246. if (max_bits < 0)
  247. max_bits = 0;
  248. else if (max_bits > rc->max_frame_bandwidth)
  249. max_bits = rc->max_frame_bandwidth;
  250. return (int)max_bits;
  251. }
  252. void vp9_init_first_pass(VP9_COMP *cpi) {
  253. zero_stats(&cpi->twopass.total_stats);
  254. }
  255. void vp9_end_first_pass(VP9_COMP *cpi) {
  256. if (is_two_pass_svc(cpi)) {
  257. int i;
  258. for (i = 0; i < cpi->svc.number_spatial_layers; ++i) {
  259. output_stats(&cpi->svc.layer_context[i].twopass.total_stats,
  260. cpi->output_pkt_list);
  261. }
  262. } else {
  263. output_stats(&cpi->twopass.total_stats, cpi->output_pkt_list);
  264. }
  265. }
  266. static vpx_variance_fn_t get_block_variance_fn(BLOCK_SIZE bsize) {
  267. switch (bsize) {
  268. case BLOCK_8X8: return vpx_mse8x8;
  269. case BLOCK_16X8: return vpx_mse16x8;
  270. case BLOCK_8X16: return vpx_mse8x16;
  271. default: return vpx_mse16x16;
  272. }
  273. }
  274. static unsigned int get_prediction_error(BLOCK_SIZE bsize,
  275. const struct buf_2d *src,
  276. const struct buf_2d *ref) {
  277. unsigned int sse;
  278. const vpx_variance_fn_t fn = get_block_variance_fn(bsize);
  279. fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
  280. return sse;
  281. }
  282. #if CONFIG_VP9_HIGHBITDEPTH
  283. static vpx_variance_fn_t highbd_get_block_variance_fn(BLOCK_SIZE bsize,
  284. int bd) {
  285. switch (bd) {
  286. default:
  287. switch (bsize) {
  288. case BLOCK_8X8: return vpx_highbd_8_mse8x8;
  289. case BLOCK_16X8: return vpx_highbd_8_mse16x8;
  290. case BLOCK_8X16: return vpx_highbd_8_mse8x16;
  291. default: return vpx_highbd_8_mse16x16;
  292. }
  293. break;
  294. case 10:
  295. switch (bsize) {
  296. case BLOCK_8X8: return vpx_highbd_10_mse8x8;
  297. case BLOCK_16X8: return vpx_highbd_10_mse16x8;
  298. case BLOCK_8X16: return vpx_highbd_10_mse8x16;
  299. default: return vpx_highbd_10_mse16x16;
  300. }
  301. break;
  302. case 12:
  303. switch (bsize) {
  304. case BLOCK_8X8: return vpx_highbd_12_mse8x8;
  305. case BLOCK_16X8: return vpx_highbd_12_mse16x8;
  306. case BLOCK_8X16: return vpx_highbd_12_mse8x16;
  307. default: return vpx_highbd_12_mse16x16;
  308. }
  309. break;
  310. }
  311. }
  312. static unsigned int highbd_get_prediction_error(BLOCK_SIZE bsize,
  313. const struct buf_2d *src,
  314. const struct buf_2d *ref,
  315. int bd) {
  316. unsigned int sse;
  317. const vpx_variance_fn_t fn = highbd_get_block_variance_fn(bsize, bd);
  318. fn(src->buf, src->stride, ref->buf, ref->stride, &sse);
  319. return sse;
  320. }
  321. #endif // CONFIG_VP9_HIGHBITDEPTH
  322. // Refine the motion search range according to the frame dimension
  323. // for first pass test.
  324. static int get_search_range(const VP9_COMP *cpi) {
  325. int sr = 0;
  326. const int dim = VPXMIN(cpi->initial_width, cpi->initial_height);
  327. while ((dim << sr) < MAX_FULL_PEL_VAL) ++sr;
  328. return sr;
  329. }
  330. static void first_pass_motion_search(VP9_COMP *cpi, MACROBLOCK *x,
  331. const MV *ref_mv, MV *best_mv,
  332. int *best_motion_err) {
  333. MACROBLOCKD *const xd = &x->e_mbd;
  334. MV tmp_mv = { 0, 0 };
  335. MV ref_mv_full = { ref_mv->row >> 3, ref_mv->col >> 3 };
  336. int num00, tmp_err, n;
  337. const BLOCK_SIZE bsize = xd->mi[0]->sb_type;
  338. vp9_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[bsize];
  339. const int new_mv_mode_penalty = NEW_MV_MODE_PENALTY;
  340. int step_param = 3;
  341. int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
  342. const int sr = get_search_range(cpi);
  343. step_param += sr;
  344. further_steps -= sr;
  345. // Override the default variance function to use MSE.
  346. v_fn_ptr.vf = get_block_variance_fn(bsize);
  347. #if CONFIG_VP9_HIGHBITDEPTH
  348. if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
  349. v_fn_ptr.vf = highbd_get_block_variance_fn(bsize, xd->bd);
  350. }
  351. #endif // CONFIG_VP9_HIGHBITDEPTH
  352. // Center the initial step/diamond search on best mv.
  353. tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
  354. step_param, x->sadperbit16, &num00,
  355. &v_fn_ptr, ref_mv);
  356. if (tmp_err < INT_MAX)
  357. tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
  358. if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
  359. if (tmp_err < *best_motion_err) {
  360. *best_motion_err = tmp_err;
  361. *best_mv = tmp_mv;
  362. }
  363. // Carry out further step/diamond searches as necessary.
  364. n = num00;
  365. num00 = 0;
  366. while (n < further_steps) {
  367. ++n;
  368. if (num00) {
  369. --num00;
  370. } else {
  371. tmp_err = cpi->diamond_search_sad(x, &cpi->ss_cfg, &ref_mv_full, &tmp_mv,
  372. step_param + n, x->sadperbit16, &num00,
  373. &v_fn_ptr, ref_mv);
  374. if (tmp_err < INT_MAX)
  375. tmp_err = vp9_get_mvpred_var(x, &tmp_mv, ref_mv, &v_fn_ptr, 1);
  376. if (tmp_err < INT_MAX - new_mv_mode_penalty)
  377. tmp_err += new_mv_mode_penalty;
  378. if (tmp_err < *best_motion_err) {
  379. *best_motion_err = tmp_err;
  380. *best_mv = tmp_mv;
  381. }
  382. }
  383. }
  384. }
  385. static BLOCK_SIZE get_bsize(const VP9_COMMON *cm, int mb_row, int mb_col) {
  386. if (2 * mb_col + 1 < cm->mi_cols) {
  387. return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_16X16 : BLOCK_16X8;
  388. } else {
  389. return 2 * mb_row + 1 < cm->mi_rows ? BLOCK_8X16 : BLOCK_8X8;
  390. }
  391. }
  392. static int find_fp_qindex(vpx_bit_depth_t bit_depth) {
  393. int i;
  394. for (i = 0; i < QINDEX_RANGE; ++i)
  395. if (vp9_convert_qindex_to_q(i, bit_depth) >= FIRST_PASS_Q) break;
  396. if (i == QINDEX_RANGE) i--;
  397. return i;
  398. }
  399. static void set_first_pass_params(VP9_COMP *cpi) {
  400. VP9_COMMON *const cm = &cpi->common;
  401. if (!cpi->refresh_alt_ref_frame &&
  402. (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY))) {
  403. cm->frame_type = KEY_FRAME;
  404. } else {
  405. cm->frame_type = INTER_FRAME;
  406. }
  407. // Do not use periodic key frames.
  408. cpi->rc.frames_to_key = INT_MAX;
  409. }
  410. // Scale an sse threshold to account for 8/10/12 bit.
  411. static int scale_sse_threshold(VP9_COMMON *cm, int thresh) {
  412. int ret_val = thresh;
  413. #if CONFIG_VP9_HIGHBITDEPTH
  414. if (cm->use_highbitdepth) {
  415. switch (cm->bit_depth) {
  416. case VPX_BITS_8: ret_val = thresh; break;
  417. case VPX_BITS_10: ret_val = thresh >> 4; break;
  418. case VPX_BITS_12: ret_val = thresh >> 8; break;
  419. default:
  420. assert(0 &&
  421. "cm->bit_depth should be VPX_BITS_8, "
  422. "VPX_BITS_10 or VPX_BITS_12");
  423. }
  424. }
  425. #else
  426. (void)cm;
  427. #endif // CONFIG_VP9_HIGHBITDEPTH
  428. return ret_val;
  429. }
  430. // This threshold is used to track blocks where to all intents and purposes
  431. // the intra prediction error 0. Though the metric we test against
  432. // is technically a sse we are mainly interested in blocks where all the pixels
  433. // in the 8 bit domain have an error of <= 1 (where error = sse) so a
  434. // linear scaling for 10 and 12 bit gives similar results.
  435. #define UL_INTRA_THRESH 50
  436. static int get_ul_intra_threshold(VP9_COMMON *cm) {
  437. int ret_val = UL_INTRA_THRESH;
  438. #if CONFIG_VP9_HIGHBITDEPTH
  439. if (cm->use_highbitdepth) {
  440. switch (cm->bit_depth) {
  441. case VPX_BITS_8: ret_val = UL_INTRA_THRESH; break;
  442. case VPX_BITS_10: ret_val = UL_INTRA_THRESH << 2; break;
  443. case VPX_BITS_12: ret_val = UL_INTRA_THRESH << 4; break;
  444. default:
  445. assert(0 &&
  446. "cm->bit_depth should be VPX_BITS_8, "
  447. "VPX_BITS_10 or VPX_BITS_12");
  448. }
  449. }
  450. #else
  451. (void)cm;
  452. #endif // CONFIG_VP9_HIGHBITDEPTH
  453. return ret_val;
  454. }
  455. #define SMOOTH_INTRA_THRESH 4000
  456. static int get_smooth_intra_threshold(VP9_COMMON *cm) {
  457. int ret_val = SMOOTH_INTRA_THRESH;
  458. #if CONFIG_VP9_HIGHBITDEPTH
  459. if (cm->use_highbitdepth) {
  460. switch (cm->bit_depth) {
  461. case VPX_BITS_8: ret_val = SMOOTH_INTRA_THRESH; break;
  462. case VPX_BITS_10: ret_val = SMOOTH_INTRA_THRESH << 4; break;
  463. case VPX_BITS_12: ret_val = SMOOTH_INTRA_THRESH << 8; break;
  464. default:
  465. assert(0 &&
  466. "cm->bit_depth should be VPX_BITS_8, "
  467. "VPX_BITS_10 or VPX_BITS_12");
  468. }
  469. }
  470. #else
  471. (void)cm;
  472. #endif // CONFIG_VP9_HIGHBITDEPTH
  473. return ret_val;
  474. }
  475. #define FP_DN_THRESH 8
  476. #define FP_MAX_DN_THRESH 16
  477. #define KERNEL_SIZE 3
  478. // Baseline Kernal weights for first pass noise metric
  479. static uint8_t fp_dn_kernal_3[KERNEL_SIZE * KERNEL_SIZE] = { 1, 2, 1, 2, 4,
  480. 2, 1, 2, 1 };
  481. // Estimate noise at a single point based on the impace of a spatial kernal
  482. // on the point value
  483. static int fp_estimate_point_noise(uint8_t *src_ptr, const int stride) {
  484. int sum_weight = 0;
  485. int sum_val = 0;
  486. int i, j;
  487. int max_diff = 0;
  488. int diff;
  489. int dn_diff;
  490. uint8_t *tmp_ptr;
  491. uint8_t *kernal_ptr;
  492. uint8_t dn_val;
  493. uint8_t centre_val = *src_ptr;
  494. kernal_ptr = fp_dn_kernal_3;
  495. // Apply the kernal
  496. tmp_ptr = src_ptr - stride - 1;
  497. for (i = 0; i < KERNEL_SIZE; ++i) {
  498. for (j = 0; j < KERNEL_SIZE; ++j) {
  499. diff = abs((int)centre_val - (int)tmp_ptr[j]);
  500. max_diff = VPXMAX(max_diff, diff);
  501. if (diff <= FP_DN_THRESH) {
  502. sum_weight += *kernal_ptr;
  503. sum_val += (int)tmp_ptr[j] * (int)*kernal_ptr;
  504. }
  505. ++kernal_ptr;
  506. }
  507. tmp_ptr += stride;
  508. }
  509. if (max_diff < FP_MAX_DN_THRESH)
  510. // Update the source value with the new filtered value
  511. dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
  512. else
  513. dn_val = *src_ptr;
  514. // return the noise energy as the square of the difference between the
  515. // denoised and raw value.
  516. dn_diff = (int)*src_ptr - (int)dn_val;
  517. return dn_diff * dn_diff;
  518. }
  519. #if CONFIG_VP9_HIGHBITDEPTH
  520. static int fp_highbd_estimate_point_noise(uint8_t *src_ptr, const int stride) {
  521. int sum_weight = 0;
  522. int sum_val = 0;
  523. int i, j;
  524. int max_diff = 0;
  525. int diff;
  526. int dn_diff;
  527. uint8_t *tmp_ptr;
  528. uint16_t *tmp_ptr16;
  529. uint8_t *kernal_ptr;
  530. uint16_t dn_val;
  531. uint16_t centre_val = *CONVERT_TO_SHORTPTR(src_ptr);
  532. kernal_ptr = fp_dn_kernal_3;
  533. // Apply the kernal
  534. tmp_ptr = src_ptr - stride - 1;
  535. for (i = 0; i < KERNEL_SIZE; ++i) {
  536. tmp_ptr16 = CONVERT_TO_SHORTPTR(tmp_ptr);
  537. for (j = 0; j < KERNEL_SIZE; ++j) {
  538. diff = abs((int)centre_val - (int)tmp_ptr16[j]);
  539. max_diff = VPXMAX(max_diff, diff);
  540. if (diff <= FP_DN_THRESH) {
  541. sum_weight += *kernal_ptr;
  542. sum_val += (int)tmp_ptr16[j] * (int)*kernal_ptr;
  543. }
  544. ++kernal_ptr;
  545. }
  546. tmp_ptr += stride;
  547. }
  548. if (max_diff < FP_MAX_DN_THRESH)
  549. // Update the source value with the new filtered value
  550. dn_val = (sum_val + (sum_weight >> 1)) / sum_weight;
  551. else
  552. dn_val = *CONVERT_TO_SHORTPTR(src_ptr);
  553. // return the noise energy as the square of the difference between the
  554. // denoised and raw value.
  555. dn_diff = (int)(*CONVERT_TO_SHORTPTR(src_ptr)) - (int)dn_val;
  556. return dn_diff * dn_diff;
  557. }
  558. #endif
  559. // Estimate noise for a block.
  560. static int fp_estimate_block_noise(MACROBLOCK *x, BLOCK_SIZE bsize) {
  561. #if CONFIG_VP9_HIGHBITDEPTH
  562. MACROBLOCKD *xd = &x->e_mbd;
  563. #endif
  564. uint8_t *src_ptr = &x->plane[0].src.buf[0];
  565. const int width = num_4x4_blocks_wide_lookup[bsize] * 4;
  566. const int height = num_4x4_blocks_high_lookup[bsize] * 4;
  567. int w, h;
  568. int stride = x->plane[0].src.stride;
  569. int block_noise = 0;
  570. // Sampled points to reduce cost overhead.
  571. for (h = 0; h < height; h += 2) {
  572. for (w = 0; w < width; w += 2) {
  573. #if CONFIG_VP9_HIGHBITDEPTH
  574. if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH)
  575. block_noise += fp_highbd_estimate_point_noise(src_ptr, stride);
  576. else
  577. block_noise += fp_estimate_point_noise(src_ptr, stride);
  578. #else
  579. block_noise += fp_estimate_point_noise(src_ptr, stride);
  580. #endif
  581. ++src_ptr;
  582. }
  583. src_ptr += (stride - width);
  584. }
  585. return block_noise << 2; // Scale << 2 to account for sampling.
  586. }
  587. #define INVALID_ROW -1
  588. void vp9_first_pass(VP9_COMP *cpi, const struct lookahead_entry *source) {
  589. int mb_row, mb_col;
  590. MACROBLOCK *const x = &cpi->td.mb;
  591. VP9_COMMON *const cm = &cpi->common;
  592. MACROBLOCKD *const xd = &x->e_mbd;
  593. TileInfo tile;
  594. struct macroblock_plane *const p = x->plane;
  595. struct macroblockd_plane *const pd = xd->plane;
  596. const PICK_MODE_CONTEXT *ctx = &cpi->td.pc_root->none;
  597. int i;
  598. int recon_yoffset, recon_uvoffset;
  599. int64_t intra_error = 0;
  600. int64_t coded_error = 0;
  601. int64_t sr_coded_error = 0;
  602. int64_t frame_noise_energy = 0;
  603. int sum_mvr = 0, sum_mvc = 0;
  604. int sum_mvr_abs = 0, sum_mvc_abs = 0;
  605. int64_t sum_mvrs = 0, sum_mvcs = 0;
  606. int mvcount = 0;
  607. int intercount = 0;
  608. int second_ref_count = 0;
  609. const int intrapenalty = INTRA_MODE_PENALTY;
  610. double neutral_count;
  611. int intra_skip_count = 0;
  612. int intra_smooth_count = 0;
  613. int image_data_start_row = INVALID_ROW;
  614. int new_mv_count = 0;
  615. int sum_in_vectors = 0;
  616. MV lastmv = { 0, 0 };
  617. TWO_PASS *twopass = &cpi->twopass;
  618. const MV zero_mv = { 0, 0 };
  619. int recon_y_stride, recon_uv_stride, uv_mb_height;
  620. YV12_BUFFER_CONFIG *const lst_yv12 = get_ref_frame_buffer(cpi, LAST_FRAME);
  621. YV12_BUFFER_CONFIG *gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
  622. YV12_BUFFER_CONFIG *const new_yv12 = get_frame_new_buffer(cm);
  623. const YV12_BUFFER_CONFIG *first_ref_buf = lst_yv12;
  624. LAYER_CONTEXT *const lc =
  625. is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
  626. : NULL;
  627. double intra_factor;
  628. double brightness_factor;
  629. BufferPool *const pool = cm->buffer_pool;
  630. MODE_INFO mi_above, mi_left;
  631. // First pass code requires valid last and new frame buffers.
  632. assert(new_yv12 != NULL);
  633. assert((lc != NULL) || frame_is_intra_only(cm) || (lst_yv12 != NULL));
  634. #if CONFIG_FP_MB_STATS
  635. if (cpi->use_fp_mb_stats) {
  636. vp9_zero_array(cpi->twopass.frame_mb_stats_buf, cm->initial_mbs);
  637. }
  638. #endif
  639. vpx_clear_system_state();
  640. intra_factor = 0.0;
  641. brightness_factor = 0.0;
  642. neutral_count = 0.0;
  643. set_first_pass_params(cpi);
  644. vp9_set_quantizer(cm, find_fp_qindex(cm->bit_depth));
  645. if (lc != NULL) {
  646. twopass = &lc->twopass;
  647. cpi->lst_fb_idx = cpi->svc.spatial_layer_id;
  648. cpi->ref_frame_flags = VP9_LAST_FLAG;
  649. if (cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id <
  650. REF_FRAMES) {
  651. cpi->gld_fb_idx =
  652. cpi->svc.number_spatial_layers + cpi->svc.spatial_layer_id;
  653. cpi->ref_frame_flags |= VP9_GOLD_FLAG;
  654. cpi->refresh_golden_frame = (lc->current_video_frame_in_layer == 0);
  655. } else {
  656. cpi->refresh_golden_frame = 0;
  657. }
  658. if (lc->current_video_frame_in_layer == 0) cpi->ref_frame_flags = 0;
  659. vp9_scale_references(cpi);
  660. // Use either last frame or alt frame for motion search.
  661. if (cpi->ref_frame_flags & VP9_LAST_FLAG) {
  662. first_ref_buf = vp9_get_scaled_ref_frame(cpi, LAST_FRAME);
  663. if (first_ref_buf == NULL)
  664. first_ref_buf = get_ref_frame_buffer(cpi, LAST_FRAME);
  665. }
  666. if (cpi->ref_frame_flags & VP9_GOLD_FLAG) {
  667. gld_yv12 = vp9_get_scaled_ref_frame(cpi, GOLDEN_FRAME);
  668. if (gld_yv12 == NULL) {
  669. gld_yv12 = get_ref_frame_buffer(cpi, GOLDEN_FRAME);
  670. }
  671. } else {
  672. gld_yv12 = NULL;
  673. }
  674. set_ref_ptrs(cm, xd,
  675. (cpi->ref_frame_flags & VP9_LAST_FLAG) ? LAST_FRAME : NONE,
  676. (cpi->ref_frame_flags & VP9_GOLD_FLAG) ? GOLDEN_FRAME : NONE);
  677. cpi->Source = vp9_scale_if_required(cm, cpi->un_scaled_source,
  678. &cpi->scaled_source, 0);
  679. }
  680. vp9_setup_block_planes(&x->e_mbd, cm->subsampling_x, cm->subsampling_y);
  681. vp9_setup_src_planes(x, cpi->Source, 0, 0);
  682. vp9_setup_dst_planes(xd->plane, new_yv12, 0, 0);
  683. if (!frame_is_intra_only(cm)) {
  684. vp9_setup_pre_planes(xd, 0, first_ref_buf, 0, 0, NULL);
  685. }
  686. xd->mi = cm->mi_grid_visible;
  687. xd->mi[0] = cm->mi;
  688. vp9_frame_init_quantizer(cpi);
  689. for (i = 0; i < MAX_MB_PLANE; ++i) {
  690. p[i].coeff = ctx->coeff_pbuf[i][1];
  691. p[i].qcoeff = ctx->qcoeff_pbuf[i][1];
  692. pd[i].dqcoeff = ctx->dqcoeff_pbuf[i][1];
  693. p[i].eobs = ctx->eobs_pbuf[i][1];
  694. }
  695. x->skip_recode = 0;
  696. vp9_init_mv_probs(cm);
  697. vp9_initialize_rd_consts(cpi);
  698. // Tiling is ignored in the first pass.
  699. vp9_tile_init(&tile, cm, 0, 0);
  700. recon_y_stride = new_yv12->y_stride;
  701. recon_uv_stride = new_yv12->uv_stride;
  702. uv_mb_height = 16 >> (new_yv12->y_height > new_yv12->uv_height);
  703. for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
  704. MV best_ref_mv = { 0, 0 };
  705. // Reset above block coeffs.
  706. recon_yoffset = (mb_row * recon_y_stride * 16);
  707. recon_uvoffset = (mb_row * recon_uv_stride * uv_mb_height);
  708. // Set up limit values for motion vectors to prevent them extending
  709. // outside the UMV borders.
  710. x->mv_limits.row_min = -((mb_row * 16) + BORDER_MV_PIXELS_B16);
  711. x->mv_limits.row_max =
  712. ((cm->mb_rows - 1 - mb_row) * 16) + BORDER_MV_PIXELS_B16;
  713. for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
  714. int this_error;
  715. int this_intra_error;
  716. const int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
  717. const BLOCK_SIZE bsize = get_bsize(cm, mb_row, mb_col);
  718. double log_intra;
  719. int level_sample;
  720. #if CONFIG_FP_MB_STATS
  721. const int mb_index = mb_row * cm->mb_cols + mb_col;
  722. #endif
  723. vpx_clear_system_state();
  724. xd->plane[0].dst.buf = new_yv12->y_buffer + recon_yoffset;
  725. xd->plane[1].dst.buf = new_yv12->u_buffer + recon_uvoffset;
  726. xd->plane[2].dst.buf = new_yv12->v_buffer + recon_uvoffset;
  727. xd->mi[0]->sb_type = bsize;
  728. xd->mi[0]->ref_frame[0] = INTRA_FRAME;
  729. set_mi_row_col(xd, &tile, mb_row << 1, num_8x8_blocks_high_lookup[bsize],
  730. mb_col << 1, num_8x8_blocks_wide_lookup[bsize],
  731. cm->mi_rows, cm->mi_cols);
  732. // Are edges available for intra prediction?
  733. // Since the firstpass does not populate the mi_grid_visible,
  734. // above_mi/left_mi must be overwritten with a nonzero value when edges
  735. // are available. Required by vp9_predict_intra_block().
  736. xd->above_mi = (mb_row != 0) ? &mi_above : NULL;
  737. xd->left_mi = (mb_col > tile.mi_col_start) ? &mi_left : NULL;
  738. // Do intra 16x16 prediction.
  739. x->skip_encode = 0;
  740. xd->mi[0]->mode = DC_PRED;
  741. xd->mi[0]->tx_size =
  742. use_dc_pred ? (bsize >= BLOCK_16X16 ? TX_16X16 : TX_8X8) : TX_4X4;
  743. vp9_encode_intra_block_plane(x, bsize, 0, 0);
  744. this_error = vpx_get_mb_ss(x->plane[0].src_diff);
  745. this_intra_error = this_error;
  746. // Keep a record of blocks that have very low intra error residual
  747. // (i.e. are in effect completely flat and untextured in the intra
  748. // domain). In natural videos this is uncommon, but it is much more
  749. // common in animations, graphics and screen content, so may be used
  750. // as a signal to detect these types of content.
  751. if (this_error < get_ul_intra_threshold(cm)) {
  752. ++intra_skip_count;
  753. } else if ((mb_col > 0) && (image_data_start_row == INVALID_ROW)) {
  754. image_data_start_row = mb_row;
  755. }
  756. // Blocks that are mainly smooth in the intra domain.
  757. // Some special accounting for CQ but also these are better for testing
  758. // noise levels.
  759. if (this_error < get_smooth_intra_threshold(cm)) {
  760. ++intra_smooth_count;
  761. }
  762. // Special case noise measurement for first frame.
  763. if (cm->current_video_frame == 0) {
  764. if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
  765. frame_noise_energy += fp_estimate_block_noise(x, bsize);
  766. } else {
  767. frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
  768. }
  769. }
  770. #if CONFIG_VP9_HIGHBITDEPTH
  771. if (cm->use_highbitdepth) {
  772. switch (cm->bit_depth) {
  773. case VPX_BITS_8: break;
  774. case VPX_BITS_10: this_error >>= 4; break;
  775. case VPX_BITS_12: this_error >>= 8; break;
  776. default:
  777. assert(0 &&
  778. "cm->bit_depth should be VPX_BITS_8, "
  779. "VPX_BITS_10 or VPX_BITS_12");
  780. return;
  781. }
  782. }
  783. #endif // CONFIG_VP9_HIGHBITDEPTH
  784. vpx_clear_system_state();
  785. log_intra = log(this_error + 1.0);
  786. if (log_intra < 10.0)
  787. intra_factor += 1.0 + ((10.0 - log_intra) * 0.05);
  788. else
  789. intra_factor += 1.0;
  790. #if CONFIG_VP9_HIGHBITDEPTH
  791. if (cm->use_highbitdepth)
  792. level_sample = CONVERT_TO_SHORTPTR(x->plane[0].src.buf)[0];
  793. else
  794. level_sample = x->plane[0].src.buf[0];
  795. #else
  796. level_sample = x->plane[0].src.buf[0];
  797. #endif
  798. if ((level_sample < DARK_THRESH) && (log_intra < 9.0))
  799. brightness_factor += 1.0 + (0.01 * (DARK_THRESH - level_sample));
  800. else
  801. brightness_factor += 1.0;
  802. // Intrapenalty below deals with situations where the intra and inter
  803. // error scores are very low (e.g. a plain black frame).
  804. // We do not have special cases in first pass for 0,0 and nearest etc so
  805. // all inter modes carry an overhead cost estimate for the mv.
  806. // When the error score is very low this causes us to pick all or lots of
  807. // INTRA modes and throw lots of key frames.
  808. // This penalty adds a cost matching that of a 0,0 mv to the intra case.
  809. this_error += intrapenalty;
  810. // Accumulate the intra error.
  811. intra_error += (int64_t)this_error;
  812. #if CONFIG_FP_MB_STATS
  813. if (cpi->use_fp_mb_stats) {
  814. // initialization
  815. cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
  816. }
  817. #endif
  818. // Set up limit values for motion vectors to prevent them extending
  819. // outside the UMV borders.
  820. x->mv_limits.col_min = -((mb_col * 16) + BORDER_MV_PIXELS_B16);
  821. x->mv_limits.col_max =
  822. ((cm->mb_cols - 1 - mb_col) * 16) + BORDER_MV_PIXELS_B16;
  823. // Other than for the first frame do a motion search.
  824. if ((lc == NULL && cm->current_video_frame > 0) ||
  825. (lc != NULL && lc->current_video_frame_in_layer > 0)) {
  826. int tmp_err, motion_error, raw_motion_error;
  827. // Assume 0,0 motion with no mv overhead.
  828. MV mv = { 0, 0 }, tmp_mv = { 0, 0 };
  829. struct buf_2d unscaled_last_source_buf_2d;
  830. xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
  831. #if CONFIG_VP9_HIGHBITDEPTH
  832. if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
  833. motion_error = highbd_get_prediction_error(
  834. bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
  835. } else {
  836. motion_error = get_prediction_error(bsize, &x->plane[0].src,
  837. &xd->plane[0].pre[0]);
  838. }
  839. #else
  840. motion_error =
  841. get_prediction_error(bsize, &x->plane[0].src, &xd->plane[0].pre[0]);
  842. #endif // CONFIG_VP9_HIGHBITDEPTH
  843. // Compute the motion error of the 0,0 motion using the last source
  844. // frame as the reference. Skip the further motion search on
  845. // reconstructed frame if this error is small.
  846. unscaled_last_source_buf_2d.buf =
  847. cpi->unscaled_last_source->y_buffer + recon_yoffset;
  848. unscaled_last_source_buf_2d.stride =
  849. cpi->unscaled_last_source->y_stride;
  850. #if CONFIG_VP9_HIGHBITDEPTH
  851. if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
  852. raw_motion_error = highbd_get_prediction_error(
  853. bsize, &x->plane[0].src, &unscaled_last_source_buf_2d, xd->bd);
  854. } else {
  855. raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
  856. &unscaled_last_source_buf_2d);
  857. }
  858. #else
  859. raw_motion_error = get_prediction_error(bsize, &x->plane[0].src,
  860. &unscaled_last_source_buf_2d);
  861. #endif // CONFIG_VP9_HIGHBITDEPTH
  862. // TODO(pengchong): Replace the hard-coded threshold
  863. if (raw_motion_error > 25 || lc != NULL) {
  864. // Test last reference frame using the previous best mv as the
  865. // starting point (best reference) for the search.
  866. first_pass_motion_search(cpi, x, &best_ref_mv, &mv, &motion_error);
  867. // If the current best reference mv is not centered on 0,0 then do a
  868. // 0,0 based search as well.
  869. if (!is_zero_mv(&best_ref_mv)) {
  870. tmp_err = INT_MAX;
  871. first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv, &tmp_err);
  872. if (tmp_err < motion_error) {
  873. motion_error = tmp_err;
  874. mv = tmp_mv;
  875. }
  876. }
  877. // Search in an older reference frame.
  878. if (((lc == NULL && cm->current_video_frame > 1) ||
  879. (lc != NULL && lc->current_video_frame_in_layer > 1)) &&
  880. gld_yv12 != NULL) {
  881. // Assume 0,0 motion with no mv overhead.
  882. int gf_motion_error;
  883. xd->plane[0].pre[0].buf = gld_yv12->y_buffer + recon_yoffset;
  884. #if CONFIG_VP9_HIGHBITDEPTH
  885. if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
  886. gf_motion_error = highbd_get_prediction_error(
  887. bsize, &x->plane[0].src, &xd->plane[0].pre[0], xd->bd);
  888. } else {
  889. gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
  890. &xd->plane[0].pre[0]);
  891. }
  892. #else
  893. gf_motion_error = get_prediction_error(bsize, &x->plane[0].src,
  894. &xd->plane[0].pre[0]);
  895. #endif // CONFIG_VP9_HIGHBITDEPTH
  896. first_pass_motion_search(cpi, x, &zero_mv, &tmp_mv,
  897. &gf_motion_error);
  898. if (gf_motion_error < motion_error && gf_motion_error < this_error)
  899. ++second_ref_count;
  900. // Reset to last frame as reference buffer.
  901. xd->plane[0].pre[0].buf = first_ref_buf->y_buffer + recon_yoffset;
  902. xd->plane[1].pre[0].buf = first_ref_buf->u_buffer + recon_uvoffset;
  903. xd->plane[2].pre[0].buf = first_ref_buf->v_buffer + recon_uvoffset;
  904. // In accumulating a score for the older reference frame take the
  905. // best of the motion predicted score and the intra coded error
  906. // (just as will be done for) accumulation of "coded_error" for
  907. // the last frame.
  908. if (gf_motion_error < this_error)
  909. sr_coded_error += gf_motion_error;
  910. else
  911. sr_coded_error += this_error;
  912. } else {
  913. sr_coded_error += motion_error;
  914. }
  915. } else {
  916. sr_coded_error += motion_error;
  917. }
  918. // Start by assuming that intra mode is best.
  919. best_ref_mv.row = 0;
  920. best_ref_mv.col = 0;
  921. #if CONFIG_FP_MB_STATS
  922. if (cpi->use_fp_mb_stats) {
  923. // intra prediction statistics
  924. cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
  925. cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_DCINTRA_MASK;
  926. cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
  927. if (this_error > FPMB_ERROR_LARGE_TH) {
  928. cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_LARGE_MASK;
  929. } else if (this_error < FPMB_ERROR_SMALL_TH) {
  930. cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_ERROR_SMALL_MASK;
  931. }
  932. }
  933. #endif
  934. if (motion_error <= this_error) {
  935. vpx_clear_system_state();
  936. // Keep a count of cases where the inter and intra were very close
  937. // and very low. This helps with scene cut detection for example in
  938. // cropped clips with black bars at the sides or top and bottom.
  939. if (((this_error - intrapenalty) * 9 <= motion_error * 10) &&
  940. (this_error < (2 * intrapenalty))) {
  941. neutral_count += 1.0;
  942. // Also track cases where the intra is not much worse than the inter
  943. // and use this in limiting the GF/arf group length.
  944. } else if ((this_error > NCOUNT_INTRA_THRESH) &&
  945. (this_error < (NCOUNT_INTRA_FACTOR * motion_error))) {
  946. neutral_count +=
  947. (double)motion_error / DOUBLE_DIVIDE_CHECK((double)this_error);
  948. }
  949. mv.row *= 8;
  950. mv.col *= 8;
  951. this_error = motion_error;
  952. xd->mi[0]->mode = NEWMV;
  953. xd->mi[0]->mv[0].as_mv = mv;
  954. xd->mi[0]->tx_size = TX_4X4;
  955. xd->mi[0]->ref_frame[0] = LAST_FRAME;
  956. xd->mi[0]->ref_frame[1] = NONE;
  957. vp9_build_inter_predictors_sby(xd, mb_row << 1, mb_col << 1, bsize);
  958. vp9_encode_sby_pass1(x, bsize);
  959. sum_mvr += mv.row;
  960. sum_mvr_abs += abs(mv.row);
  961. sum_mvc += mv.col;
  962. sum_mvc_abs += abs(mv.col);
  963. sum_mvrs += mv.row * mv.row;
  964. sum_mvcs += mv.col * mv.col;
  965. ++intercount;
  966. best_ref_mv = mv;
  967. #if CONFIG_FP_MB_STATS
  968. if (cpi->use_fp_mb_stats) {
  969. // inter prediction statistics
  970. cpi->twopass.frame_mb_stats_buf[mb_index] = 0;
  971. cpi->twopass.frame_mb_stats_buf[mb_index] &= ~FPMB_DCINTRA_MASK;
  972. cpi->twopass.frame_mb_stats_buf[mb_index] |= FPMB_MOTION_ZERO_MASK;
  973. if (this_error > FPMB_ERROR_LARGE_TH) {
  974. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  975. FPMB_ERROR_LARGE_MASK;
  976. } else if (this_error < FPMB_ERROR_SMALL_TH) {
  977. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  978. FPMB_ERROR_SMALL_MASK;
  979. }
  980. }
  981. #endif
  982. if (!is_zero_mv(&mv)) {
  983. ++mvcount;
  984. #if CONFIG_FP_MB_STATS
  985. if (cpi->use_fp_mb_stats) {
  986. cpi->twopass.frame_mb_stats_buf[mb_index] &=
  987. ~FPMB_MOTION_ZERO_MASK;
  988. // check estimated motion direction
  989. if (mv.as_mv.col > 0 && mv.as_mv.col >= abs(mv.as_mv.row)) {
  990. // right direction
  991. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  992. FPMB_MOTION_RIGHT_MASK;
  993. } else if (mv.as_mv.row < 0 &&
  994. abs(mv.as_mv.row) >= abs(mv.as_mv.col)) {
  995. // up direction
  996. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  997. FPMB_MOTION_UP_MASK;
  998. } else if (mv.as_mv.col < 0 &&
  999. abs(mv.as_mv.col) >= abs(mv.as_mv.row)) {
  1000. // left direction
  1001. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  1002. FPMB_MOTION_LEFT_MASK;
  1003. } else {
  1004. // down direction
  1005. cpi->twopass.frame_mb_stats_buf[mb_index] |=
  1006. FPMB_MOTION_DOWN_MASK;
  1007. }
  1008. }
  1009. #endif
  1010. // Non-zero vector, was it different from the last non zero vector?
  1011. if (!is_equal_mv(&mv, &lastmv)) ++new_mv_count;
  1012. lastmv = mv;
  1013. // Does the row vector point inwards or outwards?
  1014. if (mb_row < cm->mb_rows / 2) {
  1015. if (mv.row > 0)
  1016. --sum_in_vectors;
  1017. else if (mv.row < 0)
  1018. ++sum_in_vectors;
  1019. } else if (mb_row > cm->mb_rows / 2) {
  1020. if (mv.row > 0)
  1021. ++sum_in_vectors;
  1022. else if (mv.row < 0)
  1023. --sum_in_vectors;
  1024. }
  1025. // Does the col vector point inwards or outwards?
  1026. if (mb_col < cm->mb_cols / 2) {
  1027. if (mv.col > 0)
  1028. --sum_in_vectors;
  1029. else if (mv.col < 0)
  1030. ++sum_in_vectors;
  1031. } else if (mb_col > cm->mb_cols / 2) {
  1032. if (mv.col > 0)
  1033. ++sum_in_vectors;
  1034. else if (mv.col < 0)
  1035. --sum_in_vectors;
  1036. }
  1037. frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
  1038. } else if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH)) {
  1039. frame_noise_energy += fp_estimate_block_noise(x, bsize);
  1040. } else { // 0,0 mv but high error
  1041. frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
  1042. }
  1043. } else { // Intra < inter error
  1044. if (this_intra_error < scale_sse_threshold(cm, LOW_I_THRESH))
  1045. frame_noise_energy += fp_estimate_block_noise(x, bsize);
  1046. else
  1047. frame_noise_energy += (int64_t)SECTION_NOISE_DEF;
  1048. }
  1049. } else {
  1050. sr_coded_error += (int64_t)this_error;
  1051. }
  1052. coded_error += (int64_t)this_error;
  1053. // Adjust to the next column of MBs.
  1054. x->plane[0].src.buf += 16;
  1055. x->plane[1].src.buf += uv_mb_height;
  1056. x->plane[2].src.buf += uv_mb_height;
  1057. recon_yoffset += 16;
  1058. recon_uvoffset += uv_mb_height;
  1059. }
  1060. // Adjust to the next row of MBs.
  1061. x->plane[0].src.buf += 16 * x->plane[0].src.stride - 16 * cm->mb_cols;
  1062. x->plane[1].src.buf +=
  1063. uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
  1064. x->plane[2].src.buf +=
  1065. uv_mb_height * x->plane[1].src.stride - uv_mb_height * cm->mb_cols;
  1066. vpx_clear_system_state();
  1067. }
  1068. // Clamp the image start to rows/2. This number of rows is discarded top
  1069. // and bottom as dead data so rows / 2 means the frame is blank.
  1070. if ((image_data_start_row > cm->mb_rows / 2) ||
  1071. (image_data_start_row == INVALID_ROW)) {
  1072. image_data_start_row = cm->mb_rows / 2;
  1073. }
  1074. // Exclude any image dead zone
  1075. if (image_data_start_row > 0) {
  1076. intra_skip_count =
  1077. VPXMAX(0, intra_skip_count - (image_data_start_row * cm->mb_cols * 2));
  1078. }
  1079. {
  1080. FIRSTPASS_STATS fps;
  1081. // The minimum error here insures some bit allocation to frames even
  1082. // in static regions. The allocation per MB declines for larger formats
  1083. // where the typical "real" energy per MB also falls.
  1084. // Initial estimate here uses sqrt(mbs) to define the min_err, where the
  1085. // number of mbs is proportional to the image area.
  1086. const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
  1087. ? cpi->initial_mbs
  1088. : cpi->common.MBs;
  1089. const double min_err = 200 * sqrt(num_mbs);
  1090. intra_factor = intra_factor / (double)num_mbs;
  1091. brightness_factor = brightness_factor / (double)num_mbs;
  1092. fps.weight = intra_factor * brightness_factor;
  1093. fps.frame = cm->current_video_frame;
  1094. fps.spatial_layer_id = cpi->svc.spatial_layer_id;
  1095. fps.coded_error = (double)(coded_error >> 8) + min_err;
  1096. fps.sr_coded_error = (double)(sr_coded_error >> 8) + min_err;
  1097. fps.intra_error = (double)(intra_error >> 8) + min_err;
  1098. fps.frame_noise_energy = (double)frame_noise_energy / (double)num_mbs;
  1099. fps.count = 1.0;
  1100. fps.pcnt_inter = (double)intercount / num_mbs;
  1101. fps.pcnt_second_ref = (double)second_ref_count / num_mbs;
  1102. fps.pcnt_neutral = (double)neutral_count / num_mbs;
  1103. fps.intra_skip_pct = (double)intra_skip_count / num_mbs;
  1104. fps.intra_smooth_pct = (double)intra_smooth_count / num_mbs;
  1105. fps.inactive_zone_rows = (double)image_data_start_row;
  1106. // Currently set to 0 as most issues relate to letter boxing.
  1107. fps.inactive_zone_cols = (double)0;
  1108. if (mvcount > 0) {
  1109. fps.MVr = (double)sum_mvr / mvcount;
  1110. fps.mvr_abs = (double)sum_mvr_abs / mvcount;
  1111. fps.MVc = (double)sum_mvc / mvcount;
  1112. fps.mvc_abs = (double)sum_mvc_abs / mvcount;
  1113. fps.MVrv =
  1114. ((double)sum_mvrs - ((double)sum_mvr * sum_mvr / mvcount)) / mvcount;
  1115. fps.MVcv =
  1116. ((double)sum_mvcs - ((double)sum_mvc * sum_mvc / mvcount)) / mvcount;
  1117. fps.mv_in_out_count = (double)sum_in_vectors / (mvcount * 2);
  1118. fps.new_mv_count = new_mv_count;
  1119. fps.pcnt_motion = (double)mvcount / num_mbs;
  1120. } else {
  1121. fps.MVr = 0.0;
  1122. fps.mvr_abs = 0.0;
  1123. fps.MVc = 0.0;
  1124. fps.mvc_abs = 0.0;
  1125. fps.MVrv = 0.0;
  1126. fps.MVcv = 0.0;
  1127. fps.mv_in_out_count = 0.0;
  1128. fps.new_mv_count = 0.0;
  1129. fps.pcnt_motion = 0.0;
  1130. }
  1131. // Dont allow a value of 0 for duration.
  1132. // (Section duration is also defaulted to minimum of 1.0).
  1133. fps.duration = VPXMAX(1.0, (double)(source->ts_end - source->ts_start));
  1134. // Don't want to do output stats with a stack variable!
  1135. twopass->this_frame_stats = fps;
  1136. output_stats(&twopass->this_frame_stats, cpi->output_pkt_list);
  1137. accumulate_stats(&twopass->total_stats, &fps);
  1138. #if CONFIG_FP_MB_STATS
  1139. if (cpi->use_fp_mb_stats) {
  1140. output_fpmb_stats(twopass->frame_mb_stats_buf, cm, cpi->output_pkt_list);
  1141. }
  1142. #endif
  1143. }
  1144. // Copy the previous Last Frame back into gf and and arf buffers if
  1145. // the prediction is good enough... but also don't allow it to lag too far.
  1146. if ((twopass->sr_update_lag > 3) ||
  1147. ((cm->current_video_frame > 0) &&
  1148. (twopass->this_frame_stats.pcnt_inter > 0.20) &&
  1149. ((twopass->this_frame_stats.intra_error /
  1150. DOUBLE_DIVIDE_CHECK(twopass->this_frame_stats.coded_error)) > 2.0))) {
  1151. if (gld_yv12 != NULL) {
  1152. ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
  1153. cm->ref_frame_map[cpi->lst_fb_idx]);
  1154. }
  1155. twopass->sr_update_lag = 1;
  1156. } else {
  1157. ++twopass->sr_update_lag;
  1158. }
  1159. vpx_extend_frame_borders(new_yv12);
  1160. if (lc != NULL) {
  1161. vp9_update_reference_frames(cpi);
  1162. } else {
  1163. // The frame we just compressed now becomes the last frame.
  1164. ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->lst_fb_idx],
  1165. cm->new_fb_idx);
  1166. }
  1167. // Special case for the first frame. Copy into the GF buffer as a second
  1168. // reference.
  1169. if (cm->current_video_frame == 0 && cpi->gld_fb_idx != INVALID_IDX &&
  1170. lc == NULL) {
  1171. ref_cnt_fb(pool->frame_bufs, &cm->ref_frame_map[cpi->gld_fb_idx],
  1172. cm->ref_frame_map[cpi->lst_fb_idx]);
  1173. }
  1174. // Use this to see what the first pass reconstruction looks like.
  1175. if (0) {
  1176. char filename[512];
  1177. FILE *recon_file;
  1178. snprintf(filename, sizeof(filename), "enc%04d.yuv",
  1179. (int)cm->current_video_frame);
  1180. if (cm->current_video_frame == 0)
  1181. recon_file = fopen(filename, "wb");
  1182. else
  1183. recon_file = fopen(filename, "ab");
  1184. (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
  1185. fclose(recon_file);
  1186. }
  1187. ++cm->current_video_frame;
  1188. if (cpi->use_svc) vp9_inc_frame_in_layer(cpi);
  1189. }
  1190. static double calc_correction_factor(double err_per_mb, double err_divisor,
  1191. double pt_low, double pt_high, int q,
  1192. vpx_bit_depth_t bit_depth) {
  1193. const double error_term = err_per_mb / err_divisor;
  1194. // Adjustment based on actual quantizer to power term.
  1195. const double power_term =
  1196. VPXMIN(vp9_convert_qindex_to_q(q, bit_depth) * 0.01 + pt_low, pt_high);
  1197. // Calculate correction factor.
  1198. if (power_term < 1.0) assert(error_term >= 0.0);
  1199. return fclamp(pow(error_term, power_term), 0.05, 5.0);
  1200. }
  1201. #define ERR_DIVISOR 115.0
  1202. #define NOISE_FACTOR_MIN 0.9
  1203. #define NOISE_FACTOR_MAX 1.1
  1204. static int get_twopass_worst_quality(VP9_COMP *cpi, const double section_err,
  1205. double inactive_zone, double section_noise,
  1206. int section_target_bandwidth) {
  1207. const RATE_CONTROL *const rc = &cpi->rc;
  1208. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1209. TWO_PASS *const twopass = &cpi->twopass;
  1210. // Clamp the target rate to VBR min / max limts.
  1211. const int target_rate =
  1212. vp9_rc_clamp_pframe_target_size(cpi, section_target_bandwidth);
  1213. double noise_factor = pow((section_noise / SECTION_NOISE_DEF), 0.5);
  1214. noise_factor = fclamp(noise_factor, NOISE_FACTOR_MIN, NOISE_FACTOR_MAX);
  1215. inactive_zone = fclamp(inactive_zone, 0.0, 1.0);
  1216. if (target_rate <= 0) {
  1217. return rc->worst_quality; // Highest value allowed
  1218. } else {
  1219. const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
  1220. ? cpi->initial_mbs
  1221. : cpi->common.MBs;
  1222. const int active_mbs = VPXMAX(1, num_mbs - (int)(num_mbs * inactive_zone));
  1223. const double av_err_per_mb = section_err / active_mbs;
  1224. const double speed_term = 1.0 + 0.04 * oxcf->speed;
  1225. double last_group_rate_err;
  1226. const int target_norm_bits_per_mb =
  1227. (int)(((uint64_t)target_rate << BPER_MB_NORMBITS) / active_mbs);
  1228. int q;
  1229. int is_svc_upper_layer = 0;
  1230. if (is_two_pass_svc(cpi) && cpi->svc.spatial_layer_id > 0)
  1231. is_svc_upper_layer = 1;
  1232. // based on recent history adjust expectations of bits per macroblock.
  1233. last_group_rate_err =
  1234. (double)twopass->rolling_arf_group_actual_bits /
  1235. DOUBLE_DIVIDE_CHECK((double)twopass->rolling_arf_group_target_bits);
  1236. last_group_rate_err = VPXMAX(0.25, VPXMIN(4.0, last_group_rate_err));
  1237. twopass->bpm_factor *= (3.0 + last_group_rate_err) / 4.0;
  1238. twopass->bpm_factor = VPXMAX(0.25, VPXMIN(4.0, twopass->bpm_factor));
  1239. // Try and pick a max Q that will be high enough to encode the
  1240. // content at the given rate.
  1241. for (q = rc->best_quality; q < rc->worst_quality; ++q) {
  1242. const double factor = calc_correction_factor(
  1243. av_err_per_mb, ERR_DIVISOR,
  1244. is_svc_upper_layer ? SVC_FACTOR_PT_LOW : FACTOR_PT_LOW,
  1245. FACTOR_PT_HIGH, q, cpi->common.bit_depth);
  1246. const int bits_per_mb = vp9_rc_bits_per_mb(
  1247. INTER_FRAME, q,
  1248. factor * speed_term * cpi->twopass.bpm_factor * noise_factor,
  1249. cpi->common.bit_depth);
  1250. if (bits_per_mb <= target_norm_bits_per_mb) break;
  1251. }
  1252. // Restriction on active max q for constrained quality mode.
  1253. if (cpi->oxcf.rc_mode == VPX_CQ) q = VPXMAX(q, oxcf->cq_level);
  1254. return q;
  1255. }
  1256. }
  1257. static void setup_rf_level_maxq(VP9_COMP *cpi) {
  1258. int i;
  1259. RATE_CONTROL *const rc = &cpi->rc;
  1260. for (i = INTER_NORMAL; i < RATE_FACTOR_LEVELS; ++i) {
  1261. int qdelta = vp9_frame_type_qdelta(cpi, i, rc->worst_quality);
  1262. rc->rf_level_maxq[i] = VPXMAX(rc->worst_quality + qdelta, rc->best_quality);
  1263. }
  1264. }
  1265. static void init_subsampling(VP9_COMP *cpi) {
  1266. const VP9_COMMON *const cm = &cpi->common;
  1267. RATE_CONTROL *const rc = &cpi->rc;
  1268. const int w = cm->width;
  1269. const int h = cm->height;
  1270. int i;
  1271. for (i = 0; i < FRAME_SCALE_STEPS; ++i) {
  1272. // Note: Frames with odd-sized dimensions may result from this scaling.
  1273. rc->frame_width[i] = (w * 16) / frame_scale_factor[i];
  1274. rc->frame_height[i] = (h * 16) / frame_scale_factor[i];
  1275. }
  1276. setup_rf_level_maxq(cpi);
  1277. }
  1278. void calculate_coded_size(VP9_COMP *cpi, int *scaled_frame_width,
  1279. int *scaled_frame_height) {
  1280. RATE_CONTROL *const rc = &cpi->rc;
  1281. *scaled_frame_width = rc->frame_width[rc->frame_size_selector];
  1282. *scaled_frame_height = rc->frame_height[rc->frame_size_selector];
  1283. }
  1284. void vp9_init_second_pass(VP9_COMP *cpi) {
  1285. SVC *const svc = &cpi->svc;
  1286. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1287. const int is_two_pass_svc =
  1288. (svc->number_spatial_layers > 1) || (svc->number_temporal_layers > 1);
  1289. RATE_CONTROL *const rc = &cpi->rc;
  1290. TWO_PASS *const twopass =
  1291. is_two_pass_svc ? &svc->layer_context[svc->spatial_layer_id].twopass
  1292. : &cpi->twopass;
  1293. double frame_rate;
  1294. FIRSTPASS_STATS *stats;
  1295. zero_stats(&twopass->total_stats);
  1296. zero_stats(&twopass->total_left_stats);
  1297. if (!twopass->stats_in_end) return;
  1298. stats = &twopass->total_stats;
  1299. *stats = *twopass->stats_in_end;
  1300. twopass->total_left_stats = *stats;
  1301. frame_rate = 10000000.0 * stats->count / stats->duration;
  1302. // Each frame can have a different duration, as the frame rate in the source
  1303. // isn't guaranteed to be constant. The frame rate prior to the first frame
  1304. // encoded in the second pass is a guess. However, the sum duration is not.
  1305. // It is calculated based on the actual durations of all frames from the
  1306. // first pass.
  1307. if (is_two_pass_svc) {
  1308. vp9_update_spatial_layer_framerate(cpi, frame_rate);
  1309. twopass->bits_left =
  1310. (int64_t)(stats->duration *
  1311. svc->layer_context[svc->spatial_layer_id].target_bandwidth /
  1312. 10000000.0);
  1313. } else {
  1314. vp9_new_framerate(cpi, frame_rate);
  1315. twopass->bits_left =
  1316. (int64_t)(stats->duration * oxcf->target_bandwidth / 10000000.0);
  1317. }
  1318. // This variable monitors how far behind the second ref update is lagging.
  1319. twopass->sr_update_lag = 1;
  1320. // Scan the first pass file and calculate a modified total error based upon
  1321. // the bias/power function used to allocate bits.
  1322. {
  1323. const double avg_error =
  1324. stats->coded_error / DOUBLE_DIVIDE_CHECK(stats->count);
  1325. const FIRSTPASS_STATS *s = twopass->stats_in;
  1326. double modified_error_total = 0.0;
  1327. twopass->modified_error_min =
  1328. (avg_error * oxcf->two_pass_vbrmin_section) / 100;
  1329. twopass->modified_error_max =
  1330. (avg_error * oxcf->two_pass_vbrmax_section) / 100;
  1331. while (s < twopass->stats_in_end) {
  1332. modified_error_total += calculate_modified_err(cpi, twopass, oxcf, s);
  1333. ++s;
  1334. }
  1335. twopass->modified_error_left = modified_error_total;
  1336. }
  1337. // Reset the vbr bits off target counters
  1338. rc->vbr_bits_off_target = 0;
  1339. rc->vbr_bits_off_target_fast = 0;
  1340. rc->rate_error_estimate = 0;
  1341. // Static sequence monitor variables.
  1342. twopass->kf_zeromotion_pct = 100;
  1343. twopass->last_kfgroup_zeromotion_pct = 100;
  1344. // Initialize bits per macro_block estimate correction factor.
  1345. twopass->bpm_factor = 1.0;
  1346. // Initialize actual and target bits counters for ARF groups so that
  1347. // at the start we have a neutral bpm adjustment.
  1348. twopass->rolling_arf_group_target_bits = 1;
  1349. twopass->rolling_arf_group_actual_bits = 1;
  1350. if (oxcf->resize_mode != RESIZE_NONE) {
  1351. init_subsampling(cpi);
  1352. }
  1353. // Initialize the arnr strangth adjustment to 0
  1354. twopass->arnr_strength_adjustment = 0;
  1355. }
  1356. #define SR_DIFF_PART 0.0015
  1357. #define INTRA_PART 0.005
  1358. #define DEFAULT_DECAY_LIMIT 0.75
  1359. #define LOW_SR_DIFF_TRHESH 0.1
  1360. #define SR_DIFF_MAX 128.0
  1361. #define LOW_CODED_ERR_PER_MB 10.0
  1362. #define NCOUNT_FRAME_II_THRESH 6.0
  1363. static double get_sr_decay_rate(const VP9_COMP *cpi,
  1364. const FIRSTPASS_STATS *frame) {
  1365. const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
  1366. : cpi->common.MBs;
  1367. double sr_diff = (frame->sr_coded_error - frame->coded_error) / num_mbs;
  1368. double sr_decay = 1.0;
  1369. double modified_pct_inter;
  1370. double modified_pcnt_intra;
  1371. const double motion_amplitude_part =
  1372. frame->pcnt_motion * ((frame->mvc_abs + frame->mvr_abs) /
  1373. (cpi->initial_height + cpi->initial_width));
  1374. modified_pct_inter = frame->pcnt_inter;
  1375. if (((frame->coded_error / num_mbs) > LOW_CODED_ERR_PER_MB) &&
  1376. ((frame->intra_error / DOUBLE_DIVIDE_CHECK(frame->coded_error)) <
  1377. (double)NCOUNT_FRAME_II_THRESH)) {
  1378. modified_pct_inter = frame->pcnt_inter - frame->pcnt_neutral;
  1379. }
  1380. modified_pcnt_intra = 100 * (1.0 - modified_pct_inter);
  1381. if ((sr_diff > LOW_SR_DIFF_TRHESH)) {
  1382. sr_diff = VPXMIN(sr_diff, SR_DIFF_MAX);
  1383. sr_decay = 1.0 - (SR_DIFF_PART * sr_diff) - motion_amplitude_part -
  1384. (INTRA_PART * modified_pcnt_intra);
  1385. }
  1386. return VPXMAX(sr_decay, VPXMIN(DEFAULT_DECAY_LIMIT, modified_pct_inter));
  1387. }
  1388. // This function gives an estimate of how badly we believe the prediction
  1389. // quality is decaying from frame to frame.
  1390. static double get_zero_motion_factor(const VP9_COMP *cpi,
  1391. const FIRSTPASS_STATS *frame) {
  1392. const double zero_motion_pct = frame->pcnt_inter - frame->pcnt_motion;
  1393. double sr_decay = get_sr_decay_rate(cpi, frame);
  1394. return VPXMIN(sr_decay, zero_motion_pct);
  1395. }
  1396. #define ZM_POWER_FACTOR 0.75
  1397. static double get_prediction_decay_rate(const VP9_COMP *cpi,
  1398. const FIRSTPASS_STATS *next_frame) {
  1399. const double sr_decay_rate = get_sr_decay_rate(cpi, next_frame);
  1400. const double zero_motion_factor =
  1401. (0.95 * pow((next_frame->pcnt_inter - next_frame->pcnt_motion),
  1402. ZM_POWER_FACTOR));
  1403. return VPXMAX(zero_motion_factor,
  1404. (sr_decay_rate + ((1.0 - sr_decay_rate) * zero_motion_factor)));
  1405. }
  1406. // Function to test for a condition where a complex transition is followed
  1407. // by a static section. For example in slide shows where there is a fade
  1408. // between slides. This is to help with more optimal kf and gf positioning.
  1409. static int detect_transition_to_still(VP9_COMP *cpi, int frame_interval,
  1410. int still_interval,
  1411. double loop_decay_rate,
  1412. double last_decay_rate) {
  1413. TWO_PASS *const twopass = &cpi->twopass;
  1414. RATE_CONTROL *const rc = &cpi->rc;
  1415. // Break clause to detect very still sections after motion
  1416. // For example a static image after a fade or other transition
  1417. // instead of a clean scene cut.
  1418. if (frame_interval > rc->min_gf_interval && loop_decay_rate >= 0.999 &&
  1419. last_decay_rate < 0.9) {
  1420. int j;
  1421. // Look ahead a few frames to see if static condition persists...
  1422. for (j = 0; j < still_interval; ++j) {
  1423. const FIRSTPASS_STATS *stats = &twopass->stats_in[j];
  1424. if (stats >= twopass->stats_in_end) break;
  1425. if (stats->pcnt_inter - stats->pcnt_motion < 0.999) break;
  1426. }
  1427. // Only if it does do we signal a transition to still.
  1428. return j == still_interval;
  1429. }
  1430. return 0;
  1431. }
  1432. // This function detects a flash through the high relative pcnt_second_ref
  1433. // score in the frame following a flash frame. The offset passed in should
  1434. // reflect this.
  1435. static int detect_flash(const TWO_PASS *twopass, int offset) {
  1436. const FIRSTPASS_STATS *const next_frame = read_frame_stats(twopass, offset);
  1437. // What we are looking for here is a situation where there is a
  1438. // brief break in prediction (such as a flash) but subsequent frames
  1439. // are reasonably well predicted by an earlier (pre flash) frame.
  1440. // The recovery after a flash is indicated by a high pcnt_second_ref
  1441. // compared to pcnt_inter.
  1442. return next_frame != NULL &&
  1443. next_frame->pcnt_second_ref > next_frame->pcnt_inter &&
  1444. next_frame->pcnt_second_ref >= 0.5;
  1445. }
  1446. // Update the motion related elements to the GF arf boost calculation.
  1447. static void accumulate_frame_motion_stats(const FIRSTPASS_STATS *stats,
  1448. double *mv_in_out,
  1449. double *mv_in_out_accumulator,
  1450. double *abs_mv_in_out_accumulator,
  1451. double *mv_ratio_accumulator) {
  1452. const double pct = stats->pcnt_motion;
  1453. // Accumulate Motion In/Out of frame stats.
  1454. *mv_in_out = stats->mv_in_out_count * pct;
  1455. *mv_in_out_accumulator += *mv_in_out;
  1456. *abs_mv_in_out_accumulator += fabs(*mv_in_out);
  1457. // Accumulate a measure of how uniform (or conversely how random) the motion
  1458. // field is (a ratio of abs(mv) / mv).
  1459. if (pct > 0.05) {
  1460. const double mvr_ratio =
  1461. fabs(stats->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVr));
  1462. const double mvc_ratio =
  1463. fabs(stats->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(stats->MVc));
  1464. *mv_ratio_accumulator +=
  1465. pct * (mvr_ratio < stats->mvr_abs ? mvr_ratio : stats->mvr_abs);
  1466. *mv_ratio_accumulator +=
  1467. pct * (mvc_ratio < stats->mvc_abs ? mvc_ratio : stats->mvc_abs);
  1468. }
  1469. }
  1470. #define BASELINE_ERR_PER_MB 1000.0
  1471. static double calc_frame_boost(VP9_COMP *cpi, const FIRSTPASS_STATS *this_frame,
  1472. double this_frame_mv_in_out, double max_boost) {
  1473. double frame_boost;
  1474. const double lq = vp9_convert_qindex_to_q(
  1475. cpi->rc.avg_frame_qindex[INTER_FRAME], cpi->common.bit_depth);
  1476. const double boost_q_correction = VPXMIN((0.5 + (lq * 0.015)), 1.5);
  1477. int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE) ? cpi->initial_mbs
  1478. : cpi->common.MBs;
  1479. // Correct for any inactive region in the image
  1480. num_mbs = (int)VPXMAX(1, num_mbs * calculate_active_area(cpi, this_frame));
  1481. // Underlying boost factor is based on inter error ratio.
  1482. frame_boost = (BASELINE_ERR_PER_MB * num_mbs) /
  1483. DOUBLE_DIVIDE_CHECK(this_frame->coded_error);
  1484. frame_boost = frame_boost * BOOST_FACTOR * boost_q_correction;
  1485. // Increase boost for frames where new data coming into frame (e.g. zoom out).
  1486. // Slightly reduce boost if there is a net balance of motion out of the frame
  1487. // (zoom in). The range for this_frame_mv_in_out is -1.0 to +1.0.
  1488. if (this_frame_mv_in_out > 0.0)
  1489. frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
  1490. // In the extreme case the boost is halved.
  1491. else
  1492. frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
  1493. return VPXMIN(frame_boost, max_boost * boost_q_correction);
  1494. }
  1495. static int calc_arf_boost(VP9_COMP *cpi, int offset, int f_frames, int b_frames,
  1496. int *f_boost, int *b_boost) {
  1497. TWO_PASS *const twopass = &cpi->twopass;
  1498. int i;
  1499. double boost_score = 0.0;
  1500. double mv_ratio_accumulator = 0.0;
  1501. double decay_accumulator = 1.0;
  1502. double this_frame_mv_in_out = 0.0;
  1503. double mv_in_out_accumulator = 0.0;
  1504. double abs_mv_in_out_accumulator = 0.0;
  1505. int arf_boost;
  1506. int flash_detected = 0;
  1507. // Search forward from the proposed arf/next gf position.
  1508. for (i = 0; i < f_frames; ++i) {
  1509. const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
  1510. if (this_frame == NULL) break;
  1511. // Update the motion related elements to the boost calculation.
  1512. accumulate_frame_motion_stats(
  1513. this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1514. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1515. // We want to discount the flash frame itself and the recovery
  1516. // frame that follows as both will have poor scores.
  1517. flash_detected = detect_flash(twopass, i + offset) ||
  1518. detect_flash(twopass, i + offset + 1);
  1519. // Accumulate the effect of prediction quality decay.
  1520. if (!flash_detected) {
  1521. decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
  1522. decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
  1523. ? MIN_DECAY_FACTOR
  1524. : decay_accumulator;
  1525. }
  1526. boost_score +=
  1527. decay_accumulator *
  1528. calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
  1529. }
  1530. *f_boost = (int)boost_score;
  1531. // Reset for backward looking loop.
  1532. boost_score = 0.0;
  1533. mv_ratio_accumulator = 0.0;
  1534. decay_accumulator = 1.0;
  1535. this_frame_mv_in_out = 0.0;
  1536. mv_in_out_accumulator = 0.0;
  1537. abs_mv_in_out_accumulator = 0.0;
  1538. // Search backward towards last gf position.
  1539. for (i = -1; i >= -b_frames; --i) {
  1540. const FIRSTPASS_STATS *this_frame = read_frame_stats(twopass, i + offset);
  1541. if (this_frame == NULL) break;
  1542. // Update the motion related elements to the boost calculation.
  1543. accumulate_frame_motion_stats(
  1544. this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1545. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1546. // We want to discount the the flash frame itself and the recovery
  1547. // frame that follows as both will have poor scores.
  1548. flash_detected = detect_flash(twopass, i + offset) ||
  1549. detect_flash(twopass, i + offset + 1);
  1550. // Cumulative effect of prediction quality decay.
  1551. if (!flash_detected) {
  1552. decay_accumulator *= get_prediction_decay_rate(cpi, this_frame);
  1553. decay_accumulator = decay_accumulator < MIN_DECAY_FACTOR
  1554. ? MIN_DECAY_FACTOR
  1555. : decay_accumulator;
  1556. }
  1557. boost_score +=
  1558. decay_accumulator *
  1559. calc_frame_boost(cpi, this_frame, this_frame_mv_in_out, GF_MAX_BOOST);
  1560. }
  1561. *b_boost = (int)boost_score;
  1562. arf_boost = (*f_boost + *b_boost);
  1563. if (arf_boost < ((b_frames + f_frames) * 20))
  1564. arf_boost = ((b_frames + f_frames) * 20);
  1565. arf_boost = VPXMAX(arf_boost, MIN_ARF_GF_BOOST);
  1566. return arf_boost;
  1567. }
  1568. // Calculate a section intra ratio used in setting max loop filter.
  1569. static int calculate_section_intra_ratio(const FIRSTPASS_STATS *begin,
  1570. const FIRSTPASS_STATS *end,
  1571. int section_length) {
  1572. const FIRSTPASS_STATS *s = begin;
  1573. double intra_error = 0.0;
  1574. double coded_error = 0.0;
  1575. int i = 0;
  1576. while (s < end && i < section_length) {
  1577. intra_error += s->intra_error;
  1578. coded_error += s->coded_error;
  1579. ++s;
  1580. ++i;
  1581. }
  1582. return (int)(intra_error / DOUBLE_DIVIDE_CHECK(coded_error));
  1583. }
  1584. // Calculate the total bits to allocate in this GF/ARF group.
  1585. static int64_t calculate_total_gf_group_bits(VP9_COMP *cpi,
  1586. double gf_group_err) {
  1587. const RATE_CONTROL *const rc = &cpi->rc;
  1588. const TWO_PASS *const twopass = &cpi->twopass;
  1589. const int max_bits = frame_max_bits(rc, &cpi->oxcf);
  1590. int64_t total_group_bits;
  1591. // Calculate the bits to be allocated to the group as a whole.
  1592. if ((twopass->kf_group_bits > 0) && (twopass->kf_group_error_left > 0)) {
  1593. total_group_bits = (int64_t)(twopass->kf_group_bits *
  1594. (gf_group_err / twopass->kf_group_error_left));
  1595. } else {
  1596. total_group_bits = 0;
  1597. }
  1598. // Clamp odd edge cases.
  1599. total_group_bits =
  1600. (total_group_bits < 0) ? 0 : (total_group_bits > twopass->kf_group_bits)
  1601. ? twopass->kf_group_bits
  1602. : total_group_bits;
  1603. // Clip based on user supplied data rate variability limit.
  1604. if (total_group_bits > (int64_t)max_bits * rc->baseline_gf_interval)
  1605. total_group_bits = (int64_t)max_bits * rc->baseline_gf_interval;
  1606. return total_group_bits;
  1607. }
  1608. // Calculate the number bits extra to assign to boosted frames in a group.
  1609. static int calculate_boost_bits(int frame_count, int boost,
  1610. int64_t total_group_bits) {
  1611. int allocation_chunks;
  1612. // return 0 for invalid inputs (could arise e.g. through rounding errors)
  1613. if (!boost || (total_group_bits <= 0) || (frame_count <= 0)) return 0;
  1614. allocation_chunks = (frame_count * 100) + boost;
  1615. // Prevent overflow.
  1616. if (boost > 1023) {
  1617. int divisor = boost >> 10;
  1618. boost /= divisor;
  1619. allocation_chunks /= divisor;
  1620. }
  1621. // Calculate the number of extra bits for use in the boosted frame or frames.
  1622. return VPXMAX((int)(((int64_t)boost * total_group_bits) / allocation_chunks),
  1623. 0);
  1624. }
  1625. // Current limit on maximum number of active arfs in a GF/ARF group.
  1626. #define MAX_ACTIVE_ARFS 2
  1627. #define ARF_SLOT1 2
  1628. #define ARF_SLOT2 3
  1629. // This function indirects the choice of buffers for arfs.
  1630. // At the moment the values are fixed but this may change as part of
  1631. // the integration process with other codec features that swap buffers around.
  1632. static void get_arf_buffer_indices(unsigned char *arf_buffer_indices) {
  1633. arf_buffer_indices[0] = ARF_SLOT1;
  1634. arf_buffer_indices[1] = ARF_SLOT2;
  1635. }
  1636. static void allocate_gf_group_bits(VP9_COMP *cpi, int64_t gf_group_bits,
  1637. int gf_arf_bits) {
  1638. RATE_CONTROL *const rc = &cpi->rc;
  1639. TWO_PASS *const twopass = &cpi->twopass;
  1640. GF_GROUP *const gf_group = &twopass->gf_group;
  1641. FIRSTPASS_STATS frame_stats;
  1642. int i;
  1643. int frame_index = 1;
  1644. int target_frame_size;
  1645. int key_frame;
  1646. const int max_bits = frame_max_bits(&cpi->rc, &cpi->oxcf);
  1647. int64_t total_group_bits = gf_group_bits;
  1648. int mid_boost_bits = 0;
  1649. int mid_frame_idx;
  1650. unsigned char arf_buffer_indices[MAX_ACTIVE_ARFS];
  1651. int alt_frame_index = frame_index;
  1652. int has_temporal_layers =
  1653. is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1;
  1654. int normal_frames;
  1655. int normal_frame_bits;
  1656. int last_frame_bits;
  1657. int last_frame_reduction;
  1658. // Only encode alt reference frame in temporal base layer.
  1659. if (has_temporal_layers) alt_frame_index = cpi->svc.number_temporal_layers;
  1660. key_frame =
  1661. cpi->common.frame_type == KEY_FRAME || vp9_is_upper_layer_key_frame(cpi);
  1662. get_arf_buffer_indices(arf_buffer_indices);
  1663. // For key frames the frame target rate is already set and it
  1664. // is also the golden frame.
  1665. if (!key_frame) {
  1666. if (rc->source_alt_ref_active) {
  1667. gf_group->update_type[0] = OVERLAY_UPDATE;
  1668. gf_group->rf_level[0] = INTER_NORMAL;
  1669. gf_group->bit_allocation[0] = 0;
  1670. } else {
  1671. gf_group->update_type[0] = GF_UPDATE;
  1672. gf_group->rf_level[0] = GF_ARF_STD;
  1673. gf_group->bit_allocation[0] = gf_arf_bits;
  1674. }
  1675. gf_group->arf_update_idx[0] = arf_buffer_indices[0];
  1676. gf_group->arf_ref_idx[0] = arf_buffer_indices[0];
  1677. // Step over the golden frame / overlay frame
  1678. if (EOF == input_stats(twopass, &frame_stats)) return;
  1679. }
  1680. // Deduct the boost bits for arf (or gf if it is not a key frame)
  1681. // from the group total.
  1682. if (rc->source_alt_ref_pending || !key_frame) total_group_bits -= gf_arf_bits;
  1683. // Store the bits to spend on the ARF if there is one.
  1684. if (rc->source_alt_ref_pending) {
  1685. gf_group->update_type[alt_frame_index] = ARF_UPDATE;
  1686. gf_group->rf_level[alt_frame_index] = GF_ARF_STD;
  1687. gf_group->bit_allocation[alt_frame_index] = gf_arf_bits;
  1688. if (has_temporal_layers)
  1689. gf_group->arf_src_offset[alt_frame_index] =
  1690. (unsigned char)(rc->baseline_gf_interval -
  1691. cpi->svc.number_temporal_layers);
  1692. else
  1693. gf_group->arf_src_offset[alt_frame_index] =
  1694. (unsigned char)(rc->baseline_gf_interval - 1);
  1695. gf_group->arf_update_idx[alt_frame_index] = arf_buffer_indices[0];
  1696. gf_group->arf_ref_idx[alt_frame_index] =
  1697. arf_buffer_indices[cpi->multi_arf_last_grp_enabled &&
  1698. rc->source_alt_ref_active];
  1699. if (!has_temporal_layers) ++frame_index;
  1700. if (cpi->multi_arf_enabled) {
  1701. // Set aside a slot for a level 1 arf.
  1702. gf_group->update_type[frame_index] = ARF_UPDATE;
  1703. gf_group->rf_level[frame_index] = GF_ARF_LOW;
  1704. gf_group->arf_src_offset[frame_index] =
  1705. (unsigned char)((rc->baseline_gf_interval >> 1) - 1);
  1706. gf_group->arf_update_idx[frame_index] = arf_buffer_indices[1];
  1707. gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
  1708. ++frame_index;
  1709. }
  1710. }
  1711. // Note index of the first normal inter frame int eh group (not gf kf arf)
  1712. gf_group->first_inter_index = frame_index;
  1713. // Define middle frame
  1714. mid_frame_idx = frame_index + (rc->baseline_gf_interval >> 1) - 1;
  1715. normal_frames = (rc->baseline_gf_interval - rc->source_alt_ref_pending);
  1716. // The last frame in the group is used less as a predictor so reduce
  1717. // its allocation a little.
  1718. if (normal_frames > 1) {
  1719. normal_frame_bits = (int)(total_group_bits / normal_frames);
  1720. last_frame_reduction = normal_frame_bits / 16;
  1721. last_frame_bits = normal_frame_bits - last_frame_reduction;
  1722. } else {
  1723. normal_frame_bits = (int)total_group_bits;
  1724. last_frame_bits = normal_frame_bits;
  1725. last_frame_reduction = 0;
  1726. }
  1727. // Allocate bits to the other frames in the group.
  1728. for (i = 0; i < normal_frames; ++i) {
  1729. int arf_idx = 0;
  1730. if (EOF == input_stats(twopass, &frame_stats)) break;
  1731. if (has_temporal_layers && frame_index == alt_frame_index) {
  1732. ++frame_index;
  1733. }
  1734. target_frame_size = (i == (normal_frames - 1))
  1735. ? last_frame_bits
  1736. : (i == mid_frame_idx)
  1737. ? normal_frame_bits + last_frame_reduction
  1738. : normal_frame_bits;
  1739. if (rc->source_alt_ref_pending && cpi->multi_arf_enabled) {
  1740. mid_boost_bits += (target_frame_size >> 4);
  1741. target_frame_size -= (target_frame_size >> 4);
  1742. if (frame_index <= mid_frame_idx) arf_idx = 1;
  1743. }
  1744. gf_group->arf_update_idx[frame_index] = arf_buffer_indices[arf_idx];
  1745. gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[arf_idx];
  1746. target_frame_size =
  1747. clamp(target_frame_size, 0, VPXMIN(max_bits, (int)total_group_bits));
  1748. gf_group->update_type[frame_index] = LF_UPDATE;
  1749. gf_group->rf_level[frame_index] = INTER_NORMAL;
  1750. gf_group->bit_allocation[frame_index] = target_frame_size;
  1751. ++frame_index;
  1752. }
  1753. // Note:
  1754. // We need to configure the frame at the end of the sequence + 1 that will be
  1755. // the start frame for the next group. Otherwise prior to the call to
  1756. // vp9_rc_get_second_pass_params() the data will be undefined.
  1757. gf_group->arf_update_idx[frame_index] = arf_buffer_indices[0];
  1758. gf_group->arf_ref_idx[frame_index] = arf_buffer_indices[0];
  1759. if (rc->source_alt_ref_pending) {
  1760. gf_group->update_type[frame_index] = OVERLAY_UPDATE;
  1761. gf_group->rf_level[frame_index] = INTER_NORMAL;
  1762. // Final setup for second arf and its overlay.
  1763. if (cpi->multi_arf_enabled) {
  1764. gf_group->bit_allocation[2] =
  1765. gf_group->bit_allocation[mid_frame_idx] + mid_boost_bits;
  1766. gf_group->update_type[mid_frame_idx] = OVERLAY_UPDATE;
  1767. gf_group->bit_allocation[mid_frame_idx] = 0;
  1768. }
  1769. } else {
  1770. gf_group->update_type[frame_index] = GF_UPDATE;
  1771. gf_group->rf_level[frame_index] = GF_ARF_STD;
  1772. }
  1773. // Note whether multi-arf was enabled this group for next time.
  1774. cpi->multi_arf_last_grp_enabled = cpi->multi_arf_enabled;
  1775. }
  1776. // Adjusts the ARNF filter for a GF group.
  1777. static void adjust_group_arnr_filter(VP9_COMP *cpi, double section_noise,
  1778. double section_inter,
  1779. double section_motion) {
  1780. TWO_PASS *const twopass = &cpi->twopass;
  1781. double section_zeromv = section_inter - section_motion;
  1782. twopass->arnr_strength_adjustment = 0;
  1783. if ((section_zeromv < 0.10) || (section_noise <= (SECTION_NOISE_DEF * 0.75)))
  1784. twopass->arnr_strength_adjustment -= 1;
  1785. if (section_zeromv > 0.50) twopass->arnr_strength_adjustment += 1;
  1786. }
  1787. // Analyse and define a gf/arf group.
  1788. static void define_gf_group(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
  1789. VP9_COMMON *const cm = &cpi->common;
  1790. RATE_CONTROL *const rc = &cpi->rc;
  1791. VP9EncoderConfig *const oxcf = &cpi->oxcf;
  1792. TWO_PASS *const twopass = &cpi->twopass;
  1793. FIRSTPASS_STATS next_frame;
  1794. const FIRSTPASS_STATS *const start_pos = twopass->stats_in;
  1795. int i;
  1796. double boost_score = 0.0;
  1797. double old_boost_score = 0.0;
  1798. double gf_group_err = 0.0;
  1799. double gf_group_raw_error = 0.0;
  1800. double gf_group_noise = 0.0;
  1801. double gf_group_skip_pct = 0.0;
  1802. double gf_group_inactive_zone_rows = 0.0;
  1803. double gf_group_inter = 0.0;
  1804. double gf_group_motion = 0.0;
  1805. double gf_first_frame_err = 0.0;
  1806. double mod_frame_err = 0.0;
  1807. double mv_ratio_accumulator = 0.0;
  1808. double decay_accumulator = 1.0;
  1809. double zero_motion_accumulator = 1.0;
  1810. double loop_decay_rate = 1.00;
  1811. double last_loop_decay_rate = 1.00;
  1812. double this_frame_mv_in_out = 0.0;
  1813. double mv_in_out_accumulator = 0.0;
  1814. double abs_mv_in_out_accumulator = 0.0;
  1815. double mv_ratio_accumulator_thresh;
  1816. unsigned int allow_alt_ref = is_altref_enabled(cpi);
  1817. int f_boost = 0;
  1818. int b_boost = 0;
  1819. int flash_detected;
  1820. int active_max_gf_interval;
  1821. int active_min_gf_interval;
  1822. int64_t gf_group_bits;
  1823. int gf_arf_bits;
  1824. const int is_key_frame = frame_is_intra_only(cm);
  1825. const int arf_active_or_kf = is_key_frame || rc->source_alt_ref_active;
  1826. // Reset the GF group data structures unless this is a key
  1827. // frame in which case it will already have been done.
  1828. if (is_key_frame == 0) {
  1829. vp9_zero(twopass->gf_group);
  1830. }
  1831. vpx_clear_system_state();
  1832. vp9_zero(next_frame);
  1833. // Load stats for the current frame.
  1834. mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
  1835. // Note the error of the frame at the start of the group. This will be
  1836. // the GF frame error if we code a normal gf.
  1837. gf_first_frame_err = mod_frame_err;
  1838. // If this is a key frame or the overlay from a previous arf then
  1839. // the error score / cost of this frame has already been accounted for.
  1840. if (arf_active_or_kf) {
  1841. gf_group_err -= gf_first_frame_err;
  1842. gf_group_raw_error -= this_frame->coded_error;
  1843. gf_group_noise -= this_frame->frame_noise_energy;
  1844. gf_group_skip_pct -= this_frame->intra_skip_pct;
  1845. gf_group_inactive_zone_rows -= this_frame->inactive_zone_rows;
  1846. gf_group_inter -= this_frame->pcnt_inter;
  1847. gf_group_motion -= this_frame->pcnt_motion;
  1848. }
  1849. // Motion breakout threshold for loop below depends on image size.
  1850. mv_ratio_accumulator_thresh =
  1851. (cpi->initial_height + cpi->initial_width) / 4.0;
  1852. // Set a maximum and minimum interval for the GF group.
  1853. // If the image appears almost completely static we can extend beyond this.
  1854. {
  1855. int int_max_q = (int)(vp9_convert_qindex_to_q(twopass->active_worst_quality,
  1856. cpi->common.bit_depth));
  1857. int int_lbq = (int)(vp9_convert_qindex_to_q(rc->last_boosted_qindex,
  1858. cpi->common.bit_depth));
  1859. active_min_gf_interval =
  1860. rc->min_gf_interval + arf_active_or_kf + VPXMIN(2, int_max_q / 200);
  1861. if (active_min_gf_interval > rc->max_gf_interval)
  1862. active_min_gf_interval = rc->max_gf_interval;
  1863. if (cpi->multi_arf_allowed) {
  1864. active_max_gf_interval = rc->max_gf_interval;
  1865. } else {
  1866. // The value chosen depends on the active Q range. At low Q we have
  1867. // bits to spare and are better with a smaller interval and smaller boost.
  1868. // At high Q when there are few bits to spare we are better with a longer
  1869. // interval to spread the cost of the GF.
  1870. active_max_gf_interval = 12 + arf_active_or_kf + VPXMIN(4, (int_lbq / 6));
  1871. // We have: active_min_gf_interval <= rc->max_gf_interval
  1872. if (active_max_gf_interval < active_min_gf_interval)
  1873. active_max_gf_interval = active_min_gf_interval;
  1874. else if (active_max_gf_interval > rc->max_gf_interval)
  1875. active_max_gf_interval = rc->max_gf_interval;
  1876. // Would the active max drop us out just before the near the next kf?
  1877. if ((active_max_gf_interval <= rc->frames_to_key) &&
  1878. (active_max_gf_interval >= (rc->frames_to_key - rc->min_gf_interval)))
  1879. active_max_gf_interval = rc->frames_to_key / 2;
  1880. }
  1881. }
  1882. i = 0;
  1883. while (i < rc->static_scene_max_gf_interval && i < rc->frames_to_key) {
  1884. ++i;
  1885. // Accumulate error score of frames in this gf group.
  1886. mod_frame_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
  1887. gf_group_err += mod_frame_err;
  1888. gf_group_raw_error += this_frame->coded_error;
  1889. gf_group_noise += this_frame->frame_noise_energy;
  1890. gf_group_skip_pct += this_frame->intra_skip_pct;
  1891. gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
  1892. gf_group_inter += this_frame->pcnt_inter;
  1893. gf_group_motion += this_frame->pcnt_motion;
  1894. if (EOF == input_stats(twopass, &next_frame)) break;
  1895. // Test for the case where there is a brief flash but the prediction
  1896. // quality back to an earlier frame is then restored.
  1897. flash_detected = detect_flash(twopass, 0);
  1898. // Update the motion related elements to the boost calculation.
  1899. accumulate_frame_motion_stats(
  1900. &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1901. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1902. // Accumulate the effect of prediction quality decay.
  1903. if (!flash_detected) {
  1904. last_loop_decay_rate = loop_decay_rate;
  1905. loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
  1906. decay_accumulator = decay_accumulator * loop_decay_rate;
  1907. // Monitor for static sections.
  1908. zero_motion_accumulator = VPXMIN(
  1909. zero_motion_accumulator, get_zero_motion_factor(cpi, &next_frame));
  1910. // Break clause to detect very still sections after motion. For example,
  1911. // a static image after a fade or other transition.
  1912. if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
  1913. last_loop_decay_rate)) {
  1914. allow_alt_ref = 0;
  1915. break;
  1916. }
  1917. }
  1918. // Calculate a boost number for this frame.
  1919. boost_score +=
  1920. decay_accumulator *
  1921. calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out, GF_MAX_BOOST);
  1922. // Break out conditions.
  1923. if (
  1924. // Break at active_max_gf_interval unless almost totally static.
  1925. ((i >= active_max_gf_interval) && (zero_motion_accumulator < 0.995)) ||
  1926. (
  1927. // Don't break out with a very short interval.
  1928. (i >= active_min_gf_interval) &&
  1929. // If possible dont break very close to a kf
  1930. ((rc->frames_to_key - i) >= rc->min_gf_interval) &&
  1931. (!flash_detected) &&
  1932. ((mv_ratio_accumulator > mv_ratio_accumulator_thresh) ||
  1933. (abs_mv_in_out_accumulator > 3.0) ||
  1934. (mv_in_out_accumulator < -2.0) ||
  1935. ((boost_score - old_boost_score) < BOOST_BREAKOUT)))) {
  1936. boost_score = old_boost_score;
  1937. break;
  1938. }
  1939. *this_frame = next_frame;
  1940. old_boost_score = boost_score;
  1941. }
  1942. // Was the group length constrained by the requirement for a new KF?
  1943. rc->constrained_gf_group = (i >= rc->frames_to_key) ? 1 : 0;
  1944. // Should we use the alternate reference frame.
  1945. if (allow_alt_ref && (i < cpi->oxcf.lag_in_frames) &&
  1946. (i >= rc->min_gf_interval)) {
  1947. // Calculate the boost for alt ref.
  1948. rc->gfu_boost =
  1949. calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost, &b_boost);
  1950. rc->source_alt_ref_pending = 1;
  1951. // Test to see if multi arf is appropriate.
  1952. cpi->multi_arf_enabled =
  1953. (cpi->multi_arf_allowed && (rc->baseline_gf_interval >= 6) &&
  1954. (zero_motion_accumulator < 0.995))
  1955. ? 1
  1956. : 0;
  1957. } else {
  1958. rc->gfu_boost = VPXMAX((int)boost_score, MIN_ARF_GF_BOOST);
  1959. rc->source_alt_ref_pending = 0;
  1960. }
  1961. // Set the interval until the next gf.
  1962. rc->baseline_gf_interval = i - (is_key_frame || rc->source_alt_ref_pending);
  1963. // Only encode alt reference frame in temporal base layer. So
  1964. // baseline_gf_interval should be multiple of a temporal layer group
  1965. // (typically the frame distance between two base layer frames)
  1966. if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
  1967. int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
  1968. int new_gf_interval = (rc->baseline_gf_interval + count) & (~count);
  1969. int j;
  1970. for (j = 0; j < new_gf_interval - rc->baseline_gf_interval; ++j) {
  1971. if (EOF == input_stats(twopass, this_frame)) break;
  1972. gf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
  1973. gf_group_raw_error += this_frame->coded_error;
  1974. gf_group_noise += this_frame->frame_noise_energy;
  1975. gf_group_skip_pct += this_frame->intra_skip_pct;
  1976. gf_group_inactive_zone_rows += this_frame->inactive_zone_rows;
  1977. gf_group_inter += this_frame->pcnt_inter;
  1978. gf_group_motion += this_frame->pcnt_motion;
  1979. }
  1980. rc->baseline_gf_interval = new_gf_interval;
  1981. }
  1982. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  1983. // Reset the file position.
  1984. reset_fpf_position(twopass, start_pos);
  1985. // Calculate the bits to be allocated to the gf/arf group as a whole
  1986. gf_group_bits = calculate_total_gf_group_bits(cpi, gf_group_err);
  1987. // Calculate an estimate of the maxq needed for the group.
  1988. // We are more agressive about correcting for sections
  1989. // where there could be significant overshoot than for easier
  1990. // sections where we do not wish to risk creating an overshoot
  1991. // of the allocated bit budget.
  1992. if ((cpi->oxcf.rc_mode != VPX_Q) && (rc->baseline_gf_interval > 1)) {
  1993. const int vbr_group_bits_per_frame =
  1994. (int)(gf_group_bits / rc->baseline_gf_interval);
  1995. const double group_av_err = gf_group_raw_error / rc->baseline_gf_interval;
  1996. const double group_av_noise = gf_group_noise / rc->baseline_gf_interval;
  1997. const double group_av_skip_pct =
  1998. gf_group_skip_pct / rc->baseline_gf_interval;
  1999. const double group_av_inactive_zone =
  2000. ((gf_group_inactive_zone_rows * 2) /
  2001. (rc->baseline_gf_interval * (double)cm->mb_rows));
  2002. int tmp_q = get_twopass_worst_quality(
  2003. cpi, group_av_err, (group_av_skip_pct + group_av_inactive_zone),
  2004. group_av_noise, vbr_group_bits_per_frame);
  2005. twopass->active_worst_quality =
  2006. (tmp_q + (twopass->active_worst_quality * 3)) >> 2;
  2007. }
  2008. // Context Adjustment of ARNR filter strength
  2009. if (rc->baseline_gf_interval > 1) {
  2010. adjust_group_arnr_filter(cpi, (gf_group_noise / rc->baseline_gf_interval),
  2011. (gf_group_inter / rc->baseline_gf_interval),
  2012. (gf_group_motion / rc->baseline_gf_interval));
  2013. } else {
  2014. twopass->arnr_strength_adjustment = 0;
  2015. }
  2016. // Calculate the extra bits to be used for boosted frame(s)
  2017. gf_arf_bits = calculate_boost_bits(rc->baseline_gf_interval, rc->gfu_boost,
  2018. gf_group_bits);
  2019. // Adjust KF group bits and error remaining.
  2020. twopass->kf_group_error_left -= (int64_t)gf_group_err;
  2021. // Allocate bits to each of the frames in the GF group.
  2022. allocate_gf_group_bits(cpi, gf_group_bits, gf_arf_bits);
  2023. // Reset the file position.
  2024. reset_fpf_position(twopass, start_pos);
  2025. // Calculate a section intra ratio used in setting max loop filter.
  2026. if (cpi->common.frame_type != KEY_FRAME) {
  2027. twopass->section_intra_rating = calculate_section_intra_ratio(
  2028. start_pos, twopass->stats_in_end, rc->baseline_gf_interval);
  2029. }
  2030. if (oxcf->resize_mode == RESIZE_DYNAMIC) {
  2031. // Default to starting GF groups at normal frame size.
  2032. cpi->rc.next_frame_size_selector = UNSCALED;
  2033. }
  2034. // Reset rolling actual and target bits counters for ARF groups.
  2035. twopass->rolling_arf_group_target_bits = 0;
  2036. twopass->rolling_arf_group_actual_bits = 0;
  2037. }
  2038. // Threshold for use of the lagging second reference frame. High second ref
  2039. // usage may point to a transient event like a flash or occlusion rather than
  2040. // a real scene cut.
  2041. #define SECOND_REF_USEAGE_THRESH 0.1
  2042. // Minimum % intra coding observed in first pass (1.0 = 100%)
  2043. #define MIN_INTRA_LEVEL 0.25
  2044. // Minimum ratio between the % of intra coding and inter coding in the first
  2045. // pass after discounting neutral blocks (discounting neutral blocks in this
  2046. // way helps catch scene cuts in clips with very flat areas or letter box
  2047. // format clips with image padding.
  2048. #define INTRA_VS_INTER_THRESH 2.0
  2049. // Hard threshold where the first pass chooses intra for almost all blocks.
  2050. // In such a case even if the frame is not a scene cut coding a key frame
  2051. // may be a good option.
  2052. #define VERY_LOW_INTER_THRESH 0.05
  2053. // Maximum threshold for the relative ratio of intra error score vs best
  2054. // inter error score.
  2055. #define KF_II_ERR_THRESHOLD 2.5
  2056. // In real scene cuts there is almost always a sharp change in the intra
  2057. // or inter error score.
  2058. #define ERR_CHANGE_THRESHOLD 0.4
  2059. // For real scene cuts we expect an improvment in the intra inter error
  2060. // ratio in the next frame.
  2061. #define II_IMPROVEMENT_THRESHOLD 3.5
  2062. #define KF_II_MAX 128.0
  2063. static int test_candidate_kf(TWO_PASS *twopass,
  2064. const FIRSTPASS_STATS *last_frame,
  2065. const FIRSTPASS_STATS *this_frame,
  2066. const FIRSTPASS_STATS *next_frame) {
  2067. int is_viable_kf = 0;
  2068. double pcnt_intra = 1.0 - this_frame->pcnt_inter;
  2069. double modified_pcnt_inter =
  2070. this_frame->pcnt_inter - this_frame->pcnt_neutral;
  2071. // Does the frame satisfy the primary criteria of a key frame?
  2072. // See above for an explanation of the test criteria.
  2073. // If so, then examine how well it predicts subsequent frames.
  2074. if ((this_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
  2075. (next_frame->pcnt_second_ref < SECOND_REF_USEAGE_THRESH) &&
  2076. ((this_frame->pcnt_inter < VERY_LOW_INTER_THRESH) ||
  2077. ((pcnt_intra > MIN_INTRA_LEVEL) &&
  2078. (pcnt_intra > (INTRA_VS_INTER_THRESH * modified_pcnt_inter)) &&
  2079. ((this_frame->intra_error /
  2080. DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) <
  2081. KF_II_ERR_THRESHOLD) &&
  2082. ((fabs(last_frame->coded_error - this_frame->coded_error) /
  2083. DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
  2084. ERR_CHANGE_THRESHOLD) ||
  2085. (fabs(last_frame->intra_error - this_frame->intra_error) /
  2086. DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
  2087. ERR_CHANGE_THRESHOLD) ||
  2088. ((next_frame->intra_error /
  2089. DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) >
  2090. II_IMPROVEMENT_THRESHOLD))))) {
  2091. int i;
  2092. const FIRSTPASS_STATS *start_pos = twopass->stats_in;
  2093. FIRSTPASS_STATS local_next_frame = *next_frame;
  2094. double boost_score = 0.0;
  2095. double old_boost_score = 0.0;
  2096. double decay_accumulator = 1.0;
  2097. // Examine how well the key frame predicts subsequent frames.
  2098. for (i = 0; i < 16; ++i) {
  2099. double next_iiratio = (BOOST_FACTOR * local_next_frame.intra_error /
  2100. DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
  2101. if (next_iiratio > KF_II_MAX) next_iiratio = KF_II_MAX;
  2102. // Cumulative effect of decay in prediction quality.
  2103. if (local_next_frame.pcnt_inter > 0.85)
  2104. decay_accumulator *= local_next_frame.pcnt_inter;
  2105. else
  2106. decay_accumulator *= (0.85 + local_next_frame.pcnt_inter) / 2.0;
  2107. // Keep a running total.
  2108. boost_score += (decay_accumulator * next_iiratio);
  2109. // Test various breakout clauses.
  2110. if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
  2111. (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
  2112. 0.20) &&
  2113. (next_iiratio < 3.0)) ||
  2114. ((boost_score - old_boost_score) < 3.0) ||
  2115. (local_next_frame.intra_error < 200)) {
  2116. break;
  2117. }
  2118. old_boost_score = boost_score;
  2119. // Get the next frame details
  2120. if (EOF == input_stats(twopass, &local_next_frame)) break;
  2121. }
  2122. // If there is tolerable prediction for at least the next 3 frames then
  2123. // break out else discard this potential key frame and move on
  2124. if (boost_score > 30.0 && (i > 3)) {
  2125. is_viable_kf = 1;
  2126. } else {
  2127. // Reset the file position
  2128. reset_fpf_position(twopass, start_pos);
  2129. is_viable_kf = 0;
  2130. }
  2131. }
  2132. return is_viable_kf;
  2133. }
  2134. #define FRAMES_TO_CHECK_DECAY 8
  2135. static void find_next_key_frame(VP9_COMP *cpi, FIRSTPASS_STATS *this_frame) {
  2136. int i, j;
  2137. RATE_CONTROL *const rc = &cpi->rc;
  2138. TWO_PASS *const twopass = &cpi->twopass;
  2139. GF_GROUP *const gf_group = &twopass->gf_group;
  2140. const VP9EncoderConfig *const oxcf = &cpi->oxcf;
  2141. const FIRSTPASS_STATS first_frame = *this_frame;
  2142. const FIRSTPASS_STATS *const start_position = twopass->stats_in;
  2143. FIRSTPASS_STATS next_frame;
  2144. FIRSTPASS_STATS last_frame;
  2145. int kf_bits = 0;
  2146. int loop_decay_counter = 0;
  2147. double decay_accumulator = 1.0;
  2148. double av_decay_accumulator = 0.0;
  2149. double zero_motion_accumulator = 1.0;
  2150. double boost_score = 0.0;
  2151. double kf_mod_err = 0.0;
  2152. double kf_group_err = 0.0;
  2153. double recent_loop_decay[FRAMES_TO_CHECK_DECAY];
  2154. vp9_zero(next_frame);
  2155. cpi->common.frame_type = KEY_FRAME;
  2156. // Reset the GF group data structures.
  2157. vp9_zero(*gf_group);
  2158. // Is this a forced key frame by interval.
  2159. rc->this_key_frame_forced = rc->next_key_frame_forced;
  2160. // Clear the alt ref active flag and last group multi arf flags as they
  2161. // can never be set for a key frame.
  2162. rc->source_alt_ref_active = 0;
  2163. cpi->multi_arf_last_grp_enabled = 0;
  2164. // KF is always a GF so clear frames till next gf counter.
  2165. rc->frames_till_gf_update_due = 0;
  2166. rc->frames_to_key = 1;
  2167. twopass->kf_group_bits = 0; // Total bits available to kf group
  2168. twopass->kf_group_error_left = 0; // Group modified error score.
  2169. kf_mod_err = calculate_modified_err(cpi, twopass, oxcf, this_frame);
  2170. // Initialize the decay rates for the recent frames to check
  2171. for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j) recent_loop_decay[j] = 1.0;
  2172. // Find the next keyframe.
  2173. i = 0;
  2174. while (twopass->stats_in < twopass->stats_in_end &&
  2175. rc->frames_to_key < cpi->oxcf.key_freq) {
  2176. // Accumulate kf group error.
  2177. kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
  2178. // Load the next frame's stats.
  2179. last_frame = *this_frame;
  2180. input_stats(twopass, this_frame);
  2181. // Provided that we are not at the end of the file...
  2182. if (cpi->oxcf.auto_key && twopass->stats_in < twopass->stats_in_end) {
  2183. double loop_decay_rate;
  2184. // Check for a scene cut.
  2185. if (test_candidate_kf(twopass, &last_frame, this_frame,
  2186. twopass->stats_in))
  2187. break;
  2188. // How fast is the prediction quality decaying?
  2189. loop_decay_rate = get_prediction_decay_rate(cpi, twopass->stats_in);
  2190. // We want to know something about the recent past... rather than
  2191. // as used elsewhere where we are concerned with decay in prediction
  2192. // quality since the last GF or KF.
  2193. recent_loop_decay[i % FRAMES_TO_CHECK_DECAY] = loop_decay_rate;
  2194. decay_accumulator = 1.0;
  2195. for (j = 0; j < FRAMES_TO_CHECK_DECAY; ++j)
  2196. decay_accumulator *= recent_loop_decay[j];
  2197. // Special check for transition or high motion followed by a
  2198. // static scene.
  2199. if (detect_transition_to_still(cpi, i, cpi->oxcf.key_freq - i,
  2200. loop_decay_rate, decay_accumulator))
  2201. break;
  2202. // Step on to the next frame.
  2203. ++rc->frames_to_key;
  2204. // If we don't have a real key frame within the next two
  2205. // key_freq intervals then break out of the loop.
  2206. if (rc->frames_to_key >= 2 * cpi->oxcf.key_freq) break;
  2207. } else {
  2208. ++rc->frames_to_key;
  2209. }
  2210. ++i;
  2211. }
  2212. // If there is a max kf interval set by the user we must obey it.
  2213. // We already breakout of the loop above at 2x max.
  2214. // This code centers the extra kf if the actual natural interval
  2215. // is between 1x and 2x.
  2216. if (cpi->oxcf.auto_key && rc->frames_to_key > cpi->oxcf.key_freq) {
  2217. FIRSTPASS_STATS tmp_frame = first_frame;
  2218. rc->frames_to_key /= 2;
  2219. // Reset to the start of the group.
  2220. reset_fpf_position(twopass, start_position);
  2221. kf_group_err = 0.0;
  2222. // Rescan to get the correct error data for the forced kf group.
  2223. for (i = 0; i < rc->frames_to_key; ++i) {
  2224. kf_group_err += calculate_modified_err(cpi, twopass, oxcf, &tmp_frame);
  2225. input_stats(twopass, &tmp_frame);
  2226. }
  2227. rc->next_key_frame_forced = 1;
  2228. } else if (twopass->stats_in == twopass->stats_in_end ||
  2229. rc->frames_to_key >= cpi->oxcf.key_freq) {
  2230. rc->next_key_frame_forced = 1;
  2231. } else {
  2232. rc->next_key_frame_forced = 0;
  2233. }
  2234. if (is_two_pass_svc(cpi) && cpi->svc.number_temporal_layers > 1) {
  2235. int count = (1 << (cpi->svc.number_temporal_layers - 1)) - 1;
  2236. int new_frame_to_key = (rc->frames_to_key + count) & (~count);
  2237. int j;
  2238. for (j = 0; j < new_frame_to_key - rc->frames_to_key; ++j) {
  2239. if (EOF == input_stats(twopass, this_frame)) break;
  2240. kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
  2241. }
  2242. rc->frames_to_key = new_frame_to_key;
  2243. }
  2244. // Special case for the last key frame of the file.
  2245. if (twopass->stats_in >= twopass->stats_in_end) {
  2246. // Accumulate kf group error.
  2247. kf_group_err += calculate_modified_err(cpi, twopass, oxcf, this_frame);
  2248. }
  2249. // Calculate the number of bits that should be assigned to the kf group.
  2250. if (twopass->bits_left > 0 && twopass->modified_error_left > 0.0) {
  2251. // Maximum number of bits for a single normal frame (not key frame).
  2252. const int max_bits = frame_max_bits(rc, &cpi->oxcf);
  2253. // Maximum number of bits allocated to the key frame group.
  2254. int64_t max_grp_bits;
  2255. // Default allocation based on bits left and relative
  2256. // complexity of the section.
  2257. twopass->kf_group_bits = (int64_t)(
  2258. twopass->bits_left * (kf_group_err / twopass->modified_error_left));
  2259. // Clip based on maximum per frame rate defined by the user.
  2260. max_grp_bits = (int64_t)max_bits * (int64_t)rc->frames_to_key;
  2261. if (twopass->kf_group_bits > max_grp_bits)
  2262. twopass->kf_group_bits = max_grp_bits;
  2263. } else {
  2264. twopass->kf_group_bits = 0;
  2265. }
  2266. twopass->kf_group_bits = VPXMAX(0, twopass->kf_group_bits);
  2267. // Reset the first pass file position.
  2268. reset_fpf_position(twopass, start_position);
  2269. // Scan through the kf group collating various stats used to determine
  2270. // how many bits to spend on it.
  2271. decay_accumulator = 1.0;
  2272. boost_score = 0.0;
  2273. for (i = 0; i < (rc->frames_to_key - 1); ++i) {
  2274. if (EOF == input_stats(twopass, &next_frame)) break;
  2275. // Monitor for static sections.
  2276. zero_motion_accumulator = VPXMIN(zero_motion_accumulator,
  2277. get_zero_motion_factor(cpi, &next_frame));
  2278. // Not all frames in the group are necessarily used in calculating boost.
  2279. if ((i <= rc->max_gf_interval) ||
  2280. ((i <= (rc->max_gf_interval * 4)) && (decay_accumulator > 0.5))) {
  2281. const double frame_boost =
  2282. calc_frame_boost(cpi, &next_frame, 0, KF_MAX_BOOST);
  2283. // How fast is prediction quality decaying.
  2284. if (!detect_flash(twopass, 0)) {
  2285. const double loop_decay_rate =
  2286. get_prediction_decay_rate(cpi, &next_frame);
  2287. decay_accumulator *= loop_decay_rate;
  2288. decay_accumulator = VPXMAX(decay_accumulator, MIN_DECAY_FACTOR);
  2289. av_decay_accumulator += decay_accumulator;
  2290. ++loop_decay_counter;
  2291. }
  2292. boost_score += (decay_accumulator * frame_boost);
  2293. }
  2294. }
  2295. av_decay_accumulator /= (double)loop_decay_counter;
  2296. reset_fpf_position(twopass, start_position);
  2297. // Store the zero motion percentage
  2298. twopass->kf_zeromotion_pct = (int)(zero_motion_accumulator * 100.0);
  2299. // Calculate a section intra ratio used in setting max loop filter.
  2300. twopass->section_intra_rating = calculate_section_intra_ratio(
  2301. start_position, twopass->stats_in_end, rc->frames_to_key);
  2302. // Apply various clamps for min and max boost
  2303. rc->kf_boost = (int)(av_decay_accumulator * boost_score);
  2304. rc->kf_boost = VPXMAX(rc->kf_boost, (rc->frames_to_key * 3));
  2305. rc->kf_boost = VPXMAX(rc->kf_boost, MIN_KF_BOOST);
  2306. // Work out how many bits to allocate for the key frame itself.
  2307. kf_bits = calculate_boost_bits((rc->frames_to_key - 1), rc->kf_boost,
  2308. twopass->kf_group_bits);
  2309. twopass->kf_group_bits -= kf_bits;
  2310. // Save the bits to spend on the key frame.
  2311. gf_group->bit_allocation[0] = kf_bits;
  2312. gf_group->update_type[0] = KF_UPDATE;
  2313. gf_group->rf_level[0] = KF_STD;
  2314. // Note the total error score of the kf group minus the key frame itself.
  2315. twopass->kf_group_error_left = (int)(kf_group_err - kf_mod_err);
  2316. // Adjust the count of total modified error left.
  2317. // The count of bits left is adjusted elsewhere based on real coded frame
  2318. // sizes.
  2319. twopass->modified_error_left -= kf_group_err;
  2320. if (oxcf->resize_mode == RESIZE_DYNAMIC) {
  2321. // Default to normal-sized frame on keyframes.
  2322. cpi->rc.next_frame_size_selector = UNSCALED;
  2323. }
  2324. }
  2325. // Define the reference buffers that will be updated post encode.
  2326. static void configure_buffer_updates(VP9_COMP *cpi) {
  2327. TWO_PASS *const twopass = &cpi->twopass;
  2328. cpi->rc.is_src_frame_alt_ref = 0;
  2329. switch (twopass->gf_group.update_type[twopass->gf_group.index]) {
  2330. case KF_UPDATE:
  2331. cpi->refresh_last_frame = 1;
  2332. cpi->refresh_golden_frame = 1;
  2333. cpi->refresh_alt_ref_frame = 1;
  2334. break;
  2335. case LF_UPDATE:
  2336. cpi->refresh_last_frame = 1;
  2337. cpi->refresh_golden_frame = 0;
  2338. cpi->refresh_alt_ref_frame = 0;
  2339. break;
  2340. case GF_UPDATE:
  2341. cpi->refresh_last_frame = 1;
  2342. cpi->refresh_golden_frame = 1;
  2343. cpi->refresh_alt_ref_frame = 0;
  2344. break;
  2345. case OVERLAY_UPDATE:
  2346. cpi->refresh_last_frame = 0;
  2347. cpi->refresh_golden_frame = 1;
  2348. cpi->refresh_alt_ref_frame = 0;
  2349. cpi->rc.is_src_frame_alt_ref = 1;
  2350. break;
  2351. case ARF_UPDATE:
  2352. cpi->refresh_last_frame = 0;
  2353. cpi->refresh_golden_frame = 0;
  2354. cpi->refresh_alt_ref_frame = 1;
  2355. break;
  2356. default: assert(0); break;
  2357. }
  2358. if (is_two_pass_svc(cpi)) {
  2359. if (cpi->svc.temporal_layer_id > 0) {
  2360. cpi->refresh_last_frame = 0;
  2361. cpi->refresh_golden_frame = 0;
  2362. }
  2363. if (cpi->svc.layer_context[cpi->svc.spatial_layer_id].gold_ref_idx < 0)
  2364. cpi->refresh_golden_frame = 0;
  2365. if (cpi->alt_ref_source == NULL) cpi->refresh_alt_ref_frame = 0;
  2366. }
  2367. }
  2368. static int is_skippable_frame(const VP9_COMP *cpi) {
  2369. // If the current frame does not have non-zero motion vector detected in the
  2370. // first pass, and so do its previous and forward frames, then this frame
  2371. // can be skipped for partition check, and the partition size is assigned
  2372. // according to the variance
  2373. const SVC *const svc = &cpi->svc;
  2374. const TWO_PASS *const twopass =
  2375. is_two_pass_svc(cpi) ? &svc->layer_context[svc->spatial_layer_id].twopass
  2376. : &cpi->twopass;
  2377. return (!frame_is_intra_only(&cpi->common) &&
  2378. twopass->stats_in - 2 > twopass->stats_in_start &&
  2379. twopass->stats_in < twopass->stats_in_end &&
  2380. (twopass->stats_in - 1)->pcnt_inter -
  2381. (twopass->stats_in - 1)->pcnt_motion ==
  2382. 1 &&
  2383. (twopass->stats_in - 2)->pcnt_inter -
  2384. (twopass->stats_in - 2)->pcnt_motion ==
  2385. 1 &&
  2386. twopass->stats_in->pcnt_inter - twopass->stats_in->pcnt_motion == 1);
  2387. }
  2388. void vp9_rc_get_second_pass_params(VP9_COMP *cpi) {
  2389. VP9_COMMON *const cm = &cpi->common;
  2390. RATE_CONTROL *const rc = &cpi->rc;
  2391. TWO_PASS *const twopass = &cpi->twopass;
  2392. GF_GROUP *const gf_group = &twopass->gf_group;
  2393. FIRSTPASS_STATS this_frame;
  2394. int target_rate;
  2395. LAYER_CONTEXT *const lc =
  2396. is_two_pass_svc(cpi) ? &cpi->svc.layer_context[cpi->svc.spatial_layer_id]
  2397. : 0;
  2398. if (!twopass->stats_in) return;
  2399. // If this is an arf frame then we dont want to read the stats file or
  2400. // advance the input pointer as we already have what we need.
  2401. if (gf_group->update_type[gf_group->index] == ARF_UPDATE) {
  2402. int target_rate;
  2403. configure_buffer_updates(cpi);
  2404. target_rate = gf_group->bit_allocation[gf_group->index];
  2405. target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
  2406. rc->base_frame_target = target_rate;
  2407. cm->frame_type = INTER_FRAME;
  2408. if (lc != NULL) {
  2409. if (cpi->svc.spatial_layer_id == 0) {
  2410. lc->is_key_frame = 0;
  2411. } else {
  2412. lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
  2413. if (lc->is_key_frame) cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
  2414. }
  2415. }
  2416. // Do the firstpass stats indicate that this frame is skippable for the
  2417. // partition search?
  2418. if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
  2419. (!cpi->use_svc || is_two_pass_svc(cpi))) {
  2420. cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
  2421. }
  2422. return;
  2423. }
  2424. vpx_clear_system_state();
  2425. if (cpi->oxcf.rc_mode == VPX_Q) {
  2426. twopass->active_worst_quality = cpi->oxcf.cq_level;
  2427. } else if (cm->current_video_frame == 0 ||
  2428. (lc != NULL && lc->current_video_frame_in_layer == 0)) {
  2429. const int frames_left =
  2430. (int)(twopass->total_stats.count -
  2431. ((lc != NULL) ? lc->current_video_frame_in_layer
  2432. : cm->current_video_frame));
  2433. // Special case code for first frame.
  2434. const int section_target_bandwidth =
  2435. (int)(twopass->bits_left / frames_left);
  2436. const double section_length = twopass->total_left_stats.count;
  2437. const double section_error =
  2438. twopass->total_left_stats.coded_error / section_length;
  2439. const double section_intra_skip =
  2440. twopass->total_left_stats.intra_skip_pct / section_length;
  2441. const double section_inactive_zone =
  2442. (twopass->total_left_stats.inactive_zone_rows * 2) /
  2443. ((double)cm->mb_rows * section_length);
  2444. const double section_noise =
  2445. twopass->total_left_stats.frame_noise_energy / section_length;
  2446. int tmp_q;
  2447. tmp_q = get_twopass_worst_quality(
  2448. cpi, section_error, section_intra_skip + section_inactive_zone,
  2449. section_noise, section_target_bandwidth);
  2450. twopass->active_worst_quality = tmp_q;
  2451. twopass->baseline_active_worst_quality = tmp_q;
  2452. rc->ni_av_qi = tmp_q;
  2453. rc->last_q[INTER_FRAME] = tmp_q;
  2454. rc->avg_q = vp9_convert_qindex_to_q(tmp_q, cm->bit_depth);
  2455. rc->avg_frame_qindex[INTER_FRAME] = tmp_q;
  2456. rc->last_q[KEY_FRAME] = (tmp_q + cpi->oxcf.best_allowed_q) / 2;
  2457. rc->avg_frame_qindex[KEY_FRAME] = rc->last_q[KEY_FRAME];
  2458. }
  2459. vp9_zero(this_frame);
  2460. if (EOF == input_stats(twopass, &this_frame)) return;
  2461. // Set the frame content type flag.
  2462. if (this_frame.intra_skip_pct >= FC_ANIMATION_THRESH)
  2463. twopass->fr_content_type = FC_GRAPHICS_ANIMATION;
  2464. else
  2465. twopass->fr_content_type = FC_NORMAL;
  2466. // Keyframe and section processing.
  2467. if (rc->frames_to_key == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY)) {
  2468. FIRSTPASS_STATS this_frame_copy;
  2469. this_frame_copy = this_frame;
  2470. // Define next KF group and assign bits to it.
  2471. find_next_key_frame(cpi, &this_frame);
  2472. this_frame = this_frame_copy;
  2473. } else {
  2474. cm->frame_type = INTER_FRAME;
  2475. }
  2476. if (lc != NULL) {
  2477. if (cpi->svc.spatial_layer_id == 0) {
  2478. lc->is_key_frame = (cm->frame_type == KEY_FRAME);
  2479. if (lc->is_key_frame) {
  2480. cpi->ref_frame_flags &=
  2481. (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
  2482. lc->frames_from_key_frame = 0;
  2483. // Encode an intra only empty frame since we have a key frame.
  2484. cpi->svc.encode_intra_empty_frame = 1;
  2485. }
  2486. } else {
  2487. cm->frame_type = INTER_FRAME;
  2488. lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
  2489. if (lc->is_key_frame) {
  2490. cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
  2491. lc->frames_from_key_frame = 0;
  2492. }
  2493. }
  2494. }
  2495. // Define a new GF/ARF group. (Should always enter here for key frames).
  2496. if (rc->frames_till_gf_update_due == 0) {
  2497. define_gf_group(cpi, &this_frame);
  2498. rc->frames_till_gf_update_due = rc->baseline_gf_interval;
  2499. if (lc != NULL) cpi->refresh_golden_frame = 1;
  2500. #if ARF_STATS_OUTPUT
  2501. {
  2502. FILE *fpfile;
  2503. fpfile = fopen("arf.stt", "a");
  2504. ++arf_count;
  2505. fprintf(fpfile, "%10d %10ld %10d %10d %10ld\n", cm->current_video_frame,
  2506. rc->frames_till_gf_update_due, rc->kf_boost, arf_count,
  2507. rc->gfu_boost);
  2508. fclose(fpfile);
  2509. }
  2510. #endif
  2511. }
  2512. configure_buffer_updates(cpi);
  2513. // Do the firstpass stats indicate that this frame is skippable for the
  2514. // partition search?
  2515. if (cpi->sf.allow_partition_search_skip && cpi->oxcf.pass == 2 &&
  2516. (!cpi->use_svc || is_two_pass_svc(cpi))) {
  2517. cpi->partition_search_skippable_frame = is_skippable_frame(cpi);
  2518. }
  2519. target_rate = gf_group->bit_allocation[gf_group->index];
  2520. rc->base_frame_target = target_rate;
  2521. {
  2522. const int num_mbs = (cpi->oxcf.resize_mode != RESIZE_NONE)
  2523. ? cpi->initial_mbs
  2524. : cpi->common.MBs;
  2525. // The multiplication by 256 reverses a scaling factor of (>> 8)
  2526. // applied when combining MB error values for the frame.
  2527. twopass->mb_av_energy =
  2528. log(((this_frame.intra_error * 256.0) / num_mbs) + 1.0);
  2529. twopass->mb_smooth_pct = this_frame.intra_smooth_pct;
  2530. }
  2531. // Update the total stats remaining structure.
  2532. subtract_stats(&twopass->total_left_stats, &this_frame);
  2533. }
  2534. #define MINQ_ADJ_LIMIT 48
  2535. #define MINQ_ADJ_LIMIT_CQ 20
  2536. #define HIGH_UNDERSHOOT_RATIO 2
  2537. void vp9_twopass_postencode_update(VP9_COMP *cpi) {
  2538. TWO_PASS *const twopass = &cpi->twopass;
  2539. RATE_CONTROL *const rc = &cpi->rc;
  2540. VP9_COMMON *const cm = &cpi->common;
  2541. const int bits_used = rc->base_frame_target;
  2542. // VBR correction is done through rc->vbr_bits_off_target. Based on the
  2543. // sign of this value, a limited % adjustment is made to the target rate
  2544. // of subsequent frames, to try and push it back towards 0. This method
  2545. // is designed to prevent extreme behaviour at the end of a clip
  2546. // or group of frames.
  2547. rc->vbr_bits_off_target += rc->base_frame_target - rc->projected_frame_size;
  2548. twopass->bits_left = VPXMAX(twopass->bits_left - bits_used, 0);
  2549. // Target vs actual bits for this arf group.
  2550. twopass->rolling_arf_group_target_bits += rc->this_frame_target;
  2551. twopass->rolling_arf_group_actual_bits += rc->projected_frame_size;
  2552. // Calculate the pct rc error.
  2553. if (rc->total_actual_bits) {
  2554. rc->rate_error_estimate =
  2555. (int)((rc->vbr_bits_off_target * 100) / rc->total_actual_bits);
  2556. rc->rate_error_estimate = clamp(rc->rate_error_estimate, -100, 100);
  2557. } else {
  2558. rc->rate_error_estimate = 0;
  2559. }
  2560. if (cpi->common.frame_type != KEY_FRAME &&
  2561. !vp9_is_upper_layer_key_frame(cpi)) {
  2562. twopass->kf_group_bits -= bits_used;
  2563. twopass->last_kfgroup_zeromotion_pct = twopass->kf_zeromotion_pct;
  2564. }
  2565. twopass->kf_group_bits = VPXMAX(twopass->kf_group_bits, 0);
  2566. // Increment the gf group index ready for the next frame.
  2567. ++twopass->gf_group.index;
  2568. // If the rate control is drifting consider adjustment to min or maxq.
  2569. if ((cpi->oxcf.rc_mode != VPX_Q) && !cpi->rc.is_src_frame_alt_ref) {
  2570. const int maxq_adj_limit =
  2571. rc->worst_quality - twopass->active_worst_quality;
  2572. const int minq_adj_limit =
  2573. (cpi->oxcf.rc_mode == VPX_CQ ? MINQ_ADJ_LIMIT_CQ : MINQ_ADJ_LIMIT);
  2574. int aq_extend_min = 0;
  2575. int aq_extend_max = 0;
  2576. // Extend min or Max Q range to account for imbalance from the base
  2577. // value when using AQ.
  2578. if (cpi->oxcf.aq_mode != NO_AQ) {
  2579. if (cm->seg.aq_av_offset < 0) {
  2580. // The balance of the AQ map tends towarda lowering the average Q.
  2581. aq_extend_min = 0;
  2582. aq_extend_max = VPXMIN(maxq_adj_limit, -cm->seg.aq_av_offset);
  2583. } else {
  2584. // The balance of the AQ map tends towards raising the average Q.
  2585. aq_extend_min = VPXMIN(minq_adj_limit, cm->seg.aq_av_offset);
  2586. aq_extend_max = 0;
  2587. }
  2588. }
  2589. // Undershoot.
  2590. if (rc->rate_error_estimate > cpi->oxcf.under_shoot_pct) {
  2591. --twopass->extend_maxq;
  2592. if (rc->rolling_target_bits >= rc->rolling_actual_bits)
  2593. ++twopass->extend_minq;
  2594. // Overshoot.
  2595. } else if (rc->rate_error_estimate < -cpi->oxcf.over_shoot_pct) {
  2596. --twopass->extend_minq;
  2597. if (rc->rolling_target_bits < rc->rolling_actual_bits)
  2598. ++twopass->extend_maxq;
  2599. } else {
  2600. // Adjustment for extreme local overshoot.
  2601. if (rc->projected_frame_size > (2 * rc->base_frame_target) &&
  2602. rc->projected_frame_size > (2 * rc->avg_frame_bandwidth))
  2603. ++twopass->extend_maxq;
  2604. // Unwind undershoot or overshoot adjustment.
  2605. if (rc->rolling_target_bits < rc->rolling_actual_bits)
  2606. --twopass->extend_minq;
  2607. else if (rc->rolling_target_bits > rc->rolling_actual_bits)
  2608. --twopass->extend_maxq;
  2609. }
  2610. twopass->extend_minq =
  2611. clamp(twopass->extend_minq, aq_extend_min, minq_adj_limit);
  2612. twopass->extend_maxq =
  2613. clamp(twopass->extend_maxq, aq_extend_max, maxq_adj_limit);
  2614. // If there is a big and undexpected undershoot then feed the extra
  2615. // bits back in quickly. One situation where this may happen is if a
  2616. // frame is unexpectedly almost perfectly predicted by the ARF or GF
  2617. // but not very well predcited by the previous frame.
  2618. if (!frame_is_kf_gf_arf(cpi) && !cpi->rc.is_src_frame_alt_ref) {
  2619. int fast_extra_thresh = rc->base_frame_target / HIGH_UNDERSHOOT_RATIO;
  2620. if (rc->projected_frame_size < fast_extra_thresh) {
  2621. rc->vbr_bits_off_target_fast +=
  2622. fast_extra_thresh - rc->projected_frame_size;
  2623. rc->vbr_bits_off_target_fast =
  2624. VPXMIN(rc->vbr_bits_off_target_fast, (4 * rc->avg_frame_bandwidth));
  2625. // Fast adaptation of minQ if necessary to use up the extra bits.
  2626. if (rc->avg_frame_bandwidth) {
  2627. twopass->extend_minq_fast =
  2628. (int)(rc->vbr_bits_off_target_fast * 8 / rc->avg_frame_bandwidth);
  2629. }
  2630. twopass->extend_minq_fast = VPXMIN(
  2631. twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
  2632. } else if (rc->vbr_bits_off_target_fast) {
  2633. twopass->extend_minq_fast = VPXMIN(
  2634. twopass->extend_minq_fast, minq_adj_limit - twopass->extend_minq);
  2635. } else {
  2636. twopass->extend_minq_fast = 0;
  2637. }
  2638. }
  2639. }
  2640. }