vp9_firstpass.c 98 KB

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