vp9_firstpass.c 125 KB

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