firstpass.c 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159
  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 <math.h>
  11. #include <limits.h>
  12. #include <stdio.h>
  13. #include "./vpx_dsp_rtcd.h"
  14. #include "./vpx_scale_rtcd.h"
  15. #include "block.h"
  16. #include "onyx_int.h"
  17. #include "vpx_dsp/variance.h"
  18. #include "encodeintra.h"
  19. #include "vp8/common/common.h"
  20. #include "vp8/common/setupintrarecon.h"
  21. #include "vp8/common/systemdependent.h"
  22. #include "mcomp.h"
  23. #include "firstpass.h"
  24. #include "vpx_scale/vpx_scale.h"
  25. #include "encodemb.h"
  26. #include "vp8/common/extend.h"
  27. #include "vpx_ports/system_state.h"
  28. #include "vpx_mem/vpx_mem.h"
  29. #include "vp8/common/swapyv12buffer.h"
  30. #include "rdopt.h"
  31. #include "vp8/common/quant_common.h"
  32. #include "encodemv.h"
  33. #include "encodeframe.h"
  34. #define OUTPUT_FPF 0
  35. extern void vp8cx_frame_init_quantizer(VP8_COMP *cpi);
  36. #define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
  37. extern int vp8_kf_boost_qadjustment[QINDEX_RANGE];
  38. extern const int vp8_gf_boost_qadjustment[QINDEX_RANGE];
  39. #define IIFACTOR 1.5
  40. #define IIKFACTOR1 1.40
  41. #define IIKFACTOR2 1.5
  42. #define RMAX 14.0
  43. #define GF_RMAX 48.0
  44. #define KF_MB_INTRA_MIN 300
  45. #define GF_MB_INTRA_MIN 200
  46. #define DOUBLE_DIVIDE_CHECK(X) ((X) < 0 ? (X)-.000001 : (X) + .000001)
  47. #define POW1 (double)cpi->oxcf.two_pass_vbrbias / 100.0
  48. #define POW2 (double)cpi->oxcf.two_pass_vbrbias / 100.0
  49. #define NEW_BOOST 1
  50. static int vscale_lookup[7] = { 0, 1, 1, 2, 2, 3, 3 };
  51. static int hscale_lookup[7] = { 0, 0, 1, 1, 2, 2, 3 };
  52. static const int cq_level[QINDEX_RANGE] = {
  53. 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11,
  54. 11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24,
  55. 24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
  56. 39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 50, 51, 52, 53,
  57. 54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69,
  58. 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86,
  59. 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
  60. };
  61. static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame);
  62. /* Resets the first pass file to the given position using a relative seek
  63. * from the current position
  64. */
  65. static void reset_fpf_position(VP8_COMP *cpi, FIRSTPASS_STATS *Position) {
  66. cpi->twopass.stats_in = Position;
  67. }
  68. static int lookup_next_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *next_frame) {
  69. if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) return EOF;
  70. *next_frame = *cpi->twopass.stats_in;
  71. return 1;
  72. }
  73. /* Read frame stats at an offset from the current position */
  74. static int read_frame_stats(VP8_COMP *cpi, FIRSTPASS_STATS *frame_stats,
  75. int offset) {
  76. FIRSTPASS_STATS *fps_ptr = cpi->twopass.stats_in;
  77. /* Check legality of offset */
  78. if (offset >= 0) {
  79. if (&fps_ptr[offset] >= cpi->twopass.stats_in_end) return EOF;
  80. } else if (offset < 0) {
  81. if (&fps_ptr[offset] < cpi->twopass.stats_in_start) return EOF;
  82. }
  83. *frame_stats = fps_ptr[offset];
  84. return 1;
  85. }
  86. static int input_stats(VP8_COMP *cpi, FIRSTPASS_STATS *fps) {
  87. if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) return EOF;
  88. *fps = *cpi->twopass.stats_in;
  89. cpi->twopass.stats_in =
  90. (void *)((char *)cpi->twopass.stats_in + sizeof(FIRSTPASS_STATS));
  91. return 1;
  92. }
  93. static void output_stats(const VP8_COMP *cpi,
  94. struct vpx_codec_pkt_list *pktlist,
  95. FIRSTPASS_STATS *stats) {
  96. struct vpx_codec_cx_pkt pkt;
  97. (void)cpi;
  98. pkt.kind = VPX_CODEC_STATS_PKT;
  99. pkt.data.twopass_stats.buf = stats;
  100. pkt.data.twopass_stats.sz = sizeof(FIRSTPASS_STATS);
  101. vpx_codec_pkt_list_add(pktlist, &pkt);
  102. /* TEMP debug code */
  103. #if OUTPUT_FPF
  104. {
  105. FILE *fpfile;
  106. fpfile = fopen("firstpass.stt", "a");
  107. fprintf(fpfile,
  108. "%12.0f %12.0f %12.0f %12.4f %12.4f %12.4f %12.4f"
  109. " %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f %12.4f"
  110. " %12.0f %12.0f %12.4f\n",
  111. stats->frame, stats->intra_error, stats->coded_error,
  112. stats->ssim_weighted_pred_err, stats->pcnt_inter,
  113. stats->pcnt_motion, stats->pcnt_second_ref, stats->pcnt_neutral,
  114. stats->MVr, stats->mvr_abs, stats->MVc, stats->mvc_abs, stats->MVrv,
  115. stats->MVcv, stats->mv_in_out_count, stats->new_mv_count,
  116. stats->count, stats->duration);
  117. fclose(fpfile);
  118. }
  119. #endif
  120. }
  121. static void zero_stats(FIRSTPASS_STATS *section) {
  122. section->frame = 0.0;
  123. section->intra_error = 0.0;
  124. section->coded_error = 0.0;
  125. section->ssim_weighted_pred_err = 0.0;
  126. section->pcnt_inter = 0.0;
  127. section->pcnt_motion = 0.0;
  128. section->pcnt_second_ref = 0.0;
  129. section->pcnt_neutral = 0.0;
  130. section->MVr = 0.0;
  131. section->mvr_abs = 0.0;
  132. section->MVc = 0.0;
  133. section->mvc_abs = 0.0;
  134. section->MVrv = 0.0;
  135. section->MVcv = 0.0;
  136. section->mv_in_out_count = 0.0;
  137. section->new_mv_count = 0.0;
  138. section->count = 0.0;
  139. section->duration = 1.0;
  140. }
  141. static void accumulate_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
  142. section->frame += frame->frame;
  143. section->intra_error += frame->intra_error;
  144. section->coded_error += frame->coded_error;
  145. section->ssim_weighted_pred_err += frame->ssim_weighted_pred_err;
  146. section->pcnt_inter += frame->pcnt_inter;
  147. section->pcnt_motion += frame->pcnt_motion;
  148. section->pcnt_second_ref += frame->pcnt_second_ref;
  149. section->pcnt_neutral += frame->pcnt_neutral;
  150. section->MVr += frame->MVr;
  151. section->mvr_abs += frame->mvr_abs;
  152. section->MVc += frame->MVc;
  153. section->mvc_abs += frame->mvc_abs;
  154. section->MVrv += frame->MVrv;
  155. section->MVcv += frame->MVcv;
  156. section->mv_in_out_count += frame->mv_in_out_count;
  157. section->new_mv_count += frame->new_mv_count;
  158. section->count += frame->count;
  159. section->duration += frame->duration;
  160. }
  161. static void subtract_stats(FIRSTPASS_STATS *section, FIRSTPASS_STATS *frame) {
  162. section->frame -= frame->frame;
  163. section->intra_error -= frame->intra_error;
  164. section->coded_error -= frame->coded_error;
  165. section->ssim_weighted_pred_err -= frame->ssim_weighted_pred_err;
  166. section->pcnt_inter -= frame->pcnt_inter;
  167. section->pcnt_motion -= frame->pcnt_motion;
  168. section->pcnt_second_ref -= frame->pcnt_second_ref;
  169. section->pcnt_neutral -= frame->pcnt_neutral;
  170. section->MVr -= frame->MVr;
  171. section->mvr_abs -= frame->mvr_abs;
  172. section->MVc -= frame->MVc;
  173. section->mvc_abs -= frame->mvc_abs;
  174. section->MVrv -= frame->MVrv;
  175. section->MVcv -= frame->MVcv;
  176. section->mv_in_out_count -= frame->mv_in_out_count;
  177. section->new_mv_count -= frame->new_mv_count;
  178. section->count -= frame->count;
  179. section->duration -= frame->duration;
  180. }
  181. static void avg_stats(FIRSTPASS_STATS *section) {
  182. if (section->count < 1.0) return;
  183. section->intra_error /= section->count;
  184. section->coded_error /= section->count;
  185. section->ssim_weighted_pred_err /= section->count;
  186. section->pcnt_inter /= section->count;
  187. section->pcnt_second_ref /= section->count;
  188. section->pcnt_neutral /= section->count;
  189. section->pcnt_motion /= section->count;
  190. section->MVr /= section->count;
  191. section->mvr_abs /= section->count;
  192. section->MVc /= section->count;
  193. section->mvc_abs /= section->count;
  194. section->MVrv /= section->count;
  195. section->MVcv /= section->count;
  196. section->mv_in_out_count /= section->count;
  197. section->duration /= section->count;
  198. }
  199. /* Calculate a modified Error used in distributing bits between easier
  200. * and harder frames
  201. */
  202. static double calculate_modified_err(VP8_COMP *cpi,
  203. FIRSTPASS_STATS *this_frame) {
  204. double av_err = (cpi->twopass.total_stats.ssim_weighted_pred_err /
  205. cpi->twopass.total_stats.count);
  206. double this_err = this_frame->ssim_weighted_pred_err;
  207. double modified_err;
  208. if (this_err > av_err) {
  209. modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW1);
  210. } else {
  211. modified_err = av_err * pow((this_err / DOUBLE_DIVIDE_CHECK(av_err)), POW2);
  212. }
  213. return modified_err;
  214. }
  215. static const double weight_table[256] = {
  216. 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  217. 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  218. 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  219. 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.020000,
  220. 0.020000, 0.020000, 0.020000, 0.020000, 0.020000, 0.031250, 0.062500,
  221. 0.093750, 0.125000, 0.156250, 0.187500, 0.218750, 0.250000, 0.281250,
  222. 0.312500, 0.343750, 0.375000, 0.406250, 0.437500, 0.468750, 0.500000,
  223. 0.531250, 0.562500, 0.593750, 0.625000, 0.656250, 0.687500, 0.718750,
  224. 0.750000, 0.781250, 0.812500, 0.843750, 0.875000, 0.906250, 0.937500,
  225. 0.968750, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  226. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  227. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  228. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  229. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  230. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  231. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  232. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  233. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  234. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  235. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  236. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  237. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  238. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  239. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  240. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  241. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  242. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  243. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  244. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  245. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  246. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  247. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  248. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  249. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  250. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  251. 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000, 1.000000,
  252. 1.000000, 1.000000, 1.000000, 1.000000
  253. };
  254. static double simple_weight(YV12_BUFFER_CONFIG *source) {
  255. int i, j;
  256. unsigned char *src = source->y_buffer;
  257. double sum_weights = 0.0;
  258. /* Loop throught the Y plane raw examining levels and creating a weight
  259. * for the image
  260. */
  261. i = source->y_height;
  262. do {
  263. j = source->y_width;
  264. do {
  265. sum_weights += weight_table[*src];
  266. src++;
  267. } while (--j);
  268. src -= source->y_width;
  269. src += source->y_stride;
  270. } while (--i);
  271. sum_weights /= (source->y_height * source->y_width);
  272. return sum_weights;
  273. }
  274. /* This function returns the current per frame maximum bitrate target */
  275. static int frame_max_bits(VP8_COMP *cpi) {
  276. /* Max allocation for a single frame based on the max section guidelines
  277. * passed in and how many bits are left
  278. */
  279. int max_bits;
  280. /* For CBR we need to also consider buffer fullness.
  281. * If we are running below the optimal level then we need to gradually
  282. * tighten up on max_bits.
  283. */
  284. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  285. double buffer_fullness_ratio =
  286. (double)cpi->buffer_level /
  287. DOUBLE_DIVIDE_CHECK((double)cpi->oxcf.optimal_buffer_level);
  288. /* For CBR base this on the target average bits per frame plus the
  289. * maximum sedction rate passed in by the user
  290. */
  291. max_bits = (int)(cpi->av_per_frame_bandwidth *
  292. ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
  293. /* If our buffer is below the optimum level */
  294. if (buffer_fullness_ratio < 1.0) {
  295. /* The lower of max_bits / 4 or cpi->av_per_frame_bandwidth / 4. */
  296. int min_max_bits = ((cpi->av_per_frame_bandwidth >> 2) < (max_bits >> 2))
  297. ? cpi->av_per_frame_bandwidth >> 2
  298. : max_bits >> 2;
  299. max_bits = (int)(max_bits * buffer_fullness_ratio);
  300. /* Lowest value we will set ... which should allow the buffer to
  301. * refill.
  302. */
  303. if (max_bits < min_max_bits) max_bits = min_max_bits;
  304. }
  305. }
  306. /* VBR */
  307. else {
  308. /* For VBR base this on the bits and frames left plus the
  309. * two_pass_vbrmax_section rate passed in by the user
  310. */
  311. max_bits = (int)(((double)cpi->twopass.bits_left /
  312. (cpi->twopass.total_stats.count -
  313. (double)cpi->common.current_video_frame)) *
  314. ((double)cpi->oxcf.two_pass_vbrmax_section / 100.0));
  315. }
  316. /* Trap case where we are out of bits */
  317. if (max_bits < 0) max_bits = 0;
  318. return max_bits;
  319. }
  320. void vp8_init_first_pass(VP8_COMP *cpi) {
  321. zero_stats(&cpi->twopass.total_stats);
  322. }
  323. void vp8_end_first_pass(VP8_COMP *cpi) {
  324. output_stats(cpi, cpi->output_pkt_list, &cpi->twopass.total_stats);
  325. }
  326. static void zz_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
  327. YV12_BUFFER_CONFIG *raw_buffer,
  328. int *raw_motion_err,
  329. YV12_BUFFER_CONFIG *recon_buffer,
  330. int *best_motion_err, int recon_yoffset) {
  331. MACROBLOCKD *const xd = &x->e_mbd;
  332. BLOCK *b = &x->block[0];
  333. BLOCKD *d = &x->e_mbd.block[0];
  334. unsigned char *src_ptr = (*(b->base_src) + b->src);
  335. int src_stride = b->src_stride;
  336. unsigned char *raw_ptr;
  337. int raw_stride = raw_buffer->y_stride;
  338. unsigned char *ref_ptr;
  339. int ref_stride = x->e_mbd.pre.y_stride;
  340. (void)cpi;
  341. /* Set up pointers for this macro block raw buffer */
  342. raw_ptr = (unsigned char *)(raw_buffer->y_buffer + recon_yoffset + d->offset);
  343. vpx_mse16x16(src_ptr, src_stride, raw_ptr, raw_stride,
  344. (unsigned int *)(raw_motion_err));
  345. /* Set up pointers for this macro block recon buffer */
  346. xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
  347. ref_ptr = (unsigned char *)(xd->pre.y_buffer + d->offset);
  348. vpx_mse16x16(src_ptr, src_stride, ref_ptr, ref_stride,
  349. (unsigned int *)(best_motion_err));
  350. }
  351. static void first_pass_motion_search(VP8_COMP *cpi, MACROBLOCK *x,
  352. int_mv *ref_mv, MV *best_mv,
  353. YV12_BUFFER_CONFIG *recon_buffer,
  354. int *best_motion_err, int recon_yoffset) {
  355. MACROBLOCKD *const xd = &x->e_mbd;
  356. BLOCK *b = &x->block[0];
  357. BLOCKD *d = &x->e_mbd.block[0];
  358. int num00;
  359. int_mv tmp_mv;
  360. int_mv ref_mv_full;
  361. int tmp_err;
  362. int step_param = 3; /* Dont search over full range for first pass */
  363. int further_steps = (MAX_MVSEARCH_STEPS - 1) - step_param;
  364. int n;
  365. vp8_variance_fn_ptr_t v_fn_ptr = cpi->fn_ptr[BLOCK_16X16];
  366. int new_mv_mode_penalty = 256;
  367. /* override the default variance function to use MSE */
  368. v_fn_ptr.vf = vpx_mse16x16;
  369. /* Set up pointers for this macro block recon buffer */
  370. xd->pre.y_buffer = recon_buffer->y_buffer + recon_yoffset;
  371. /* Initial step/diamond search centred on best mv */
  372. tmp_mv.as_int = 0;
  373. ref_mv_full.as_mv.col = ref_mv->as_mv.col >> 3;
  374. ref_mv_full.as_mv.row = ref_mv->as_mv.row >> 3;
  375. tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv, step_param,
  376. x->sadperbit16, &num00, &v_fn_ptr,
  377. x->mvcost, ref_mv);
  378. if (tmp_err < INT_MAX - new_mv_mode_penalty) tmp_err += new_mv_mode_penalty;
  379. if (tmp_err < *best_motion_err) {
  380. *best_motion_err = tmp_err;
  381. best_mv->row = tmp_mv.as_mv.row;
  382. best_mv->col = tmp_mv.as_mv.col;
  383. }
  384. /* Further step/diamond searches as necessary */
  385. n = num00;
  386. num00 = 0;
  387. while (n < further_steps) {
  388. n++;
  389. if (num00) {
  390. num00--;
  391. } else {
  392. tmp_err = cpi->diamond_search_sad(x, b, d, &ref_mv_full, &tmp_mv,
  393. step_param + n, x->sadperbit16, &num00,
  394. &v_fn_ptr, x->mvcost, ref_mv);
  395. if (tmp_err < INT_MAX - new_mv_mode_penalty) {
  396. tmp_err += new_mv_mode_penalty;
  397. }
  398. if (tmp_err < *best_motion_err) {
  399. *best_motion_err = tmp_err;
  400. best_mv->row = tmp_mv.as_mv.row;
  401. best_mv->col = tmp_mv.as_mv.col;
  402. }
  403. }
  404. }
  405. }
  406. void vp8_first_pass(VP8_COMP *cpi) {
  407. int mb_row, mb_col;
  408. MACROBLOCK *const x = &cpi->mb;
  409. VP8_COMMON *const cm = &cpi->common;
  410. MACROBLOCKD *const xd = &x->e_mbd;
  411. int recon_yoffset, recon_uvoffset;
  412. YV12_BUFFER_CONFIG *lst_yv12 = &cm->yv12_fb[cm->lst_fb_idx];
  413. YV12_BUFFER_CONFIG *new_yv12 = &cm->yv12_fb[cm->new_fb_idx];
  414. YV12_BUFFER_CONFIG *gld_yv12 = &cm->yv12_fb[cm->gld_fb_idx];
  415. int recon_y_stride = lst_yv12->y_stride;
  416. int recon_uv_stride = lst_yv12->uv_stride;
  417. int64_t intra_error = 0;
  418. int64_t coded_error = 0;
  419. int sum_mvr = 0, sum_mvc = 0;
  420. int sum_mvr_abs = 0, sum_mvc_abs = 0;
  421. int sum_mvrs = 0, sum_mvcs = 0;
  422. int mvcount = 0;
  423. int intercount = 0;
  424. int second_ref_count = 0;
  425. int intrapenalty = 256;
  426. int neutral_count = 0;
  427. int new_mv_count = 0;
  428. int sum_in_vectors = 0;
  429. uint32_t lastmv_as_int = 0;
  430. int_mv zero_ref_mv;
  431. zero_ref_mv.as_int = 0;
  432. vpx_clear_system_state();
  433. x->src = *cpi->Source;
  434. xd->pre = *lst_yv12;
  435. xd->dst = *new_yv12;
  436. x->partition_info = x->pi;
  437. xd->mode_info_context = cm->mi;
  438. if (!cm->use_bilinear_mc_filter) {
  439. xd->subpixel_predict = vp8_sixtap_predict4x4;
  440. xd->subpixel_predict8x4 = vp8_sixtap_predict8x4;
  441. xd->subpixel_predict8x8 = vp8_sixtap_predict8x8;
  442. xd->subpixel_predict16x16 = vp8_sixtap_predict16x16;
  443. } else {
  444. xd->subpixel_predict = vp8_bilinear_predict4x4;
  445. xd->subpixel_predict8x4 = vp8_bilinear_predict8x4;
  446. xd->subpixel_predict8x8 = vp8_bilinear_predict8x8;
  447. xd->subpixel_predict16x16 = vp8_bilinear_predict16x16;
  448. }
  449. vp8_build_block_offsets(x);
  450. /* set up frame new frame for intra coded blocks */
  451. vp8_setup_intra_recon(new_yv12);
  452. vp8cx_frame_init_quantizer(cpi);
  453. /* Initialise the MV cost table to the defaults */
  454. {
  455. int flag[2] = { 1, 1 };
  456. vp8_initialize_rd_consts(cpi, x,
  457. vp8_dc_quant(cm->base_qindex, cm->y1dc_delta_q));
  458. memcpy(cm->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
  459. vp8_build_component_cost_table(cpi->mb.mvcost,
  460. (const MV_CONTEXT *)cm->fc.mvc, flag);
  461. }
  462. /* for each macroblock row in image */
  463. for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
  464. int_mv best_ref_mv;
  465. best_ref_mv.as_int = 0;
  466. /* reset above block coeffs */
  467. xd->up_available = (mb_row != 0);
  468. recon_yoffset = (mb_row * recon_y_stride * 16);
  469. recon_uvoffset = (mb_row * recon_uv_stride * 8);
  470. /* Set up limit values for motion vectors to prevent them extending
  471. * outside the UMV borders
  472. */
  473. x->mv_row_min = -((mb_row * 16) + (VP8BORDERINPIXELS - 16));
  474. x->mv_row_max =
  475. ((cm->mb_rows - 1 - mb_row) * 16) + (VP8BORDERINPIXELS - 16);
  476. /* for each macroblock col in image */
  477. for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
  478. int this_error;
  479. int gf_motion_error = INT_MAX;
  480. int use_dc_pred = (mb_col || mb_row) && (!mb_col || !mb_row);
  481. xd->dst.y_buffer = new_yv12->y_buffer + recon_yoffset;
  482. xd->dst.u_buffer = new_yv12->u_buffer + recon_uvoffset;
  483. xd->dst.v_buffer = new_yv12->v_buffer + recon_uvoffset;
  484. xd->left_available = (mb_col != 0);
  485. /* Copy current mb to a buffer */
  486. vp8_copy_mem16x16(x->src.y_buffer, x->src.y_stride, x->thismb, 16);
  487. /* do intra 16x16 prediction */
  488. this_error = vp8_encode_intra(cpi, x, use_dc_pred);
  489. /* "intrapenalty" below deals with situations where the intra
  490. * and inter error scores are very low (eg a plain black frame)
  491. * We do not have special cases in first pass for 0,0 and
  492. * nearest etc so all inter modes carry an overhead cost
  493. * estimate fot the mv. When the error score is very low this
  494. * causes us to pick all or lots of INTRA modes and throw lots
  495. * of key frames. This penalty adds a cost matching that of a
  496. * 0,0 mv to the intra case.
  497. */
  498. this_error += intrapenalty;
  499. /* Cumulative intra error total */
  500. intra_error += (int64_t)this_error;
  501. /* Set up limit values for motion vectors to prevent them
  502. * extending outside the UMV borders
  503. */
  504. x->mv_col_min = -((mb_col * 16) + (VP8BORDERINPIXELS - 16));
  505. x->mv_col_max =
  506. ((cm->mb_cols - 1 - mb_col) * 16) + (VP8BORDERINPIXELS - 16);
  507. /* Other than for the first frame do a motion search */
  508. if (cm->current_video_frame > 0) {
  509. BLOCKD *d = &x->e_mbd.block[0];
  510. MV tmp_mv = { 0, 0 };
  511. int tmp_err;
  512. int motion_error = INT_MAX;
  513. int raw_motion_error = INT_MAX;
  514. /* Simple 0,0 motion with no mv overhead */
  515. zz_motion_search(cpi, x, cpi->last_frame_unscaled_source,
  516. &raw_motion_error, lst_yv12, &motion_error,
  517. recon_yoffset);
  518. d->bmi.mv.as_mv.row = 0;
  519. d->bmi.mv.as_mv.col = 0;
  520. if (raw_motion_error < cpi->oxcf.encode_breakout) {
  521. goto skip_motion_search;
  522. }
  523. /* Test last reference frame using the previous best mv as the
  524. * starting point (best reference) for the search
  525. */
  526. first_pass_motion_search(cpi, x, &best_ref_mv, &d->bmi.mv.as_mv,
  527. lst_yv12, &motion_error, recon_yoffset);
  528. /* If the current best reference mv is not centred on 0,0
  529. * then do a 0,0 based search as well
  530. */
  531. if (best_ref_mv.as_int) {
  532. tmp_err = INT_MAX;
  533. first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, lst_yv12,
  534. &tmp_err, recon_yoffset);
  535. if (tmp_err < motion_error) {
  536. motion_error = tmp_err;
  537. d->bmi.mv.as_mv.row = tmp_mv.row;
  538. d->bmi.mv.as_mv.col = tmp_mv.col;
  539. }
  540. }
  541. /* Experimental search in a second reference frame ((0,0)
  542. * based only)
  543. */
  544. if (cm->current_video_frame > 1) {
  545. first_pass_motion_search(cpi, x, &zero_ref_mv, &tmp_mv, gld_yv12,
  546. &gf_motion_error, recon_yoffset);
  547. if ((gf_motion_error < motion_error) &&
  548. (gf_motion_error < this_error)) {
  549. second_ref_count++;
  550. }
  551. /* Reset to last frame as reference buffer */
  552. xd->pre.y_buffer = lst_yv12->y_buffer + recon_yoffset;
  553. xd->pre.u_buffer = lst_yv12->u_buffer + recon_uvoffset;
  554. xd->pre.v_buffer = lst_yv12->v_buffer + recon_uvoffset;
  555. }
  556. skip_motion_search:
  557. /* Intra assumed best */
  558. best_ref_mv.as_int = 0;
  559. if (motion_error <= this_error) {
  560. /* Keep a count of cases where the inter and intra were
  561. * very close and very low. This helps with scene cut
  562. * detection for example in cropped clips with black bars
  563. * at the sides or top and bottom.
  564. */
  565. if ((((this_error - intrapenalty) * 9) <= (motion_error * 10)) &&
  566. (this_error < (2 * intrapenalty))) {
  567. neutral_count++;
  568. }
  569. d->bmi.mv.as_mv.row *= 8;
  570. d->bmi.mv.as_mv.col *= 8;
  571. this_error = motion_error;
  572. vp8_set_mbmode_and_mvs(x, NEWMV, &d->bmi.mv);
  573. vp8_encode_inter16x16y(x);
  574. sum_mvr += d->bmi.mv.as_mv.row;
  575. sum_mvr_abs += abs(d->bmi.mv.as_mv.row);
  576. sum_mvc += d->bmi.mv.as_mv.col;
  577. sum_mvc_abs += abs(d->bmi.mv.as_mv.col);
  578. sum_mvrs += d->bmi.mv.as_mv.row * d->bmi.mv.as_mv.row;
  579. sum_mvcs += d->bmi.mv.as_mv.col * d->bmi.mv.as_mv.col;
  580. intercount++;
  581. best_ref_mv.as_int = d->bmi.mv.as_int;
  582. /* Was the vector non-zero */
  583. if (d->bmi.mv.as_int) {
  584. mvcount++;
  585. /* Was it different from the last non zero vector */
  586. if (d->bmi.mv.as_int != lastmv_as_int) new_mv_count++;
  587. lastmv_as_int = d->bmi.mv.as_int;
  588. /* Does the Row vector point inwards or outwards */
  589. if (mb_row < cm->mb_rows / 2) {
  590. if (d->bmi.mv.as_mv.row > 0) {
  591. sum_in_vectors--;
  592. } else if (d->bmi.mv.as_mv.row < 0) {
  593. sum_in_vectors++;
  594. }
  595. } else if (mb_row > cm->mb_rows / 2) {
  596. if (d->bmi.mv.as_mv.row > 0) {
  597. sum_in_vectors++;
  598. } else if (d->bmi.mv.as_mv.row < 0) {
  599. sum_in_vectors--;
  600. }
  601. }
  602. /* Does the Row vector point inwards or outwards */
  603. if (mb_col < cm->mb_cols / 2) {
  604. if (d->bmi.mv.as_mv.col > 0) {
  605. sum_in_vectors--;
  606. } else if (d->bmi.mv.as_mv.col < 0) {
  607. sum_in_vectors++;
  608. }
  609. } else if (mb_col > cm->mb_cols / 2) {
  610. if (d->bmi.mv.as_mv.col > 0) {
  611. sum_in_vectors++;
  612. } else if (d->bmi.mv.as_mv.col < 0) {
  613. sum_in_vectors--;
  614. }
  615. }
  616. }
  617. }
  618. }
  619. coded_error += (int64_t)this_error;
  620. /* adjust to the next column of macroblocks */
  621. x->src.y_buffer += 16;
  622. x->src.u_buffer += 8;
  623. x->src.v_buffer += 8;
  624. recon_yoffset += 16;
  625. recon_uvoffset += 8;
  626. }
  627. /* adjust to the next row of mbs */
  628. x->src.y_buffer += 16 * x->src.y_stride - 16 * cm->mb_cols;
  629. x->src.u_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
  630. x->src.v_buffer += 8 * x->src.uv_stride - 8 * cm->mb_cols;
  631. /* extend the recon for intra prediction */
  632. vp8_extend_mb_row(new_yv12, xd->dst.y_buffer + 16, xd->dst.u_buffer + 8,
  633. xd->dst.v_buffer + 8);
  634. vpx_clear_system_state();
  635. }
  636. vpx_clear_system_state();
  637. {
  638. double weight = 0.0;
  639. FIRSTPASS_STATS fps;
  640. fps.frame = cm->current_video_frame;
  641. fps.intra_error = (double)(intra_error >> 8);
  642. fps.coded_error = (double)(coded_error >> 8);
  643. weight = simple_weight(cpi->Source);
  644. if (weight < 0.1) weight = 0.1;
  645. fps.ssim_weighted_pred_err = fps.coded_error * weight;
  646. fps.pcnt_inter = 0.0;
  647. fps.pcnt_motion = 0.0;
  648. fps.MVr = 0.0;
  649. fps.mvr_abs = 0.0;
  650. fps.MVc = 0.0;
  651. fps.mvc_abs = 0.0;
  652. fps.MVrv = 0.0;
  653. fps.MVcv = 0.0;
  654. fps.mv_in_out_count = 0.0;
  655. fps.new_mv_count = 0.0;
  656. fps.count = 1.0;
  657. fps.pcnt_inter = 1.0 * (double)intercount / cm->MBs;
  658. fps.pcnt_second_ref = 1.0 * (double)second_ref_count / cm->MBs;
  659. fps.pcnt_neutral = 1.0 * (double)neutral_count / cm->MBs;
  660. if (mvcount > 0) {
  661. fps.MVr = (double)sum_mvr / (double)mvcount;
  662. fps.mvr_abs = (double)sum_mvr_abs / (double)mvcount;
  663. fps.MVc = (double)sum_mvc / (double)mvcount;
  664. fps.mvc_abs = (double)sum_mvc_abs / (double)mvcount;
  665. fps.MVrv = ((double)sum_mvrs - (fps.MVr * fps.MVr / (double)mvcount)) /
  666. (double)mvcount;
  667. fps.MVcv = ((double)sum_mvcs - (fps.MVc * fps.MVc / (double)mvcount)) /
  668. (double)mvcount;
  669. fps.mv_in_out_count = (double)sum_in_vectors / (double)(mvcount * 2);
  670. fps.new_mv_count = new_mv_count;
  671. fps.pcnt_motion = 1.0 * (double)mvcount / cpi->common.MBs;
  672. }
  673. /* TODO: handle the case when duration is set to 0, or something less
  674. * than the full time between subsequent cpi->source_time_stamps
  675. */
  676. fps.duration = (double)(cpi->source->ts_end - cpi->source->ts_start);
  677. /* don't want to do output stats with a stack variable! */
  678. memcpy(&cpi->twopass.this_frame_stats, &fps, sizeof(FIRSTPASS_STATS));
  679. output_stats(cpi, cpi->output_pkt_list, &cpi->twopass.this_frame_stats);
  680. accumulate_stats(&cpi->twopass.total_stats, &fps);
  681. }
  682. /* Copy the previous Last Frame into the GF buffer if specific
  683. * conditions for doing so are met
  684. */
  685. if ((cm->current_video_frame > 0) &&
  686. (cpi->twopass.this_frame_stats.pcnt_inter > 0.20) &&
  687. ((cpi->twopass.this_frame_stats.intra_error /
  688. DOUBLE_DIVIDE_CHECK(cpi->twopass.this_frame_stats.coded_error)) >
  689. 2.0)) {
  690. vp8_yv12_copy_frame(lst_yv12, gld_yv12);
  691. }
  692. /* swap frame pointers so last frame refers to the frame we just
  693. * compressed
  694. */
  695. vp8_swap_yv12_buffer(lst_yv12, new_yv12);
  696. vp8_yv12_extend_frame_borders(lst_yv12);
  697. /* Special case for the first frame. Copy into the GF buffer as a
  698. * second reference.
  699. */
  700. if (cm->current_video_frame == 0) {
  701. vp8_yv12_copy_frame(lst_yv12, gld_yv12);
  702. }
  703. /* use this to see what the first pass reconstruction looks like */
  704. if (0) {
  705. char filename[512];
  706. FILE *recon_file;
  707. sprintf(filename, "enc%04d.yuv", (int)cm->current_video_frame);
  708. if (cm->current_video_frame == 0) {
  709. recon_file = fopen(filename, "wb");
  710. } else {
  711. recon_file = fopen(filename, "ab");
  712. }
  713. (void)fwrite(lst_yv12->buffer_alloc, lst_yv12->frame_size, 1, recon_file);
  714. fclose(recon_file);
  715. }
  716. cm->current_video_frame++;
  717. }
  718. extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
  719. /* Estimate a cost per mb attributable to overheads such as the coding of
  720. * modes and motion vectors.
  721. * Currently simplistic in its assumptions for testing.
  722. */
  723. static double bitcost(double prob) {
  724. if (prob > 0.000122) {
  725. return -log(prob) / log(2.0);
  726. } else {
  727. return 13.0;
  728. }
  729. }
  730. static int64_t estimate_modemvcost(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats) {
  731. int mv_cost;
  732. int64_t mode_cost;
  733. double av_pct_inter = fpstats->pcnt_inter / fpstats->count;
  734. double av_pct_motion = fpstats->pcnt_motion / fpstats->count;
  735. double av_intra = (1.0 - av_pct_inter);
  736. double zz_cost;
  737. double motion_cost;
  738. double intra_cost;
  739. zz_cost = bitcost(av_pct_inter - av_pct_motion);
  740. motion_cost = bitcost(av_pct_motion);
  741. intra_cost = bitcost(av_intra);
  742. /* Estimate of extra bits per mv overhead for mbs
  743. * << 9 is the normalization to the (bits * 512) used in vp8_bits_per_mb
  744. */
  745. mv_cost = ((int)(fpstats->new_mv_count / fpstats->count) * 8) << 9;
  746. /* Crude estimate of overhead cost from modes
  747. * << 9 is the normalization to (bits * 512) used in vp8_bits_per_mb
  748. */
  749. mode_cost =
  750. (int64_t)((((av_pct_inter - av_pct_motion) * zz_cost) +
  751. (av_pct_motion * motion_cost) + (av_intra * intra_cost)) *
  752. cpi->common.MBs) *
  753. 512;
  754. return mv_cost + mode_cost;
  755. }
  756. static double calc_correction_factor(double err_per_mb, double err_devisor,
  757. double pt_low, double pt_high, int Q) {
  758. double power_term;
  759. double error_term = err_per_mb / err_devisor;
  760. double correction_factor;
  761. /* Adjustment based on Q to power term. */
  762. power_term = pt_low + (Q * 0.01);
  763. power_term = (power_term > pt_high) ? pt_high : power_term;
  764. /* Adjustments to error term */
  765. /* TBD */
  766. /* Calculate correction factor */
  767. correction_factor = pow(error_term, power_term);
  768. /* Clip range */
  769. correction_factor = (correction_factor < 0.05)
  770. ? 0.05
  771. : (correction_factor > 5.0) ? 5.0 : correction_factor;
  772. return correction_factor;
  773. }
  774. static int estimate_max_q(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats,
  775. int section_target_bandwitdh, int overhead_bits) {
  776. int Q;
  777. int num_mbs = cpi->common.MBs;
  778. int target_norm_bits_per_mb;
  779. double section_err = (fpstats->coded_error / fpstats->count);
  780. double err_per_mb = section_err / num_mbs;
  781. double err_correction_factor;
  782. double speed_correction = 1.0;
  783. int overhead_bits_per_mb;
  784. if (section_target_bandwitdh <= 0) {
  785. return cpi->twopass.maxq_max_limit; /* Highest value allowed */
  786. }
  787. target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
  788. ? (512 * section_target_bandwitdh) / num_mbs
  789. : 512 * (section_target_bandwitdh / num_mbs);
  790. /* Calculate a corrective factor based on a rolling ratio of bits spent
  791. * vs target bits
  792. */
  793. if ((cpi->rolling_target_bits > 0) &&
  794. (cpi->active_worst_quality < cpi->worst_quality)) {
  795. double rolling_ratio;
  796. rolling_ratio =
  797. (double)cpi->rolling_actual_bits / (double)cpi->rolling_target_bits;
  798. if (rolling_ratio < 0.95) {
  799. cpi->twopass.est_max_qcorrection_factor -= 0.005;
  800. } else if (rolling_ratio > 1.05) {
  801. cpi->twopass.est_max_qcorrection_factor += 0.005;
  802. }
  803. cpi->twopass.est_max_qcorrection_factor =
  804. (cpi->twopass.est_max_qcorrection_factor < 0.1)
  805. ? 0.1
  806. : (cpi->twopass.est_max_qcorrection_factor > 10.0)
  807. ? 10.0
  808. : cpi->twopass.est_max_qcorrection_factor;
  809. }
  810. /* Corrections for higher compression speed settings
  811. * (reduced compression expected)
  812. */
  813. if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
  814. if (cpi->oxcf.cpu_used <= 5) {
  815. speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
  816. } else {
  817. speed_correction = 1.25;
  818. }
  819. }
  820. /* Estimate of overhead bits per mb */
  821. /* Correction to overhead bits for min allowed Q. */
  822. overhead_bits_per_mb = overhead_bits / num_mbs;
  823. overhead_bits_per_mb = (int)(overhead_bits_per_mb *
  824. pow(0.98, (double)cpi->twopass.maxq_min_limit));
  825. /* Try and pick a max Q that will be high enough to encode the
  826. * content at the given rate.
  827. */
  828. for (Q = cpi->twopass.maxq_min_limit; Q < cpi->twopass.maxq_max_limit; ++Q) {
  829. int bits_per_mb_at_this_q;
  830. /* Error per MB based correction factor */
  831. err_correction_factor =
  832. calc_correction_factor(err_per_mb, 150.0, 0.40, 0.90, Q);
  833. bits_per_mb_at_this_q =
  834. vp8_bits_per_mb[INTER_FRAME][Q] + overhead_bits_per_mb;
  835. bits_per_mb_at_this_q =
  836. (int)(.5 + err_correction_factor * speed_correction *
  837. cpi->twopass.est_max_qcorrection_factor *
  838. cpi->twopass.section_max_qfactor *
  839. (double)bits_per_mb_at_this_q);
  840. /* Mode and motion overhead */
  841. /* As Q rises in real encode loop rd code will force overhead down
  842. * We make a crude adjustment for this here as *.98 per Q step.
  843. */
  844. overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);
  845. if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
  846. }
  847. /* Restriction on active max q for constrained quality mode. */
  848. if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
  849. (Q < cpi->cq_target_quality)) {
  850. Q = cpi->cq_target_quality;
  851. }
  852. /* Adjust maxq_min_limit and maxq_max_limit limits based on
  853. * average q observed in clip for non kf/gf.arf frames
  854. * Give average a chance to settle though.
  855. */
  856. if ((cpi->ni_frames > ((int)cpi->twopass.total_stats.count >> 8)) &&
  857. (cpi->ni_frames > 150)) {
  858. cpi->twopass.maxq_max_limit = ((cpi->ni_av_qi + 32) < cpi->worst_quality)
  859. ? (cpi->ni_av_qi + 32)
  860. : cpi->worst_quality;
  861. cpi->twopass.maxq_min_limit = ((cpi->ni_av_qi - 32) > cpi->best_quality)
  862. ? (cpi->ni_av_qi - 32)
  863. : cpi->best_quality;
  864. }
  865. return Q;
  866. }
  867. /* For cq mode estimate a cq level that matches the observed
  868. * complexity and data rate.
  869. */
  870. static int estimate_cq(VP8_COMP *cpi, FIRSTPASS_STATS *fpstats,
  871. int section_target_bandwitdh, int overhead_bits) {
  872. int Q;
  873. int num_mbs = cpi->common.MBs;
  874. int target_norm_bits_per_mb;
  875. double section_err = (fpstats->coded_error / fpstats->count);
  876. double err_per_mb = section_err / num_mbs;
  877. double err_correction_factor;
  878. double speed_correction = 1.0;
  879. double clip_iiratio;
  880. double clip_iifactor;
  881. int overhead_bits_per_mb;
  882. if (0) {
  883. FILE *f = fopen("epmp.stt", "a");
  884. fprintf(f, "%10.2f\n", err_per_mb);
  885. fclose(f);
  886. }
  887. target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
  888. ? (512 * section_target_bandwitdh) / num_mbs
  889. : 512 * (section_target_bandwitdh / num_mbs);
  890. /* Estimate of overhead bits per mb */
  891. overhead_bits_per_mb = overhead_bits / num_mbs;
  892. /* Corrections for higher compression speed settings
  893. * (reduced compression expected)
  894. */
  895. if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
  896. if (cpi->oxcf.cpu_used <= 5) {
  897. speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
  898. } else {
  899. speed_correction = 1.25;
  900. }
  901. }
  902. /* II ratio correction factor for clip as a whole */
  903. clip_iiratio = cpi->twopass.total_stats.intra_error /
  904. DOUBLE_DIVIDE_CHECK(cpi->twopass.total_stats.coded_error);
  905. clip_iifactor = 1.0 - ((clip_iiratio - 10.0) * 0.025);
  906. if (clip_iifactor < 0.80) clip_iifactor = 0.80;
  907. /* Try and pick a Q that can encode the content at the given rate. */
  908. for (Q = 0; Q < MAXQ; ++Q) {
  909. int bits_per_mb_at_this_q;
  910. /* Error per MB based correction factor */
  911. err_correction_factor =
  912. calc_correction_factor(err_per_mb, 100.0, 0.40, 0.90, Q);
  913. bits_per_mb_at_this_q =
  914. vp8_bits_per_mb[INTER_FRAME][Q] + overhead_bits_per_mb;
  915. bits_per_mb_at_this_q =
  916. (int)(.5 + err_correction_factor * speed_correction * clip_iifactor *
  917. (double)bits_per_mb_at_this_q);
  918. /* Mode and motion overhead */
  919. /* As Q rises in real encode loop rd code will force overhead down
  920. * We make a crude adjustment for this here as *.98 per Q step.
  921. */
  922. overhead_bits_per_mb = (int)((double)overhead_bits_per_mb * 0.98);
  923. if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
  924. }
  925. /* Clip value to range "best allowed to (worst allowed - 1)" */
  926. Q = cq_level[Q];
  927. if (Q >= cpi->worst_quality) Q = cpi->worst_quality - 1;
  928. if (Q < cpi->best_quality) Q = cpi->best_quality;
  929. return Q;
  930. }
  931. static int estimate_q(VP8_COMP *cpi, double section_err,
  932. int section_target_bandwitdh) {
  933. int Q;
  934. int num_mbs = cpi->common.MBs;
  935. int target_norm_bits_per_mb;
  936. double err_per_mb = section_err / num_mbs;
  937. double err_correction_factor;
  938. double speed_correction = 1.0;
  939. target_norm_bits_per_mb = (section_target_bandwitdh < (1 << 20))
  940. ? (512 * section_target_bandwitdh) / num_mbs
  941. : 512 * (section_target_bandwitdh / num_mbs);
  942. /* Corrections for higher compression speed settings
  943. * (reduced compression expected)
  944. */
  945. if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
  946. if (cpi->oxcf.cpu_used <= 5) {
  947. speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
  948. } else {
  949. speed_correction = 1.25;
  950. }
  951. }
  952. /* Try and pick a Q that can encode the content at the given rate. */
  953. for (Q = 0; Q < MAXQ; ++Q) {
  954. int bits_per_mb_at_this_q;
  955. /* Error per MB based correction factor */
  956. err_correction_factor =
  957. calc_correction_factor(err_per_mb, 150.0, 0.40, 0.90, Q);
  958. bits_per_mb_at_this_q =
  959. (int)(.5 + (err_correction_factor * speed_correction *
  960. cpi->twopass.est_max_qcorrection_factor *
  961. (double)vp8_bits_per_mb[INTER_FRAME][Q] / 1.0));
  962. if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
  963. }
  964. return Q;
  965. }
  966. /* Estimate a worst case Q for a KF group */
  967. static int estimate_kf_group_q(VP8_COMP *cpi, double section_err,
  968. int section_target_bandwitdh,
  969. double group_iiratio) {
  970. int Q;
  971. int num_mbs = cpi->common.MBs;
  972. int target_norm_bits_per_mb = (512 * section_target_bandwitdh) / num_mbs;
  973. int bits_per_mb_at_this_q;
  974. double err_per_mb = section_err / num_mbs;
  975. double err_correction_factor;
  976. double speed_correction = 1.0;
  977. double current_spend_ratio = 1.0;
  978. double pow_highq = (POW1 < 0.6) ? POW1 + 0.3 : 0.90;
  979. double pow_lowq = (POW1 < 0.7) ? POW1 + 0.1 : 0.80;
  980. double iiratio_correction_factor = 1.0;
  981. double combined_correction_factor;
  982. /* Trap special case where the target is <= 0 */
  983. if (target_norm_bits_per_mb <= 0) return MAXQ * 2;
  984. /* Calculate a corrective factor based on a rolling ratio of bits spent
  985. * vs target bits
  986. * This is clamped to the range 0.1 to 10.0
  987. */
  988. if (cpi->long_rolling_target_bits <= 0) {
  989. current_spend_ratio = 10.0;
  990. } else {
  991. current_spend_ratio = (double)cpi->long_rolling_actual_bits /
  992. (double)cpi->long_rolling_target_bits;
  993. current_spend_ratio =
  994. (current_spend_ratio > 10.0)
  995. ? 10.0
  996. : (current_spend_ratio < 0.1) ? 0.1 : current_spend_ratio;
  997. }
  998. /* Calculate a correction factor based on the quality of prediction in
  999. * the sequence as indicated by intra_inter error score ratio (IIRatio)
  1000. * The idea here is to favour subsampling in the hardest sections vs
  1001. * the easyest.
  1002. */
  1003. iiratio_correction_factor = 1.0 - ((group_iiratio - 6.0) * 0.1);
  1004. if (iiratio_correction_factor < 0.5) iiratio_correction_factor = 0.5;
  1005. /* Corrections for higher compression speed settings
  1006. * (reduced compression expected)
  1007. */
  1008. if ((cpi->compressor_speed == 3) || (cpi->compressor_speed == 1)) {
  1009. if (cpi->oxcf.cpu_used <= 5) {
  1010. speed_correction = 1.04 + (cpi->oxcf.cpu_used * 0.04);
  1011. } else {
  1012. speed_correction = 1.25;
  1013. }
  1014. }
  1015. /* Combine the various factors calculated above */
  1016. combined_correction_factor =
  1017. speed_correction * iiratio_correction_factor * current_spend_ratio;
  1018. /* Try and pick a Q that should be high enough to encode the content at
  1019. * the given rate.
  1020. */
  1021. for (Q = 0; Q < MAXQ; ++Q) {
  1022. /* Error per MB based correction factor */
  1023. err_correction_factor =
  1024. calc_correction_factor(err_per_mb, 150.0, pow_lowq, pow_highq, Q);
  1025. bits_per_mb_at_this_q =
  1026. (int)(.5 + (err_correction_factor * combined_correction_factor *
  1027. (double)vp8_bits_per_mb[INTER_FRAME][Q]));
  1028. if (bits_per_mb_at_this_q <= target_norm_bits_per_mb) break;
  1029. }
  1030. /* If we could not hit the target even at Max Q then estimate what Q
  1031. * would have been required
  1032. */
  1033. while ((bits_per_mb_at_this_q > target_norm_bits_per_mb) &&
  1034. (Q < (MAXQ * 2))) {
  1035. bits_per_mb_at_this_q = (int)(0.96 * bits_per_mb_at_this_q);
  1036. Q++;
  1037. }
  1038. if (0) {
  1039. FILE *f = fopen("estkf_q.stt", "a");
  1040. fprintf(f, "%8d %8d %8d %8.2f %8.3f %8.2f %8.3f %8.3f %8.3f %8d\n",
  1041. cpi->common.current_video_frame, bits_per_mb_at_this_q,
  1042. target_norm_bits_per_mb, err_per_mb, err_correction_factor,
  1043. current_spend_ratio, group_iiratio, iiratio_correction_factor,
  1044. (double)cpi->buffer_level / (double)cpi->oxcf.optimal_buffer_level,
  1045. Q);
  1046. fclose(f);
  1047. }
  1048. return Q;
  1049. }
  1050. void vp8_init_second_pass(VP8_COMP *cpi) {
  1051. FIRSTPASS_STATS this_frame;
  1052. FIRSTPASS_STATS *start_pos;
  1053. double two_pass_min_rate = (double)(cpi->oxcf.target_bandwidth *
  1054. cpi->oxcf.two_pass_vbrmin_section / 100);
  1055. zero_stats(&cpi->twopass.total_stats);
  1056. zero_stats(&cpi->twopass.total_left_stats);
  1057. if (!cpi->twopass.stats_in_end) return;
  1058. cpi->twopass.total_stats = *cpi->twopass.stats_in_end;
  1059. cpi->twopass.total_left_stats = cpi->twopass.total_stats;
  1060. /* each frame can have a different duration, as the frame rate in the
  1061. * source isn't guaranteed to be constant. The frame rate prior to
  1062. * the first frame encoded in the second pass is a guess. However the
  1063. * sum duration is not. Its calculated based on the actual durations of
  1064. * all frames from the first pass.
  1065. */
  1066. vp8_new_framerate(cpi, 10000000.0 * cpi->twopass.total_stats.count /
  1067. cpi->twopass.total_stats.duration);
  1068. cpi->output_framerate = cpi->framerate;
  1069. cpi->twopass.bits_left = (int64_t)(cpi->twopass.total_stats.duration *
  1070. cpi->oxcf.target_bandwidth / 10000000.0);
  1071. cpi->twopass.bits_left -= (int64_t)(cpi->twopass.total_stats.duration *
  1072. two_pass_min_rate / 10000000.0);
  1073. /* Calculate a minimum intra value to be used in determining the IIratio
  1074. * scores used in the second pass. We have this minimum to make sure
  1075. * that clips that are static but "low complexity" in the intra domain
  1076. * are still boosted appropriately for KF/GF/ARF
  1077. */
  1078. cpi->twopass.kf_intra_err_min = KF_MB_INTRA_MIN * cpi->common.MBs;
  1079. cpi->twopass.gf_intra_err_min = GF_MB_INTRA_MIN * cpi->common.MBs;
  1080. /* Scan the first pass file and calculate an average Intra / Inter error
  1081. * score ratio for the sequence
  1082. */
  1083. {
  1084. double sum_iiratio = 0.0;
  1085. double IIRatio;
  1086. start_pos = cpi->twopass.stats_in; /* Note starting "file" position */
  1087. while (input_stats(cpi, &this_frame) != EOF) {
  1088. IIRatio =
  1089. this_frame.intra_error / DOUBLE_DIVIDE_CHECK(this_frame.coded_error);
  1090. IIRatio = (IIRatio < 1.0) ? 1.0 : (IIRatio > 20.0) ? 20.0 : IIRatio;
  1091. sum_iiratio += IIRatio;
  1092. }
  1093. cpi->twopass.avg_iiratio =
  1094. sum_iiratio /
  1095. DOUBLE_DIVIDE_CHECK((double)cpi->twopass.total_stats.count);
  1096. /* Reset file position */
  1097. reset_fpf_position(cpi, start_pos);
  1098. }
  1099. /* Scan the first pass file and calculate a modified total error based
  1100. * upon the bias/power function used to allocate bits
  1101. */
  1102. {
  1103. start_pos = cpi->twopass.stats_in; /* Note starting "file" position */
  1104. cpi->twopass.modified_error_total = 0.0;
  1105. cpi->twopass.modified_error_used = 0.0;
  1106. while (input_stats(cpi, &this_frame) != EOF) {
  1107. cpi->twopass.modified_error_total +=
  1108. calculate_modified_err(cpi, &this_frame);
  1109. }
  1110. cpi->twopass.modified_error_left = cpi->twopass.modified_error_total;
  1111. reset_fpf_position(cpi, start_pos); /* Reset file position */
  1112. }
  1113. }
  1114. void vp8_end_second_pass(VP8_COMP *cpi) { (void)cpi; }
  1115. /* This function gives and estimate of how badly we believe the prediction
  1116. * quality is decaying from frame to frame.
  1117. */
  1118. static double get_prediction_decay_rate(VP8_COMP *cpi,
  1119. FIRSTPASS_STATS *next_frame) {
  1120. double prediction_decay_rate;
  1121. double motion_decay;
  1122. double motion_pct = next_frame->pcnt_motion;
  1123. (void)cpi;
  1124. /* Initial basis is the % mbs inter coded */
  1125. prediction_decay_rate = next_frame->pcnt_inter;
  1126. /* High % motion -> somewhat higher decay rate */
  1127. motion_decay = (1.0 - (motion_pct / 20.0));
  1128. if (motion_decay < prediction_decay_rate) {
  1129. prediction_decay_rate = motion_decay;
  1130. }
  1131. /* Adjustment to decay rate based on speed of motion */
  1132. {
  1133. double this_mv_rabs;
  1134. double this_mv_cabs;
  1135. double distance_factor;
  1136. this_mv_rabs = fabs(next_frame->mvr_abs * motion_pct);
  1137. this_mv_cabs = fabs(next_frame->mvc_abs * motion_pct);
  1138. distance_factor =
  1139. sqrt((this_mv_rabs * this_mv_rabs) + (this_mv_cabs * this_mv_cabs)) /
  1140. 250.0;
  1141. distance_factor = ((distance_factor > 1.0) ? 0.0 : (1.0 - distance_factor));
  1142. if (distance_factor < prediction_decay_rate) {
  1143. prediction_decay_rate = distance_factor;
  1144. }
  1145. }
  1146. return prediction_decay_rate;
  1147. }
  1148. /* Function to test for a condition where a complex transition is followed
  1149. * by a static section. For example in slide shows where there is a fade
  1150. * between slides. This is to help with more optimal kf and gf positioning.
  1151. */
  1152. static int detect_transition_to_still(VP8_COMP *cpi, int frame_interval,
  1153. int still_interval,
  1154. double loop_decay_rate,
  1155. double decay_accumulator) {
  1156. int trans_to_still = 0;
  1157. /* Break clause to detect very still sections after motion
  1158. * For example a static image after a fade or other transition
  1159. * instead of a clean scene cut.
  1160. */
  1161. if ((frame_interval > MIN_GF_INTERVAL) && (loop_decay_rate >= 0.999) &&
  1162. (decay_accumulator < 0.9)) {
  1163. int j;
  1164. FIRSTPASS_STATS *position = cpi->twopass.stats_in;
  1165. FIRSTPASS_STATS tmp_next_frame;
  1166. double decay_rate;
  1167. /* Look ahead a few frames to see if static condition persists... */
  1168. for (j = 0; j < still_interval; ++j) {
  1169. if (EOF == input_stats(cpi, &tmp_next_frame)) break;
  1170. decay_rate = get_prediction_decay_rate(cpi, &tmp_next_frame);
  1171. if (decay_rate < 0.999) break;
  1172. }
  1173. /* Reset file position */
  1174. reset_fpf_position(cpi, position);
  1175. /* Only if it does do we signal a transition to still */
  1176. if (j == still_interval) trans_to_still = 1;
  1177. }
  1178. return trans_to_still;
  1179. }
  1180. /* This function detects a flash through the high relative pcnt_second_ref
  1181. * score in the frame following a flash frame. The offset passed in should
  1182. * reflect this
  1183. */
  1184. static int detect_flash(VP8_COMP *cpi, int offset) {
  1185. FIRSTPASS_STATS next_frame;
  1186. int flash_detected = 0;
  1187. /* Read the frame data. */
  1188. /* The return is 0 (no flash detected) if not a valid frame */
  1189. if (read_frame_stats(cpi, &next_frame, offset) != EOF) {
  1190. /* What we are looking for here is a situation where there is a
  1191. * brief break in prediction (such as a flash) but subsequent frames
  1192. * are reasonably well predicted by an earlier (pre flash) frame.
  1193. * The recovery after a flash is indicated by a high pcnt_second_ref
  1194. * comapred to pcnt_inter.
  1195. */
  1196. if ((next_frame.pcnt_second_ref > next_frame.pcnt_inter) &&
  1197. (next_frame.pcnt_second_ref >= 0.5)) {
  1198. flash_detected = 1;
  1199. /*if (1)
  1200. {
  1201. FILE *f = fopen("flash.stt", "a");
  1202. fprintf(f, "%8.0f %6.2f %6.2f\n",
  1203. next_frame.frame,
  1204. next_frame.pcnt_inter,
  1205. next_frame.pcnt_second_ref);
  1206. fclose(f);
  1207. }*/
  1208. }
  1209. }
  1210. return flash_detected;
  1211. }
  1212. /* Update the motion related elements to the GF arf boost calculation */
  1213. static void accumulate_frame_motion_stats(VP8_COMP *cpi,
  1214. FIRSTPASS_STATS *this_frame,
  1215. double *this_frame_mv_in_out,
  1216. double *mv_in_out_accumulator,
  1217. double *abs_mv_in_out_accumulator,
  1218. double *mv_ratio_accumulator) {
  1219. double this_frame_mvr_ratio;
  1220. double this_frame_mvc_ratio;
  1221. double motion_pct;
  1222. (void)cpi;
  1223. /* Accumulate motion stats. */
  1224. motion_pct = this_frame->pcnt_motion;
  1225. /* Accumulate Motion In/Out of frame stats */
  1226. *this_frame_mv_in_out = this_frame->mv_in_out_count * motion_pct;
  1227. *mv_in_out_accumulator += this_frame->mv_in_out_count * motion_pct;
  1228. *abs_mv_in_out_accumulator += fabs(this_frame->mv_in_out_count * motion_pct);
  1229. /* Accumulate a measure of how uniform (or conversely how random)
  1230. * the motion field is. (A ratio of absmv / mv)
  1231. */
  1232. if (motion_pct > 0.05) {
  1233. this_frame_mvr_ratio =
  1234. fabs(this_frame->mvr_abs) / DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVr));
  1235. this_frame_mvc_ratio =
  1236. fabs(this_frame->mvc_abs) / DOUBLE_DIVIDE_CHECK(fabs(this_frame->MVc));
  1237. *mv_ratio_accumulator += (this_frame_mvr_ratio < this_frame->mvr_abs)
  1238. ? (this_frame_mvr_ratio * motion_pct)
  1239. : this_frame->mvr_abs * motion_pct;
  1240. *mv_ratio_accumulator += (this_frame_mvc_ratio < this_frame->mvc_abs)
  1241. ? (this_frame_mvc_ratio * motion_pct)
  1242. : this_frame->mvc_abs * motion_pct;
  1243. }
  1244. }
  1245. /* Calculate a baseline boost number for the current frame. */
  1246. static double calc_frame_boost(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame,
  1247. double this_frame_mv_in_out) {
  1248. double frame_boost;
  1249. /* Underlying boost factor is based on inter intra error ratio */
  1250. if (this_frame->intra_error > cpi->twopass.gf_intra_err_min) {
  1251. frame_boost = (IIFACTOR * this_frame->intra_error /
  1252. DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
  1253. } else {
  1254. frame_boost = (IIFACTOR * cpi->twopass.gf_intra_err_min /
  1255. DOUBLE_DIVIDE_CHECK(this_frame->coded_error));
  1256. }
  1257. /* Increase boost for frames where new data coming into frame
  1258. * (eg zoom out). Slightly reduce boost if there is a net balance
  1259. * of motion out of the frame (zoom in).
  1260. * The range for this_frame_mv_in_out is -1.0 to +1.0
  1261. */
  1262. if (this_frame_mv_in_out > 0.0) {
  1263. frame_boost += frame_boost * (this_frame_mv_in_out * 2.0);
  1264. /* In extreme case boost is halved */
  1265. } else {
  1266. frame_boost += frame_boost * (this_frame_mv_in_out / 2.0);
  1267. }
  1268. /* Clip to maximum */
  1269. if (frame_boost > GF_RMAX) frame_boost = GF_RMAX;
  1270. return frame_boost;
  1271. }
  1272. #if NEW_BOOST
  1273. static int calc_arf_boost(VP8_COMP *cpi, int offset, int f_frames, int b_frames,
  1274. int *f_boost, int *b_boost) {
  1275. FIRSTPASS_STATS this_frame;
  1276. int i;
  1277. double boost_score = 0.0;
  1278. double mv_ratio_accumulator = 0.0;
  1279. double decay_accumulator = 1.0;
  1280. double this_frame_mv_in_out = 0.0;
  1281. double mv_in_out_accumulator = 0.0;
  1282. double abs_mv_in_out_accumulator = 0.0;
  1283. double r;
  1284. int flash_detected = 0;
  1285. /* Search forward from the proposed arf/next gf position */
  1286. for (i = 0; i < f_frames; ++i) {
  1287. if (read_frame_stats(cpi, &this_frame, (i + offset)) == EOF) break;
  1288. /* Update the motion related elements to the boost calculation */
  1289. accumulate_frame_motion_stats(
  1290. cpi, &this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1291. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1292. /* Calculate the baseline boost number for this frame */
  1293. r = calc_frame_boost(cpi, &this_frame, this_frame_mv_in_out);
  1294. /* We want to discount the the flash frame itself and the recovery
  1295. * frame that follows as both will have poor scores.
  1296. */
  1297. flash_detected =
  1298. detect_flash(cpi, (i + offset)) || detect_flash(cpi, (i + offset + 1));
  1299. /* Cumulative effect of prediction quality decay */
  1300. if (!flash_detected) {
  1301. decay_accumulator =
  1302. decay_accumulator * get_prediction_decay_rate(cpi, &this_frame);
  1303. decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
  1304. }
  1305. boost_score += (decay_accumulator * r);
  1306. /* Break out conditions. */
  1307. if ((!flash_detected) &&
  1308. ((mv_ratio_accumulator > 100.0) || (abs_mv_in_out_accumulator > 3.0) ||
  1309. (mv_in_out_accumulator < -2.0))) {
  1310. break;
  1311. }
  1312. }
  1313. *f_boost = (int)(boost_score * 100.0) >> 4;
  1314. /* Reset for backward looking loop */
  1315. boost_score = 0.0;
  1316. mv_ratio_accumulator = 0.0;
  1317. decay_accumulator = 1.0;
  1318. this_frame_mv_in_out = 0.0;
  1319. mv_in_out_accumulator = 0.0;
  1320. abs_mv_in_out_accumulator = 0.0;
  1321. /* Search forward from the proposed arf/next gf position */
  1322. for (i = -1; i >= -b_frames; i--) {
  1323. if (read_frame_stats(cpi, &this_frame, (i + offset)) == EOF) break;
  1324. /* Update the motion related elements to the boost calculation */
  1325. accumulate_frame_motion_stats(
  1326. cpi, &this_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1327. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1328. /* Calculate the baseline boost number for this frame */
  1329. r = calc_frame_boost(cpi, &this_frame, this_frame_mv_in_out);
  1330. /* We want to discount the the flash frame itself and the recovery
  1331. * frame that follows as both will have poor scores.
  1332. */
  1333. flash_detected =
  1334. detect_flash(cpi, (i + offset)) || detect_flash(cpi, (i + offset + 1));
  1335. /* Cumulative effect of prediction quality decay */
  1336. if (!flash_detected) {
  1337. decay_accumulator =
  1338. decay_accumulator * get_prediction_decay_rate(cpi, &this_frame);
  1339. decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
  1340. }
  1341. boost_score += (decay_accumulator * r);
  1342. /* Break out conditions. */
  1343. if ((!flash_detected) &&
  1344. ((mv_ratio_accumulator > 100.0) || (abs_mv_in_out_accumulator > 3.0) ||
  1345. (mv_in_out_accumulator < -2.0))) {
  1346. break;
  1347. }
  1348. }
  1349. *b_boost = (int)(boost_score * 100.0) >> 4;
  1350. return (*f_boost + *b_boost);
  1351. }
  1352. #endif
  1353. /* Analyse and define a gf/arf group . */
  1354. static void define_gf_group(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
  1355. FIRSTPASS_STATS next_frame;
  1356. FIRSTPASS_STATS *start_pos;
  1357. int i;
  1358. double r;
  1359. double boost_score = 0.0;
  1360. double old_boost_score = 0.0;
  1361. double gf_group_err = 0.0;
  1362. double gf_first_frame_err = 0.0;
  1363. double mod_frame_err = 0.0;
  1364. double mv_ratio_accumulator = 0.0;
  1365. double decay_accumulator = 1.0;
  1366. double loop_decay_rate = 1.00; /* Starting decay rate */
  1367. double this_frame_mv_in_out = 0.0;
  1368. double mv_in_out_accumulator = 0.0;
  1369. double abs_mv_in_out_accumulator = 0.0;
  1370. double mod_err_per_mb_accumulator = 0.0;
  1371. int max_bits = frame_max_bits(cpi); /* Max for a single frame */
  1372. unsigned int allow_alt_ref =
  1373. cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames;
  1374. int alt_boost = 0;
  1375. int f_boost = 0;
  1376. int b_boost = 0;
  1377. int flash_detected;
  1378. cpi->twopass.gf_group_bits = 0;
  1379. cpi->twopass.gf_decay_rate = 0;
  1380. vpx_clear_system_state();
  1381. start_pos = cpi->twopass.stats_in;
  1382. memset(&next_frame, 0, sizeof(next_frame)); /* assure clean */
  1383. /* Load stats for the current frame. */
  1384. mod_frame_err = calculate_modified_err(cpi, this_frame);
  1385. /* Note the error of the frame at the start of the group (this will be
  1386. * the GF frame error if we code a normal gf
  1387. */
  1388. gf_first_frame_err = mod_frame_err;
  1389. /* Special treatment if the current frame is a key frame (which is also
  1390. * a gf). If it is then its error score (and hence bit allocation) need
  1391. * to be subtracted out from the calculation for the GF group
  1392. */
  1393. if (cpi->common.frame_type == KEY_FRAME) gf_group_err -= gf_first_frame_err;
  1394. /* Scan forward to try and work out how many frames the next gf group
  1395. * should contain and what level of boost is appropriate for the GF
  1396. * or ARF that will be coded with the group
  1397. */
  1398. i = 0;
  1399. while (((i < cpi->twopass.static_scene_max_gf_interval) ||
  1400. ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL)) &&
  1401. (i < cpi->twopass.frames_to_key)) {
  1402. i++;
  1403. /* Accumulate error score of frames in this gf group */
  1404. mod_frame_err = calculate_modified_err(cpi, this_frame);
  1405. gf_group_err += mod_frame_err;
  1406. mod_err_per_mb_accumulator +=
  1407. mod_frame_err / DOUBLE_DIVIDE_CHECK((double)cpi->common.MBs);
  1408. if (EOF == input_stats(cpi, &next_frame)) break;
  1409. /* Test for the case where there is a brief flash but the prediction
  1410. * quality back to an earlier frame is then restored.
  1411. */
  1412. flash_detected = detect_flash(cpi, 0);
  1413. /* Update the motion related elements to the boost calculation */
  1414. accumulate_frame_motion_stats(
  1415. cpi, &next_frame, &this_frame_mv_in_out, &mv_in_out_accumulator,
  1416. &abs_mv_in_out_accumulator, &mv_ratio_accumulator);
  1417. /* Calculate a baseline boost number for this frame */
  1418. r = calc_frame_boost(cpi, &next_frame, this_frame_mv_in_out);
  1419. /* Cumulative effect of prediction quality decay */
  1420. if (!flash_detected) {
  1421. loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
  1422. decay_accumulator = decay_accumulator * loop_decay_rate;
  1423. decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
  1424. }
  1425. boost_score += (decay_accumulator * r);
  1426. /* Break clause to detect very still sections after motion
  1427. * For example a staic image after a fade or other transition.
  1428. */
  1429. if (detect_transition_to_still(cpi, i, 5, loop_decay_rate,
  1430. decay_accumulator)) {
  1431. allow_alt_ref = 0;
  1432. boost_score = old_boost_score;
  1433. break;
  1434. }
  1435. /* Break out conditions. */
  1436. if (
  1437. /* Break at cpi->max_gf_interval unless almost totally static */
  1438. (i >= cpi->max_gf_interval && (decay_accumulator < 0.995)) ||
  1439. (
  1440. /* Dont break out with a very short interval */
  1441. (i > MIN_GF_INTERVAL) &&
  1442. /* Dont break out very close to a key frame */
  1443. ((cpi->twopass.frames_to_key - i) >= MIN_GF_INTERVAL) &&
  1444. ((boost_score > 20.0) || (next_frame.pcnt_inter < 0.75)) &&
  1445. (!flash_detected) &&
  1446. ((mv_ratio_accumulator > 100.0) ||
  1447. (abs_mv_in_out_accumulator > 3.0) ||
  1448. (mv_in_out_accumulator < -2.0) ||
  1449. ((boost_score - old_boost_score) < 2.0)))) {
  1450. boost_score = old_boost_score;
  1451. break;
  1452. }
  1453. memcpy(this_frame, &next_frame, sizeof(*this_frame));
  1454. old_boost_score = boost_score;
  1455. }
  1456. cpi->twopass.gf_decay_rate =
  1457. (i > 0) ? (int)(100.0 * (1.0 - decay_accumulator)) / i : 0;
  1458. /* When using CBR apply additional buffer related upper limits */
  1459. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  1460. double max_boost;
  1461. /* For cbr apply buffer related limits */
  1462. if (cpi->drop_frames_allowed) {
  1463. int64_t df_buffer_level = cpi->oxcf.drop_frames_water_mark *
  1464. (cpi->oxcf.optimal_buffer_level / 100);
  1465. if (cpi->buffer_level > df_buffer_level) {
  1466. max_boost =
  1467. ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) /
  1468. DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
  1469. } else {
  1470. max_boost = 0.0;
  1471. }
  1472. } else if (cpi->buffer_level > 0) {
  1473. max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) /
  1474. DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
  1475. } else {
  1476. max_boost = 0.0;
  1477. }
  1478. if (boost_score > max_boost) boost_score = max_boost;
  1479. }
  1480. /* Dont allow conventional gf too near the next kf */
  1481. if ((cpi->twopass.frames_to_key - i) < MIN_GF_INTERVAL) {
  1482. while (i < cpi->twopass.frames_to_key) {
  1483. i++;
  1484. if (EOF == input_stats(cpi, this_frame)) break;
  1485. if (i < cpi->twopass.frames_to_key) {
  1486. mod_frame_err = calculate_modified_err(cpi, this_frame);
  1487. gf_group_err += mod_frame_err;
  1488. }
  1489. }
  1490. }
  1491. cpi->gfu_boost = (int)(boost_score * 100.0) >> 4;
  1492. #if NEW_BOOST
  1493. /* Alterrnative boost calculation for alt ref */
  1494. alt_boost = calc_arf_boost(cpi, 0, (i - 1), (i - 1), &f_boost, &b_boost);
  1495. #endif
  1496. /* Should we use the alternate refernce frame */
  1497. if (allow_alt_ref && (i >= MIN_GF_INTERVAL) &&
  1498. /* dont use ARF very near next kf */
  1499. (i <= (cpi->twopass.frames_to_key - MIN_GF_INTERVAL)) &&
  1500. #if NEW_BOOST
  1501. ((next_frame.pcnt_inter > 0.75) || (next_frame.pcnt_second_ref > 0.5)) &&
  1502. ((mv_in_out_accumulator / (double)i > -0.2) ||
  1503. (mv_in_out_accumulator > -2.0)) &&
  1504. (b_boost > 100) && (f_boost > 100))
  1505. #else
  1506. (next_frame.pcnt_inter > 0.75) &&
  1507. ((mv_in_out_accumulator / (double)i > -0.2) ||
  1508. (mv_in_out_accumulator > -2.0)) &&
  1509. (cpi->gfu_boost > 100) &&
  1510. (cpi->twopass.gf_decay_rate <=
  1511. (ARF_DECAY_THRESH + (cpi->gfu_boost / 200))))
  1512. #endif
  1513. {
  1514. int Boost;
  1515. int allocation_chunks;
  1516. int Q =
  1517. (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
  1518. int tmp_q;
  1519. int arf_frame_bits = 0;
  1520. int group_bits;
  1521. #if NEW_BOOST
  1522. cpi->gfu_boost = alt_boost;
  1523. #endif
  1524. /* Estimate the bits to be allocated to the group as a whole */
  1525. if ((cpi->twopass.kf_group_bits > 0) &&
  1526. (cpi->twopass.kf_group_error_left > 0)) {
  1527. group_bits =
  1528. (int)((double)cpi->twopass.kf_group_bits *
  1529. (gf_group_err / (double)cpi->twopass.kf_group_error_left));
  1530. } else {
  1531. group_bits = 0;
  1532. }
  1533. /* Boost for arf frame */
  1534. #if NEW_BOOST
  1535. Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
  1536. #else
  1537. Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
  1538. #endif
  1539. Boost += (i * 50);
  1540. /* Set max and minimum boost and hence minimum allocation */
  1541. if (Boost > ((cpi->baseline_gf_interval + 1) * 200)) {
  1542. Boost = ((cpi->baseline_gf_interval + 1) * 200);
  1543. } else if (Boost < 125) {
  1544. Boost = 125;
  1545. }
  1546. allocation_chunks = (i * 100) + Boost;
  1547. /* Normalize Altboost and allocations chunck down to prevent overflow */
  1548. while (Boost > 1000) {
  1549. Boost /= 2;
  1550. allocation_chunks /= 2;
  1551. }
  1552. /* Calculate the number of bits to be spent on the arf based on the
  1553. * boost number
  1554. */
  1555. arf_frame_bits =
  1556. (int)((double)Boost * (group_bits / (double)allocation_chunks));
  1557. /* Estimate if there are enough bits available to make worthwhile use
  1558. * of an arf.
  1559. */
  1560. tmp_q = estimate_q(cpi, mod_frame_err, (int)arf_frame_bits);
  1561. /* Only use an arf if it is likely we will be able to code
  1562. * it at a lower Q than the surrounding frames.
  1563. */
  1564. if (tmp_q < cpi->worst_quality) {
  1565. int half_gf_int;
  1566. int frames_after_arf;
  1567. int frames_bwd = cpi->oxcf.arnr_max_frames - 1;
  1568. int frames_fwd = cpi->oxcf.arnr_max_frames - 1;
  1569. cpi->source_alt_ref_pending = 1;
  1570. /*
  1571. * For alt ref frames the error score for the end frame of the
  1572. * group (the alt ref frame) should not contribute to the group
  1573. * total and hence the number of bit allocated to the group.
  1574. * Rather it forms part of the next group (it is the GF at the
  1575. * start of the next group)
  1576. * gf_group_err -= mod_frame_err;
  1577. *
  1578. * For alt ref frames alt ref frame is technically part of the
  1579. * GF frame for the next group but we always base the error
  1580. * calculation and bit allocation on the current group of frames.
  1581. *
  1582. * Set the interval till the next gf or arf.
  1583. * For ARFs this is the number of frames to be coded before the
  1584. * future frame that is coded as an ARF.
  1585. * The future frame itself is part of the next group
  1586. */
  1587. cpi->baseline_gf_interval = i;
  1588. /*
  1589. * Define the arnr filter width for this group of frames:
  1590. * We only filter frames that lie within a distance of half
  1591. * the GF interval from the ARF frame. We also have to trap
  1592. * cases where the filter extends beyond the end of clip.
  1593. * Note: this_frame->frame has been updated in the loop
  1594. * so it now points at the ARF frame.
  1595. */
  1596. half_gf_int = cpi->baseline_gf_interval >> 1;
  1597. frames_after_arf =
  1598. (int)(cpi->twopass.total_stats.count - this_frame->frame - 1);
  1599. switch (cpi->oxcf.arnr_type) {
  1600. case 1: /* Backward filter */
  1601. frames_fwd = 0;
  1602. if (frames_bwd > half_gf_int) frames_bwd = half_gf_int;
  1603. break;
  1604. case 2: /* Forward filter */
  1605. if (frames_fwd > half_gf_int) frames_fwd = half_gf_int;
  1606. if (frames_fwd > frames_after_arf) frames_fwd = frames_after_arf;
  1607. frames_bwd = 0;
  1608. break;
  1609. case 3: /* Centered filter */
  1610. default:
  1611. frames_fwd >>= 1;
  1612. if (frames_fwd > frames_after_arf) frames_fwd = frames_after_arf;
  1613. if (frames_fwd > half_gf_int) frames_fwd = half_gf_int;
  1614. frames_bwd = frames_fwd;
  1615. /* For even length filter there is one more frame backward
  1616. * than forward: e.g. len=6 ==> bbbAff, len=7 ==> bbbAfff.
  1617. */
  1618. if (frames_bwd < half_gf_int) {
  1619. frames_bwd += (cpi->oxcf.arnr_max_frames + 1) & 0x1;
  1620. }
  1621. break;
  1622. }
  1623. cpi->active_arnr_frames = frames_bwd + 1 + frames_fwd;
  1624. } else {
  1625. cpi->source_alt_ref_pending = 0;
  1626. cpi->baseline_gf_interval = i;
  1627. }
  1628. } else {
  1629. cpi->source_alt_ref_pending = 0;
  1630. cpi->baseline_gf_interval = i;
  1631. }
  1632. /*
  1633. * Now decide how many bits should be allocated to the GF group as a
  1634. * proportion of those remaining in the kf group.
  1635. * The final key frame group in the clip is treated as a special case
  1636. * where cpi->twopass.kf_group_bits is tied to cpi->twopass.bits_left.
  1637. * This is also important for short clips where there may only be one
  1638. * key frame.
  1639. */
  1640. if (cpi->twopass.frames_to_key >=
  1641. (int)(cpi->twopass.total_stats.count - cpi->common.current_video_frame)) {
  1642. cpi->twopass.kf_group_bits =
  1643. (cpi->twopass.bits_left > 0) ? cpi->twopass.bits_left : 0;
  1644. }
  1645. /* Calculate the bits to be allocated to the group as a whole */
  1646. if ((cpi->twopass.kf_group_bits > 0) &&
  1647. (cpi->twopass.kf_group_error_left > 0)) {
  1648. cpi->twopass.gf_group_bits =
  1649. (int64_t)(cpi->twopass.kf_group_bits *
  1650. (gf_group_err / cpi->twopass.kf_group_error_left));
  1651. } else {
  1652. cpi->twopass.gf_group_bits = 0;
  1653. }
  1654. cpi->twopass.gf_group_bits =
  1655. (cpi->twopass.gf_group_bits < 0)
  1656. ? 0
  1657. : (cpi->twopass.gf_group_bits > cpi->twopass.kf_group_bits)
  1658. ? cpi->twopass.kf_group_bits
  1659. : cpi->twopass.gf_group_bits;
  1660. /* Clip cpi->twopass.gf_group_bits based on user supplied data rate
  1661. * variability limit (cpi->oxcf.two_pass_vbrmax_section)
  1662. */
  1663. if (cpi->twopass.gf_group_bits >
  1664. (int64_t)max_bits * cpi->baseline_gf_interval) {
  1665. cpi->twopass.gf_group_bits = (int64_t)max_bits * cpi->baseline_gf_interval;
  1666. }
  1667. /* Reset the file position */
  1668. reset_fpf_position(cpi, start_pos);
  1669. /* Update the record of error used so far (only done once per gf group) */
  1670. cpi->twopass.modified_error_used += gf_group_err;
  1671. /* Assign bits to the arf or gf. */
  1672. for (i = 0; i <= (cpi->source_alt_ref_pending &&
  1673. cpi->common.frame_type != KEY_FRAME);
  1674. i++) {
  1675. int Boost;
  1676. int allocation_chunks;
  1677. int Q =
  1678. (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
  1679. int gf_bits;
  1680. /* For ARF frames */
  1681. if (cpi->source_alt_ref_pending && i == 0) {
  1682. #if NEW_BOOST
  1683. Boost = (alt_boost * GFQ_ADJUSTMENT) / 100;
  1684. #else
  1685. Boost = (cpi->gfu_boost * 3 * GFQ_ADJUSTMENT) / (2 * 100);
  1686. #endif
  1687. Boost += (cpi->baseline_gf_interval * 50);
  1688. /* Set max and minimum boost and hence minimum allocation */
  1689. if (Boost > ((cpi->baseline_gf_interval + 1) * 200)) {
  1690. Boost = ((cpi->baseline_gf_interval + 1) * 200);
  1691. } else if (Boost < 125) {
  1692. Boost = 125;
  1693. }
  1694. allocation_chunks = ((cpi->baseline_gf_interval + 1) * 100) + Boost;
  1695. }
  1696. /* Else for standard golden frames */
  1697. else {
  1698. /* boost based on inter / intra ratio of subsequent frames */
  1699. Boost = (cpi->gfu_boost * GFQ_ADJUSTMENT) / 100;
  1700. /* Set max and minimum boost and hence minimum allocation */
  1701. if (Boost > (cpi->baseline_gf_interval * 150)) {
  1702. Boost = (cpi->baseline_gf_interval * 150);
  1703. } else if (Boost < 125) {
  1704. Boost = 125;
  1705. }
  1706. allocation_chunks = (cpi->baseline_gf_interval * 100) + (Boost - 100);
  1707. }
  1708. /* Normalize Altboost and allocations chunck down to prevent overflow */
  1709. while (Boost > 1000) {
  1710. Boost /= 2;
  1711. allocation_chunks /= 2;
  1712. }
  1713. /* Calculate the number of bits to be spent on the gf or arf based on
  1714. * the boost number
  1715. */
  1716. gf_bits = (int)((double)Boost *
  1717. (cpi->twopass.gf_group_bits / (double)allocation_chunks));
  1718. /* If the frame that is to be boosted is simpler than the average for
  1719. * the gf/arf group then use an alternative calculation
  1720. * based on the error score of the frame itself
  1721. */
  1722. if (mod_frame_err < gf_group_err / (double)cpi->baseline_gf_interval) {
  1723. double alt_gf_grp_bits;
  1724. int alt_gf_bits;
  1725. alt_gf_grp_bits =
  1726. (double)cpi->twopass.kf_group_bits *
  1727. (mod_frame_err * (double)cpi->baseline_gf_interval) /
  1728. DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left);
  1729. alt_gf_bits =
  1730. (int)((double)Boost * (alt_gf_grp_bits / (double)allocation_chunks));
  1731. if (gf_bits > alt_gf_bits) {
  1732. gf_bits = alt_gf_bits;
  1733. }
  1734. }
  1735. /* Else if it is harder than other frames in the group make sure it at
  1736. * least receives an allocation in keeping with its relative error
  1737. * score, otherwise it may be worse off than an "un-boosted" frame
  1738. */
  1739. else {
  1740. int alt_gf_bits =
  1741. (int)((double)cpi->twopass.kf_group_bits * mod_frame_err /
  1742. DOUBLE_DIVIDE_CHECK((double)cpi->twopass.kf_group_error_left));
  1743. if (alt_gf_bits > gf_bits) {
  1744. gf_bits = alt_gf_bits;
  1745. }
  1746. }
  1747. /* Apply an additional limit for CBR */
  1748. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  1749. if (cpi->twopass.gf_bits > (int)(cpi->buffer_level >> 1)) {
  1750. cpi->twopass.gf_bits = (int)(cpi->buffer_level >> 1);
  1751. }
  1752. }
  1753. /* Dont allow a negative value for gf_bits */
  1754. if (gf_bits < 0) gf_bits = 0;
  1755. /* Add in minimum for a frame */
  1756. gf_bits += cpi->min_frame_bandwidth;
  1757. if (i == 0) {
  1758. cpi->twopass.gf_bits = gf_bits;
  1759. }
  1760. if (i == 1 || (!cpi->source_alt_ref_pending &&
  1761. (cpi->common.frame_type != KEY_FRAME))) {
  1762. /* Per frame bit target for this frame */
  1763. cpi->per_frame_bandwidth = gf_bits;
  1764. }
  1765. }
  1766. {
  1767. /* Adjust KF group bits and error remainin */
  1768. cpi->twopass.kf_group_error_left -= (int64_t)gf_group_err;
  1769. cpi->twopass.kf_group_bits -= cpi->twopass.gf_group_bits;
  1770. if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
  1771. /* Note the error score left in the remaining frames of the group.
  1772. * For normal GFs we want to remove the error score for the first
  1773. * frame of the group (except in Key frame case where this has
  1774. * already happened)
  1775. */
  1776. if (!cpi->source_alt_ref_pending && cpi->common.frame_type != KEY_FRAME) {
  1777. cpi->twopass.gf_group_error_left =
  1778. (int)(gf_group_err - gf_first_frame_err);
  1779. } else {
  1780. cpi->twopass.gf_group_error_left = (int)gf_group_err;
  1781. }
  1782. cpi->twopass.gf_group_bits -=
  1783. cpi->twopass.gf_bits - cpi->min_frame_bandwidth;
  1784. if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
  1785. /* This condition could fail if there are two kfs very close together
  1786. * despite (MIN_GF_INTERVAL) and would cause a devide by 0 in the
  1787. * calculation of cpi->twopass.alt_extra_bits.
  1788. */
  1789. if (cpi->baseline_gf_interval >= 3) {
  1790. #if NEW_BOOST
  1791. int boost = (cpi->source_alt_ref_pending) ? b_boost : cpi->gfu_boost;
  1792. #else
  1793. int boost = cpi->gfu_boost;
  1794. #endif
  1795. if (boost >= 150) {
  1796. int pct_extra;
  1797. pct_extra = (boost - 100) / 50;
  1798. pct_extra = (pct_extra > 20) ? 20 : pct_extra;
  1799. cpi->twopass.alt_extra_bits =
  1800. (int)(cpi->twopass.gf_group_bits * pct_extra) / 100;
  1801. cpi->twopass.gf_group_bits -= cpi->twopass.alt_extra_bits;
  1802. cpi->twopass.alt_extra_bits /= ((cpi->baseline_gf_interval - 1) >> 1);
  1803. } else {
  1804. cpi->twopass.alt_extra_bits = 0;
  1805. }
  1806. } else {
  1807. cpi->twopass.alt_extra_bits = 0;
  1808. }
  1809. }
  1810. /* Adjustments based on a measure of complexity of the section */
  1811. if (cpi->common.frame_type != KEY_FRAME) {
  1812. FIRSTPASS_STATS sectionstats;
  1813. double Ratio;
  1814. zero_stats(&sectionstats);
  1815. reset_fpf_position(cpi, start_pos);
  1816. for (i = 0; i < cpi->baseline_gf_interval; ++i) {
  1817. input_stats(cpi, &next_frame);
  1818. accumulate_stats(&sectionstats, &next_frame);
  1819. }
  1820. avg_stats(&sectionstats);
  1821. cpi->twopass.section_intra_rating =
  1822. (unsigned int)(sectionstats.intra_error /
  1823. DOUBLE_DIVIDE_CHECK(sectionstats.coded_error));
  1824. Ratio = sectionstats.intra_error /
  1825. DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
  1826. cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
  1827. if (cpi->twopass.section_max_qfactor < 0.80) {
  1828. cpi->twopass.section_max_qfactor = 0.80;
  1829. }
  1830. reset_fpf_position(cpi, start_pos);
  1831. }
  1832. }
  1833. /* Allocate bits to a normal frame that is neither a gf an arf or a key frame.
  1834. */
  1835. static void assign_std_frame_bits(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
  1836. int target_frame_size;
  1837. double modified_err;
  1838. double err_fraction;
  1839. int max_bits = frame_max_bits(cpi); /* Max for a single frame */
  1840. /* Calculate modified prediction error used in bit allocation */
  1841. modified_err = calculate_modified_err(cpi, this_frame);
  1842. /* What portion of the remaining GF group error is used by this frame */
  1843. if (cpi->twopass.gf_group_error_left > 0) {
  1844. err_fraction = modified_err / cpi->twopass.gf_group_error_left;
  1845. } else {
  1846. err_fraction = 0.0;
  1847. }
  1848. /* How many of those bits available for allocation should we give it? */
  1849. target_frame_size = (int)((double)cpi->twopass.gf_group_bits * err_fraction);
  1850. /* Clip to target size to 0 - max_bits (or cpi->twopass.gf_group_bits)
  1851. * at the top end.
  1852. */
  1853. if (target_frame_size < 0) {
  1854. target_frame_size = 0;
  1855. } else {
  1856. if (target_frame_size > max_bits) target_frame_size = max_bits;
  1857. if (target_frame_size > cpi->twopass.gf_group_bits) {
  1858. target_frame_size = (int)cpi->twopass.gf_group_bits;
  1859. }
  1860. }
  1861. /* Adjust error and bits remaining */
  1862. cpi->twopass.gf_group_error_left -= (int)modified_err;
  1863. cpi->twopass.gf_group_bits -= target_frame_size;
  1864. if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
  1865. /* Add in the minimum number of bits that is set aside for every frame. */
  1866. target_frame_size += cpi->min_frame_bandwidth;
  1867. /* Every other frame gets a few extra bits */
  1868. if ((cpi->frames_since_golden & 0x01) &&
  1869. (cpi->frames_till_gf_update_due > 0)) {
  1870. target_frame_size += cpi->twopass.alt_extra_bits;
  1871. }
  1872. /* Per frame bit target for this frame */
  1873. cpi->per_frame_bandwidth = target_frame_size;
  1874. }
  1875. void vp8_second_pass(VP8_COMP *cpi) {
  1876. int tmp_q;
  1877. int frames_left =
  1878. (int)(cpi->twopass.total_stats.count - cpi->common.current_video_frame);
  1879. FIRSTPASS_STATS this_frame;
  1880. FIRSTPASS_STATS this_frame_copy;
  1881. double this_frame_intra_error;
  1882. double this_frame_coded_error;
  1883. int overhead_bits;
  1884. vp8_zero(this_frame);
  1885. if (!cpi->twopass.stats_in) {
  1886. return;
  1887. }
  1888. vpx_clear_system_state();
  1889. if (EOF == input_stats(cpi, &this_frame)) return;
  1890. this_frame_intra_error = this_frame.intra_error;
  1891. this_frame_coded_error = this_frame.coded_error;
  1892. /* keyframe and section processing ! */
  1893. if (cpi->twopass.frames_to_key == 0) {
  1894. /* Define next KF group and assign bits to it */
  1895. memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
  1896. find_next_key_frame(cpi, &this_frame_copy);
  1897. /* Special case: Error error_resilient_mode mode does not make much
  1898. * sense for two pass but with its current meaning this code is
  1899. * designed to stop outlandish behaviour if someone does set it when
  1900. * using two pass. It effectively disables GF groups. This is
  1901. * temporary code until we decide what should really happen in this
  1902. * case.
  1903. */
  1904. if (cpi->oxcf.error_resilient_mode) {
  1905. cpi->twopass.gf_group_bits = cpi->twopass.kf_group_bits;
  1906. cpi->twopass.gf_group_error_left = (int)cpi->twopass.kf_group_error_left;
  1907. cpi->baseline_gf_interval = cpi->twopass.frames_to_key;
  1908. cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
  1909. cpi->source_alt_ref_pending = 0;
  1910. }
  1911. }
  1912. /* Is this a GF / ARF (Note that a KF is always also a GF) */
  1913. if (cpi->frames_till_gf_update_due == 0) {
  1914. /* Define next gf group and assign bits to it */
  1915. memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
  1916. define_gf_group(cpi, &this_frame_copy);
  1917. /* If we are going to code an altref frame at the end of the group
  1918. * and the current frame is not a key frame.... If the previous
  1919. * group used an arf this frame has already benefited from that arf
  1920. * boost and it should not be given extra bits If the previous
  1921. * group was NOT coded using arf we may want to apply some boost to
  1922. * this GF as well
  1923. */
  1924. if (cpi->source_alt_ref_pending && (cpi->common.frame_type != KEY_FRAME)) {
  1925. /* Assign a standard frames worth of bits from those allocated
  1926. * to the GF group
  1927. */
  1928. int bak = cpi->per_frame_bandwidth;
  1929. memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
  1930. assign_std_frame_bits(cpi, &this_frame_copy);
  1931. cpi->per_frame_bandwidth = bak;
  1932. }
  1933. }
  1934. /* Otherwise this is an ordinary frame */
  1935. else {
  1936. /* Special case: Error error_resilient_mode mode does not make much
  1937. * sense for two pass but with its current meaning but this code is
  1938. * designed to stop outlandish behaviour if someone does set it
  1939. * when using two pass. It effectively disables GF groups. This is
  1940. * temporary code till we decide what should really happen in this
  1941. * case.
  1942. */
  1943. if (cpi->oxcf.error_resilient_mode) {
  1944. cpi->frames_till_gf_update_due = cpi->twopass.frames_to_key;
  1945. if (cpi->common.frame_type != KEY_FRAME) {
  1946. /* Assign bits from those allocated to the GF group */
  1947. memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
  1948. assign_std_frame_bits(cpi, &this_frame_copy);
  1949. }
  1950. } else {
  1951. /* Assign bits from those allocated to the GF group */
  1952. memcpy(&this_frame_copy, &this_frame, sizeof(this_frame));
  1953. assign_std_frame_bits(cpi, &this_frame_copy);
  1954. }
  1955. }
  1956. /* Keep a globally available copy of this and the next frame's iiratio. */
  1957. cpi->twopass.this_iiratio =
  1958. (unsigned int)(this_frame_intra_error /
  1959. DOUBLE_DIVIDE_CHECK(this_frame_coded_error));
  1960. {
  1961. FIRSTPASS_STATS next_frame;
  1962. if (lookup_next_frame_stats(cpi, &next_frame) != EOF) {
  1963. cpi->twopass.next_iiratio =
  1964. (unsigned int)(next_frame.intra_error /
  1965. DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
  1966. }
  1967. }
  1968. /* Set nominal per second bandwidth for this frame */
  1969. cpi->target_bandwidth =
  1970. (int)(cpi->per_frame_bandwidth * cpi->output_framerate);
  1971. if (cpi->target_bandwidth < 0) cpi->target_bandwidth = 0;
  1972. /* Account for mv, mode and other overheads. */
  1973. overhead_bits = (int)estimate_modemvcost(cpi, &cpi->twopass.total_left_stats);
  1974. /* Special case code for first frame. */
  1975. if (cpi->common.current_video_frame == 0) {
  1976. cpi->twopass.est_max_qcorrection_factor = 1.0;
  1977. /* Set a cq_level in constrained quality mode. */
  1978. if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
  1979. int est_cq;
  1980. est_cq = estimate_cq(cpi, &cpi->twopass.total_left_stats,
  1981. (int)(cpi->twopass.bits_left / frames_left),
  1982. overhead_bits);
  1983. cpi->cq_target_quality = cpi->oxcf.cq_level;
  1984. if (est_cq > cpi->cq_target_quality) cpi->cq_target_quality = est_cq;
  1985. }
  1986. /* guess at maxq needed in 2nd pass */
  1987. cpi->twopass.maxq_max_limit = cpi->worst_quality;
  1988. cpi->twopass.maxq_min_limit = cpi->best_quality;
  1989. tmp_q = estimate_max_q(cpi, &cpi->twopass.total_left_stats,
  1990. (int)(cpi->twopass.bits_left / frames_left),
  1991. overhead_bits);
  1992. /* Limit the maxq value returned subsequently.
  1993. * This increases the risk of overspend or underspend if the initial
  1994. * estimate for the clip is bad, but helps prevent excessive
  1995. * variation in Q, especially near the end of a clip
  1996. * where for example a small overspend may cause Q to crash
  1997. */
  1998. cpi->twopass.maxq_max_limit =
  1999. ((tmp_q + 32) < cpi->worst_quality) ? (tmp_q + 32) : cpi->worst_quality;
  2000. cpi->twopass.maxq_min_limit =
  2001. ((tmp_q - 32) > cpi->best_quality) ? (tmp_q - 32) : cpi->best_quality;
  2002. cpi->active_worst_quality = tmp_q;
  2003. cpi->ni_av_qi = tmp_q;
  2004. }
  2005. /* The last few frames of a clip almost always have to few or too many
  2006. * bits and for the sake of over exact rate control we dont want to make
  2007. * radical adjustments to the allowed quantizer range just to use up a
  2008. * few surplus bits or get beneath the target rate.
  2009. */
  2010. else if ((cpi->common.current_video_frame <
  2011. (((unsigned int)cpi->twopass.total_stats.count * 255) >> 8)) &&
  2012. ((cpi->common.current_video_frame + cpi->baseline_gf_interval) <
  2013. (unsigned int)cpi->twopass.total_stats.count)) {
  2014. if (frames_left < 1) frames_left = 1;
  2015. tmp_q = estimate_max_q(cpi, &cpi->twopass.total_left_stats,
  2016. (int)(cpi->twopass.bits_left / frames_left),
  2017. overhead_bits);
  2018. /* Move active_worst_quality but in a damped way */
  2019. if (tmp_q > cpi->active_worst_quality) {
  2020. cpi->active_worst_quality++;
  2021. } else if (tmp_q < cpi->active_worst_quality) {
  2022. cpi->active_worst_quality--;
  2023. }
  2024. cpi->active_worst_quality =
  2025. ((cpi->active_worst_quality * 3) + tmp_q + 2) / 4;
  2026. }
  2027. cpi->twopass.frames_to_key--;
  2028. /* Update the total stats remaining sturcture */
  2029. subtract_stats(&cpi->twopass.total_left_stats, &this_frame);
  2030. }
  2031. static int test_candidate_kf(VP8_COMP *cpi, FIRSTPASS_STATS *last_frame,
  2032. FIRSTPASS_STATS *this_frame,
  2033. FIRSTPASS_STATS *next_frame) {
  2034. int is_viable_kf = 0;
  2035. /* Does the frame satisfy the primary criteria of a key frame
  2036. * If so, then examine how well it predicts subsequent frames
  2037. */
  2038. if ((this_frame->pcnt_second_ref < 0.10) &&
  2039. (next_frame->pcnt_second_ref < 0.10) &&
  2040. ((this_frame->pcnt_inter < 0.05) ||
  2041. (((this_frame->pcnt_inter - this_frame->pcnt_neutral) < .25) &&
  2042. ((this_frame->intra_error /
  2043. DOUBLE_DIVIDE_CHECK(this_frame->coded_error)) < 2.5) &&
  2044. ((fabs(last_frame->coded_error - this_frame->coded_error) /
  2045. DOUBLE_DIVIDE_CHECK(this_frame->coded_error) >
  2046. .40) ||
  2047. (fabs(last_frame->intra_error - this_frame->intra_error) /
  2048. DOUBLE_DIVIDE_CHECK(this_frame->intra_error) >
  2049. .40) ||
  2050. ((next_frame->intra_error /
  2051. DOUBLE_DIVIDE_CHECK(next_frame->coded_error)) > 3.5))))) {
  2052. int i;
  2053. FIRSTPASS_STATS *start_pos;
  2054. FIRSTPASS_STATS local_next_frame;
  2055. double boost_score = 0.0;
  2056. double old_boost_score = 0.0;
  2057. double decay_accumulator = 1.0;
  2058. double next_iiratio;
  2059. memcpy(&local_next_frame, next_frame, sizeof(*next_frame));
  2060. /* Note the starting file position so we can reset to it */
  2061. start_pos = cpi->twopass.stats_in;
  2062. /* Examine how well the key frame predicts subsequent frames */
  2063. for (i = 0; i < 16; ++i) {
  2064. next_iiratio = (IIKFACTOR1 * local_next_frame.intra_error /
  2065. DOUBLE_DIVIDE_CHECK(local_next_frame.coded_error));
  2066. if (next_iiratio > RMAX) next_iiratio = RMAX;
  2067. /* Cumulative effect of decay in prediction quality */
  2068. if (local_next_frame.pcnt_inter > 0.85) {
  2069. decay_accumulator = decay_accumulator * local_next_frame.pcnt_inter;
  2070. } else {
  2071. decay_accumulator =
  2072. decay_accumulator * ((0.85 + local_next_frame.pcnt_inter) / 2.0);
  2073. }
  2074. /* Keep a running total */
  2075. boost_score += (decay_accumulator * next_iiratio);
  2076. /* Test various breakout clauses */
  2077. if ((local_next_frame.pcnt_inter < 0.05) || (next_iiratio < 1.5) ||
  2078. (((local_next_frame.pcnt_inter - local_next_frame.pcnt_neutral) <
  2079. 0.20) &&
  2080. (next_iiratio < 3.0)) ||
  2081. ((boost_score - old_boost_score) < 0.5) ||
  2082. (local_next_frame.intra_error < 200)) {
  2083. break;
  2084. }
  2085. old_boost_score = boost_score;
  2086. /* Get the next frame details */
  2087. if (EOF == input_stats(cpi, &local_next_frame)) break;
  2088. }
  2089. /* If there is tolerable prediction for at least the next 3 frames
  2090. * then break out else discard this pottential key frame and move on
  2091. */
  2092. if (boost_score > 5.0 && (i > 3)) {
  2093. is_viable_kf = 1;
  2094. } else {
  2095. /* Reset the file position */
  2096. reset_fpf_position(cpi, start_pos);
  2097. is_viable_kf = 0;
  2098. }
  2099. }
  2100. return is_viable_kf;
  2101. }
  2102. static void find_next_key_frame(VP8_COMP *cpi, FIRSTPASS_STATS *this_frame) {
  2103. int i, j;
  2104. FIRSTPASS_STATS last_frame;
  2105. FIRSTPASS_STATS first_frame;
  2106. FIRSTPASS_STATS next_frame;
  2107. FIRSTPASS_STATS *start_position;
  2108. double decay_accumulator = 1.0;
  2109. double boost_score = 0;
  2110. double old_boost_score = 0.0;
  2111. double loop_decay_rate;
  2112. double kf_mod_err = 0.0;
  2113. double kf_group_err = 0.0;
  2114. double kf_group_intra_err = 0.0;
  2115. double kf_group_coded_err = 0.0;
  2116. double recent_loop_decay[8] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
  2117. memset(&next_frame, 0, sizeof(next_frame));
  2118. vpx_clear_system_state();
  2119. start_position = cpi->twopass.stats_in;
  2120. cpi->common.frame_type = KEY_FRAME;
  2121. /* is this a forced key frame by interval */
  2122. cpi->this_key_frame_forced = cpi->next_key_frame_forced;
  2123. /* Clear the alt ref active flag as this can never be active on a key
  2124. * frame
  2125. */
  2126. cpi->source_alt_ref_active = 0;
  2127. /* Kf is always a gf so clear frames till next gf counter */
  2128. cpi->frames_till_gf_update_due = 0;
  2129. cpi->twopass.frames_to_key = 1;
  2130. /* Take a copy of the initial frame details */
  2131. memcpy(&first_frame, this_frame, sizeof(*this_frame));
  2132. cpi->twopass.kf_group_bits = 0;
  2133. cpi->twopass.kf_group_error_left = 0;
  2134. kf_mod_err = calculate_modified_err(cpi, this_frame);
  2135. /* find the next keyframe */
  2136. i = 0;
  2137. while (cpi->twopass.stats_in < cpi->twopass.stats_in_end) {
  2138. /* Accumulate kf group error */
  2139. kf_group_err += calculate_modified_err(cpi, this_frame);
  2140. /* These figures keep intra and coded error counts for all frames
  2141. * including key frames in the group. The effect of the key frame
  2142. * itself can be subtracted out using the first_frame data
  2143. * collected above
  2144. */
  2145. kf_group_intra_err += this_frame->intra_error;
  2146. kf_group_coded_err += this_frame->coded_error;
  2147. /* Load the next frame's stats. */
  2148. memcpy(&last_frame, this_frame, sizeof(*this_frame));
  2149. input_stats(cpi, this_frame);
  2150. /* Provided that we are not at the end of the file... */
  2151. if (cpi->oxcf.auto_key &&
  2152. lookup_next_frame_stats(cpi, &next_frame) != EOF) {
  2153. /* Normal scene cut check */
  2154. if ((i >= MIN_GF_INTERVAL) &&
  2155. test_candidate_kf(cpi, &last_frame, this_frame, &next_frame)) {
  2156. break;
  2157. }
  2158. /* How fast is prediction quality decaying */
  2159. loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
  2160. /* We want to know something about the recent past... rather than
  2161. * as used elsewhere where we are concened with decay in prediction
  2162. * quality since the last GF or KF.
  2163. */
  2164. recent_loop_decay[i % 8] = loop_decay_rate;
  2165. decay_accumulator = 1.0;
  2166. for (j = 0; j < 8; ++j) {
  2167. decay_accumulator = decay_accumulator * recent_loop_decay[j];
  2168. }
  2169. /* Special check for transition or high motion followed by a
  2170. * static scene.
  2171. */
  2172. if (detect_transition_to_still(cpi, i,
  2173. ((int)(cpi->key_frame_frequency) - (int)i),
  2174. loop_decay_rate, decay_accumulator)) {
  2175. break;
  2176. }
  2177. /* Step on to the next frame */
  2178. cpi->twopass.frames_to_key++;
  2179. /* If we don't have a real key frame within the next two
  2180. * forcekeyframeevery intervals then break out of the loop.
  2181. */
  2182. if (cpi->twopass.frames_to_key >= 2 * (int)cpi->key_frame_frequency) {
  2183. break;
  2184. }
  2185. } else {
  2186. cpi->twopass.frames_to_key++;
  2187. }
  2188. i++;
  2189. }
  2190. /* If there is a max kf interval set by the user we must obey it.
  2191. * We already breakout of the loop above at 2x max.
  2192. * This code centers the extra kf if the actual natural
  2193. * interval is between 1x and 2x
  2194. */
  2195. if (cpi->oxcf.auto_key &&
  2196. cpi->twopass.frames_to_key > (int)cpi->key_frame_frequency) {
  2197. FIRSTPASS_STATS *current_pos = cpi->twopass.stats_in;
  2198. FIRSTPASS_STATS tmp_frame;
  2199. cpi->twopass.frames_to_key /= 2;
  2200. /* Copy first frame details */
  2201. memcpy(&tmp_frame, &first_frame, sizeof(first_frame));
  2202. /* Reset to the start of the group */
  2203. reset_fpf_position(cpi, start_position);
  2204. kf_group_err = 0;
  2205. kf_group_intra_err = 0;
  2206. kf_group_coded_err = 0;
  2207. /* Rescan to get the correct error data for the forced kf group */
  2208. for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
  2209. /* Accumulate kf group errors */
  2210. kf_group_err += calculate_modified_err(cpi, &tmp_frame);
  2211. kf_group_intra_err += tmp_frame.intra_error;
  2212. kf_group_coded_err += tmp_frame.coded_error;
  2213. /* Load a the next frame's stats */
  2214. input_stats(cpi, &tmp_frame);
  2215. }
  2216. /* Reset to the start of the group */
  2217. reset_fpf_position(cpi, current_pos);
  2218. cpi->next_key_frame_forced = 1;
  2219. } else {
  2220. cpi->next_key_frame_forced = 0;
  2221. }
  2222. /* Special case for the last frame of the file */
  2223. if (cpi->twopass.stats_in >= cpi->twopass.stats_in_end) {
  2224. /* Accumulate kf group error */
  2225. kf_group_err += calculate_modified_err(cpi, this_frame);
  2226. /* These figures keep intra and coded error counts for all frames
  2227. * including key frames in the group. The effect of the key frame
  2228. * itself can be subtracted out using the first_frame data
  2229. * collected above
  2230. */
  2231. kf_group_intra_err += this_frame->intra_error;
  2232. kf_group_coded_err += this_frame->coded_error;
  2233. }
  2234. /* Calculate the number of bits that should be assigned to the kf group. */
  2235. if ((cpi->twopass.bits_left > 0) &&
  2236. (cpi->twopass.modified_error_left > 0.0)) {
  2237. /* Max for a single normal frame (not key frame) */
  2238. int max_bits = frame_max_bits(cpi);
  2239. /* Maximum bits for the kf group */
  2240. int64_t max_grp_bits;
  2241. /* Default allocation based on bits left and relative
  2242. * complexity of the section
  2243. */
  2244. cpi->twopass.kf_group_bits =
  2245. (int64_t)(cpi->twopass.bits_left *
  2246. (kf_group_err / cpi->twopass.modified_error_left));
  2247. /* Clip based on maximum per frame rate defined by the user. */
  2248. max_grp_bits = (int64_t)max_bits * (int64_t)cpi->twopass.frames_to_key;
  2249. if (cpi->twopass.kf_group_bits > max_grp_bits) {
  2250. cpi->twopass.kf_group_bits = max_grp_bits;
  2251. }
  2252. /* Additional special case for CBR if buffer is getting full. */
  2253. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  2254. int64_t opt_buffer_lvl = cpi->oxcf.optimal_buffer_level;
  2255. int64_t buffer_lvl = cpi->buffer_level;
  2256. /* If the buffer is near or above the optimal and this kf group is
  2257. * not being allocated much then increase the allocation a bit.
  2258. */
  2259. if (buffer_lvl >= opt_buffer_lvl) {
  2260. int64_t high_water_mark =
  2261. (opt_buffer_lvl + cpi->oxcf.maximum_buffer_size) >> 1;
  2262. int64_t av_group_bits;
  2263. /* Av bits per frame * number of frames */
  2264. av_group_bits = (int64_t)cpi->av_per_frame_bandwidth *
  2265. (int64_t)cpi->twopass.frames_to_key;
  2266. /* We are at or above the maximum. */
  2267. if (cpi->buffer_level >= high_water_mark) {
  2268. int64_t min_group_bits;
  2269. min_group_bits =
  2270. av_group_bits + (int64_t)(buffer_lvl - high_water_mark);
  2271. if (cpi->twopass.kf_group_bits < min_group_bits) {
  2272. cpi->twopass.kf_group_bits = min_group_bits;
  2273. }
  2274. }
  2275. /* We are above optimal but below the maximum */
  2276. else if (cpi->twopass.kf_group_bits < av_group_bits) {
  2277. int64_t bits_below_av = av_group_bits - cpi->twopass.kf_group_bits;
  2278. cpi->twopass.kf_group_bits += (int64_t)(
  2279. (double)bits_below_av * (double)(buffer_lvl - opt_buffer_lvl) /
  2280. (double)(high_water_mark - opt_buffer_lvl));
  2281. }
  2282. }
  2283. }
  2284. } else {
  2285. cpi->twopass.kf_group_bits = 0;
  2286. }
  2287. /* Reset the first pass file position */
  2288. reset_fpf_position(cpi, start_position);
  2289. /* determine how big to make this keyframe based on how well the
  2290. * subsequent frames use inter blocks
  2291. */
  2292. decay_accumulator = 1.0;
  2293. boost_score = 0.0;
  2294. for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
  2295. double r;
  2296. if (EOF == input_stats(cpi, &next_frame)) break;
  2297. if (next_frame.intra_error > cpi->twopass.kf_intra_err_min) {
  2298. r = (IIKFACTOR2 * next_frame.intra_error /
  2299. DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
  2300. } else {
  2301. r = (IIKFACTOR2 * cpi->twopass.kf_intra_err_min /
  2302. DOUBLE_DIVIDE_CHECK(next_frame.coded_error));
  2303. }
  2304. if (r > RMAX) r = RMAX;
  2305. /* How fast is prediction quality decaying */
  2306. loop_decay_rate = get_prediction_decay_rate(cpi, &next_frame);
  2307. decay_accumulator = decay_accumulator * loop_decay_rate;
  2308. decay_accumulator = decay_accumulator < 0.1 ? 0.1 : decay_accumulator;
  2309. boost_score += (decay_accumulator * r);
  2310. if ((i > MIN_GF_INTERVAL) && ((boost_score - old_boost_score) < 1.0)) {
  2311. break;
  2312. }
  2313. old_boost_score = boost_score;
  2314. }
  2315. if (1) {
  2316. FIRSTPASS_STATS sectionstats;
  2317. double Ratio;
  2318. zero_stats(&sectionstats);
  2319. reset_fpf_position(cpi, start_position);
  2320. for (i = 0; i < cpi->twopass.frames_to_key; ++i) {
  2321. input_stats(cpi, &next_frame);
  2322. accumulate_stats(&sectionstats, &next_frame);
  2323. }
  2324. avg_stats(&sectionstats);
  2325. cpi->twopass.section_intra_rating =
  2326. (unsigned int)(sectionstats.intra_error /
  2327. DOUBLE_DIVIDE_CHECK(sectionstats.coded_error));
  2328. Ratio = sectionstats.intra_error /
  2329. DOUBLE_DIVIDE_CHECK(sectionstats.coded_error);
  2330. cpi->twopass.section_max_qfactor = 1.0 - ((Ratio - 10.0) * 0.025);
  2331. if (cpi->twopass.section_max_qfactor < 0.80) {
  2332. cpi->twopass.section_max_qfactor = 0.80;
  2333. }
  2334. }
  2335. /* When using CBR apply additional buffer fullness related upper limits */
  2336. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  2337. double max_boost;
  2338. if (cpi->drop_frames_allowed) {
  2339. int df_buffer_level = (int)(cpi->oxcf.drop_frames_water_mark *
  2340. (cpi->oxcf.optimal_buffer_level / 100));
  2341. if (cpi->buffer_level > df_buffer_level) {
  2342. max_boost =
  2343. ((double)((cpi->buffer_level - df_buffer_level) * 2 / 3) * 16.0) /
  2344. DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
  2345. } else {
  2346. max_boost = 0.0;
  2347. }
  2348. } else if (cpi->buffer_level > 0) {
  2349. max_boost = ((double)(cpi->buffer_level * 2 / 3) * 16.0) /
  2350. DOUBLE_DIVIDE_CHECK((double)cpi->av_per_frame_bandwidth);
  2351. } else {
  2352. max_boost = 0.0;
  2353. }
  2354. if (boost_score > max_boost) boost_score = max_boost;
  2355. }
  2356. /* Reset the first pass file position */
  2357. reset_fpf_position(cpi, start_position);
  2358. /* Work out how many bits to allocate for the key frame itself */
  2359. if (1) {
  2360. int kf_boost = (int)boost_score;
  2361. int allocation_chunks;
  2362. int Counter = cpi->twopass.frames_to_key;
  2363. int alt_kf_bits;
  2364. YV12_BUFFER_CONFIG *lst_yv12 = &cpi->common.yv12_fb[cpi->common.lst_fb_idx];
  2365. /* Min boost based on kf interval */
  2366. #if 0
  2367. while ((kf_boost < 48) && (Counter > 0))
  2368. {
  2369. Counter -= 2;
  2370. kf_boost ++;
  2371. }
  2372. #endif
  2373. if (kf_boost < 48) {
  2374. kf_boost += ((Counter + 1) >> 1);
  2375. if (kf_boost > 48) kf_boost = 48;
  2376. }
  2377. /* bigger frame sizes need larger kf boosts, smaller frames smaller
  2378. * boosts...
  2379. */
  2380. if ((lst_yv12->y_width * lst_yv12->y_height) > (320 * 240)) {
  2381. kf_boost += 2 * (lst_yv12->y_width * lst_yv12->y_height) / (320 * 240);
  2382. } else if ((lst_yv12->y_width * lst_yv12->y_height) < (320 * 240)) {
  2383. kf_boost -= 4 * (320 * 240) / (lst_yv12->y_width * lst_yv12->y_height);
  2384. }
  2385. /* Min KF boost */
  2386. kf_boost = (int)((double)kf_boost * 100.0) >> 4; /* Scale 16 to 100 */
  2387. if (kf_boost < 250) kf_boost = 250;
  2388. /*
  2389. * We do three calculations for kf size.
  2390. * The first is based on the error score for the whole kf group.
  2391. * The second (optionaly) on the key frames own error if this is
  2392. * smaller than the average for the group.
  2393. * The final one insures that the frame receives at least the
  2394. * allocation it would have received based on its own error score vs
  2395. * the error score remaining
  2396. * Special case if the sequence appears almost totaly static
  2397. * as measured by the decay accumulator. In this case we want to
  2398. * spend almost all of the bits on the key frame.
  2399. * cpi->twopass.frames_to_key-1 because key frame itself is taken
  2400. * care of by kf_boost.
  2401. */
  2402. if (decay_accumulator >= 0.99) {
  2403. allocation_chunks = ((cpi->twopass.frames_to_key - 1) * 10) + kf_boost;
  2404. } else {
  2405. allocation_chunks = ((cpi->twopass.frames_to_key - 1) * 100) + kf_boost;
  2406. }
  2407. /* Normalize Altboost and allocations chunck down to prevent overflow */
  2408. while (kf_boost > 1000) {
  2409. kf_boost /= 2;
  2410. allocation_chunks /= 2;
  2411. }
  2412. cpi->twopass.kf_group_bits =
  2413. (cpi->twopass.kf_group_bits < 0) ? 0 : cpi->twopass.kf_group_bits;
  2414. /* Calculate the number of bits to be spent on the key frame */
  2415. cpi->twopass.kf_bits =
  2416. (int)((double)kf_boost *
  2417. ((double)cpi->twopass.kf_group_bits / (double)allocation_chunks));
  2418. /* Apply an additional limit for CBR */
  2419. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  2420. if (cpi->twopass.kf_bits > (int)((3 * cpi->buffer_level) >> 2)) {
  2421. cpi->twopass.kf_bits = (int)((3 * cpi->buffer_level) >> 2);
  2422. }
  2423. }
  2424. /* If the key frame is actually easier than the average for the
  2425. * kf group (which does sometimes happen... eg a blank intro frame)
  2426. * Then use an alternate calculation based on the kf error score
  2427. * which should give a smaller key frame.
  2428. */
  2429. if (kf_mod_err < kf_group_err / cpi->twopass.frames_to_key) {
  2430. double alt_kf_grp_bits =
  2431. ((double)cpi->twopass.bits_left *
  2432. (kf_mod_err * (double)cpi->twopass.frames_to_key) /
  2433. DOUBLE_DIVIDE_CHECK(cpi->twopass.modified_error_left));
  2434. alt_kf_bits = (int)((double)kf_boost *
  2435. (alt_kf_grp_bits / (double)allocation_chunks));
  2436. if (cpi->twopass.kf_bits > alt_kf_bits) {
  2437. cpi->twopass.kf_bits = alt_kf_bits;
  2438. }
  2439. }
  2440. /* Else if it is much harder than other frames in the group make sure
  2441. * it at least receives an allocation in keeping with its relative
  2442. * error score
  2443. */
  2444. else {
  2445. alt_kf_bits = (int)((double)cpi->twopass.bits_left *
  2446. (kf_mod_err / DOUBLE_DIVIDE_CHECK(
  2447. cpi->twopass.modified_error_left)));
  2448. if (alt_kf_bits > cpi->twopass.kf_bits) {
  2449. cpi->twopass.kf_bits = alt_kf_bits;
  2450. }
  2451. }
  2452. cpi->twopass.kf_group_bits -= cpi->twopass.kf_bits;
  2453. /* Add in the minimum frame allowance */
  2454. cpi->twopass.kf_bits += cpi->min_frame_bandwidth;
  2455. /* Peer frame bit target for this frame */
  2456. cpi->per_frame_bandwidth = cpi->twopass.kf_bits;
  2457. /* Convert to a per second bitrate */
  2458. cpi->target_bandwidth = (int)(cpi->twopass.kf_bits * cpi->output_framerate);
  2459. }
  2460. /* Note the total error score of the kf group minus the key frame itself */
  2461. cpi->twopass.kf_group_error_left = (int)(kf_group_err - kf_mod_err);
  2462. /* Adjust the count of total modified error left. The count of bits left
  2463. * is adjusted elsewhere based on real coded frame sizes
  2464. */
  2465. cpi->twopass.modified_error_left -= kf_group_err;
  2466. if (cpi->oxcf.allow_spatial_resampling) {
  2467. int resample_trigger = 0;
  2468. int last_kf_resampled = 0;
  2469. int kf_q;
  2470. int scale_val = 0;
  2471. int hr, hs, vr, vs;
  2472. int new_width = cpi->oxcf.Width;
  2473. int new_height = cpi->oxcf.Height;
  2474. int projected_buffer_level;
  2475. int tmp_q;
  2476. double projected_bits_perframe;
  2477. double group_iiratio = (kf_group_intra_err - first_frame.intra_error) /
  2478. (kf_group_coded_err - first_frame.coded_error);
  2479. double err_per_frame = kf_group_err / cpi->twopass.frames_to_key;
  2480. double bits_per_frame;
  2481. double av_bits_per_frame;
  2482. double effective_size_ratio;
  2483. if ((cpi->common.Width != cpi->oxcf.Width) ||
  2484. (cpi->common.Height != cpi->oxcf.Height)) {
  2485. last_kf_resampled = 1;
  2486. }
  2487. /* Set back to unscaled by defaults */
  2488. cpi->common.horiz_scale = NORMAL;
  2489. cpi->common.vert_scale = NORMAL;
  2490. /* Calculate Average bits per frame. */
  2491. av_bits_per_frame = cpi->oxcf.target_bandwidth /
  2492. DOUBLE_DIVIDE_CHECK((double)cpi->framerate);
  2493. /* CBR... Use the clip average as the target for deciding resample */
  2494. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  2495. bits_per_frame = av_bits_per_frame;
  2496. }
  2497. /* In VBR we want to avoid downsampling in easy section unless we
  2498. * are under extreme pressure So use the larger of target bitrate
  2499. * for this section or average bitrate for sequence
  2500. */
  2501. else {
  2502. /* This accounts for how hard the section is... */
  2503. bits_per_frame =
  2504. (double)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key);
  2505. /* Dont turn to resampling in easy sections just because they
  2506. * have been assigned a small number of bits
  2507. */
  2508. if (bits_per_frame < av_bits_per_frame) {
  2509. bits_per_frame = av_bits_per_frame;
  2510. }
  2511. }
  2512. /* bits_per_frame should comply with our minimum */
  2513. if (bits_per_frame < (cpi->oxcf.target_bandwidth *
  2514. cpi->oxcf.two_pass_vbrmin_section / 100)) {
  2515. bits_per_frame = (cpi->oxcf.target_bandwidth *
  2516. cpi->oxcf.two_pass_vbrmin_section / 100);
  2517. }
  2518. /* Work out if spatial resampling is necessary */
  2519. kf_q = estimate_kf_group_q(cpi, err_per_frame, (int)bits_per_frame,
  2520. group_iiratio);
  2521. /* If we project a required Q higher than the maximum allowed Q then
  2522. * make a guess at the actual size of frames in this section
  2523. */
  2524. projected_bits_perframe = bits_per_frame;
  2525. tmp_q = kf_q;
  2526. while (tmp_q > cpi->worst_quality) {
  2527. projected_bits_perframe *= 1.04;
  2528. tmp_q--;
  2529. }
  2530. /* Guess at buffer level at the end of the section */
  2531. projected_buffer_level =
  2532. (int)(cpi->buffer_level -
  2533. (int)((projected_bits_perframe - av_bits_per_frame) *
  2534. cpi->twopass.frames_to_key));
  2535. if (0) {
  2536. FILE *f = fopen("Subsamle.stt", "a");
  2537. fprintf(f, " %8d %8d %8d %8d %12.0f %8d %8d %8d\n",
  2538. cpi->common.current_video_frame, kf_q, cpi->common.horiz_scale,
  2539. cpi->common.vert_scale, kf_group_err / cpi->twopass.frames_to_key,
  2540. (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key),
  2541. new_height, new_width);
  2542. fclose(f);
  2543. }
  2544. /* The trigger for spatial resampling depends on the various
  2545. * parameters such as whether we are streaming (CBR) or VBR.
  2546. */
  2547. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  2548. /* Trigger resample if we are projected to fall below down
  2549. * sample level or resampled last time and are projected to
  2550. * remain below the up sample level
  2551. */
  2552. if ((projected_buffer_level < (cpi->oxcf.resample_down_water_mark *
  2553. cpi->oxcf.optimal_buffer_level / 100)) ||
  2554. (last_kf_resampled &&
  2555. (projected_buffer_level < (cpi->oxcf.resample_up_water_mark *
  2556. cpi->oxcf.optimal_buffer_level / 100)))) {
  2557. resample_trigger = 1;
  2558. } else {
  2559. resample_trigger = 0;
  2560. }
  2561. } else {
  2562. int64_t clip_bits = (int64_t)(
  2563. cpi->twopass.total_stats.count * cpi->oxcf.target_bandwidth /
  2564. DOUBLE_DIVIDE_CHECK((double)cpi->framerate));
  2565. int64_t over_spend = cpi->oxcf.starting_buffer_level - cpi->buffer_level;
  2566. /* If triggered last time the threshold for triggering again is
  2567. * reduced:
  2568. *
  2569. * Projected Q higher than allowed and Overspend > 5% of total
  2570. * bits
  2571. */
  2572. if ((last_kf_resampled && (kf_q > cpi->worst_quality)) ||
  2573. ((kf_q > cpi->worst_quality) && (over_spend > clip_bits / 20))) {
  2574. resample_trigger = 1;
  2575. } else {
  2576. resample_trigger = 0;
  2577. }
  2578. }
  2579. if (resample_trigger) {
  2580. while ((kf_q >= cpi->worst_quality) && (scale_val < 6)) {
  2581. scale_val++;
  2582. cpi->common.vert_scale = vscale_lookup[scale_val];
  2583. cpi->common.horiz_scale = hscale_lookup[scale_val];
  2584. Scale2Ratio(cpi->common.horiz_scale, &hr, &hs);
  2585. Scale2Ratio(cpi->common.vert_scale, &vr, &vs);
  2586. new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
  2587. new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
  2588. /* Reducing the area to 1/4 does not reduce the complexity
  2589. * (err_per_frame) to 1/4... effective_sizeratio attempts
  2590. * to provide a crude correction for this
  2591. */
  2592. effective_size_ratio = (double)(new_width * new_height) /
  2593. (double)(cpi->oxcf.Width * cpi->oxcf.Height);
  2594. effective_size_ratio = (1.0 + (3.0 * effective_size_ratio)) / 4.0;
  2595. /* Now try again and see what Q we get with the smaller
  2596. * image size
  2597. */
  2598. kf_q = estimate_kf_group_q(cpi, err_per_frame * effective_size_ratio,
  2599. (int)bits_per_frame, group_iiratio);
  2600. if (0) {
  2601. FILE *f = fopen("Subsamle.stt", "a");
  2602. fprintf(
  2603. f, "******** %8d %8d %8d %12.0f %8d %8d %8d\n", kf_q,
  2604. cpi->common.horiz_scale, cpi->common.vert_scale,
  2605. kf_group_err / cpi->twopass.frames_to_key,
  2606. (int)(cpi->twopass.kf_group_bits / cpi->twopass.frames_to_key),
  2607. new_height, new_width);
  2608. fclose(f);
  2609. }
  2610. }
  2611. }
  2612. if ((cpi->common.Width != new_width) ||
  2613. (cpi->common.Height != new_height)) {
  2614. cpi->common.Width = new_width;
  2615. cpi->common.Height = new_height;
  2616. vp8_alloc_compressor_data(cpi);
  2617. }
  2618. }
  2619. }