onyx_if.c 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442
  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 "vpx_config.h"
  11. #include "./vpx_scale_rtcd.h"
  12. #include "./vpx_dsp_rtcd.h"
  13. #include "./vp8_rtcd.h"
  14. #include "bitstream.h"
  15. #include "vp8/common/onyxc_int.h"
  16. #include "vp8/common/blockd.h"
  17. #include "onyx_int.h"
  18. #include "vp8/common/systemdependent.h"
  19. #include "vp8/common/vp8_skin_detection.h"
  20. #include "vp8/encoder/quantize.h"
  21. #include "vp8/common/alloccommon.h"
  22. #include "mcomp.h"
  23. #include "firstpass.h"
  24. #include "vpx_dsp/psnr.h"
  25. #include "vpx_scale/vpx_scale.h"
  26. #include "vp8/common/extend.h"
  27. #include "ratectrl.h"
  28. #include "vp8/common/quant_common.h"
  29. #include "segmentation.h"
  30. #if CONFIG_POSTPROC
  31. #include "vp8/common/postproc.h"
  32. #endif
  33. #include "vpx_mem/vpx_mem.h"
  34. #include "vp8/common/reconintra.h"
  35. #include "vp8/common/swapyv12buffer.h"
  36. #include "vp8/common/threading.h"
  37. #include "vpx_ports/system_state.h"
  38. #include "vpx_ports/vpx_timer.h"
  39. #include "vpx_util/vpx_write_yuv_frame.h"
  40. #if ARCH_ARM
  41. #include "vpx_ports/arm.h"
  42. #endif
  43. #if CONFIG_MULTI_RES_ENCODING
  44. #include "mr_dissim.h"
  45. #endif
  46. #include "encodeframe.h"
  47. #if CONFIG_MULTITHREAD
  48. #include "ethreading.h"
  49. #endif
  50. #include "picklpf.h"
  51. #if !CONFIG_REALTIME_ONLY
  52. #include "temporal_filter.h"
  53. #endif
  54. #include <assert.h>
  55. #include <math.h>
  56. #include <stdio.h>
  57. #include <limits.h>
  58. #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
  59. extern int vp8_update_coef_context(VP8_COMP *cpi);
  60. #endif
  61. extern void vp8_deblock_frame(YV12_BUFFER_CONFIG *source,
  62. YV12_BUFFER_CONFIG *post, int filt_lvl,
  63. int low_var_thresh, int flag);
  64. extern unsigned int vp8_get_processor_freq();
  65. int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest);
  66. static void set_default_lf_deltas(VP8_COMP *cpi);
  67. extern const int vp8_gf_interval_table[101];
  68. #if CONFIG_INTERNAL_STATS
  69. #include "math.h"
  70. #include "vpx_dsp/ssim.h"
  71. #endif
  72. #ifdef OUTPUT_YUV_SRC
  73. FILE *yuv_file;
  74. #endif
  75. #ifdef OUTPUT_YUV_DENOISED
  76. FILE *yuv_denoised_file;
  77. #endif
  78. #ifdef OUTPUT_YUV_SKINMAP
  79. static FILE *yuv_skinmap_file = NULL;
  80. #endif
  81. #if 0
  82. FILE *framepsnr;
  83. FILE *kf_list;
  84. FILE *keyfile;
  85. #endif
  86. #if 0
  87. extern int skip_true_count;
  88. extern int skip_false_count;
  89. #endif
  90. #ifdef SPEEDSTATS
  91. unsigned int frames_at_speed[16] = { 0, 0, 0, 0, 0, 0, 0, 0,
  92. 0, 0, 0, 0, 0, 0, 0, 0 };
  93. unsigned int tot_pm = 0;
  94. unsigned int cnt_pm = 0;
  95. unsigned int tot_ef = 0;
  96. unsigned int cnt_ef = 0;
  97. #endif
  98. #ifdef MODE_STATS
  99. extern unsigned __int64 Sectionbits[50];
  100. extern int y_modes[5];
  101. extern int uv_modes[4];
  102. extern int b_modes[10];
  103. extern int inter_y_modes[10];
  104. extern int inter_uv_modes[4];
  105. extern unsigned int inter_b_modes[15];
  106. #endif
  107. extern const int vp8_bits_per_mb[2][QINDEX_RANGE];
  108. extern const int qrounding_factors[129];
  109. extern const int qzbin_factors[129];
  110. extern void vp8cx_init_quantizer(VP8_COMP *cpi);
  111. extern const int vp8cx_base_skip_false_prob[128];
  112. /* Tables relating active max Q to active min Q */
  113. static const unsigned char kf_low_motion_minq[QINDEX_RANGE] = {
  114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
  117. 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5,
  118. 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10, 10, 10, 11,
  119. 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16,
  120. 17, 17, 18, 18, 18, 18, 19, 20, 20, 21, 21, 22, 23, 23
  121. };
  122. static const unsigned char kf_high_motion_minq[QINDEX_RANGE] = {
  123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
  125. 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5,
  126. 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10,
  127. 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16,
  128. 16, 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
  129. 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28, 29, 30
  130. };
  131. static const unsigned char gf_low_motion_minq[QINDEX_RANGE] = {
  132. 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3,
  133. 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8,
  134. 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
  135. 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24,
  136. 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34,
  137. 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 44,
  138. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58
  139. };
  140. static const unsigned char gf_mid_motion_minq[QINDEX_RANGE] = {
  141. 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 5,
  142. 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 11,
  143. 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18,
  144. 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  145. 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37,
  146. 37, 38, 39, 39, 40, 40, 41, 41, 42, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50,
  147. 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64
  148. };
  149. static const unsigned char gf_high_motion_minq[QINDEX_RANGE] = {
  150. 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5,
  151. 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11,
  152. 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21,
  153. 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 30, 30,
  154. 31, 31, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40,
  155. 40, 41, 41, 42, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  156. 57, 58, 59, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80
  157. };
  158. static const unsigned char inter_minq[QINDEX_RANGE] = {
  159. 0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11,
  160. 11, 12, 13, 13, 14, 15, 15, 16, 17, 17, 18, 19, 20, 20, 21, 22, 22, 23, 24,
  161. 24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38,
  162. 39, 39, 40, 41, 42, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 50, 51, 52, 53,
  163. 54, 55, 55, 56, 57, 58, 59, 60, 60, 61, 62, 63, 64, 65, 66, 67, 67, 68, 69,
  164. 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 86,
  165. 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
  166. };
  167. #ifdef PACKET_TESTING
  168. extern FILE *vpxlogc;
  169. #endif
  170. static void save_layer_context(VP8_COMP *cpi) {
  171. LAYER_CONTEXT *lc = &cpi->layer_context[cpi->current_layer];
  172. /* Save layer dependent coding state */
  173. lc->target_bandwidth = cpi->target_bandwidth;
  174. lc->starting_buffer_level = cpi->oxcf.starting_buffer_level;
  175. lc->optimal_buffer_level = cpi->oxcf.optimal_buffer_level;
  176. lc->maximum_buffer_size = cpi->oxcf.maximum_buffer_size;
  177. lc->starting_buffer_level_in_ms = cpi->oxcf.starting_buffer_level_in_ms;
  178. lc->optimal_buffer_level_in_ms = cpi->oxcf.optimal_buffer_level_in_ms;
  179. lc->maximum_buffer_size_in_ms = cpi->oxcf.maximum_buffer_size_in_ms;
  180. lc->buffer_level = cpi->buffer_level;
  181. lc->bits_off_target = cpi->bits_off_target;
  182. lc->total_actual_bits = cpi->total_actual_bits;
  183. lc->worst_quality = cpi->worst_quality;
  184. lc->active_worst_quality = cpi->active_worst_quality;
  185. lc->best_quality = cpi->best_quality;
  186. lc->active_best_quality = cpi->active_best_quality;
  187. lc->ni_av_qi = cpi->ni_av_qi;
  188. lc->ni_tot_qi = cpi->ni_tot_qi;
  189. lc->ni_frames = cpi->ni_frames;
  190. lc->avg_frame_qindex = cpi->avg_frame_qindex;
  191. lc->rate_correction_factor = cpi->rate_correction_factor;
  192. lc->key_frame_rate_correction_factor = cpi->key_frame_rate_correction_factor;
  193. lc->gf_rate_correction_factor = cpi->gf_rate_correction_factor;
  194. lc->zbin_over_quant = cpi->mb.zbin_over_quant;
  195. lc->inter_frame_target = cpi->inter_frame_target;
  196. lc->total_byte_count = cpi->total_byte_count;
  197. lc->filter_level = cpi->common.filter_level;
  198. lc->frames_since_last_drop_overshoot = cpi->frames_since_last_drop_overshoot;
  199. lc->force_maxqp = cpi->force_maxqp;
  200. lc->last_frame_percent_intra = cpi->last_frame_percent_intra;
  201. lc->last_q[0] = cpi->last_q[0];
  202. lc->last_q[1] = cpi->last_q[1];
  203. memcpy(lc->count_mb_ref_frame_usage, cpi->mb.count_mb_ref_frame_usage,
  204. sizeof(cpi->mb.count_mb_ref_frame_usage));
  205. }
  206. static void restore_layer_context(VP8_COMP *cpi, const int layer) {
  207. LAYER_CONTEXT *lc = &cpi->layer_context[layer];
  208. /* Restore layer dependent coding state */
  209. cpi->current_layer = layer;
  210. cpi->target_bandwidth = lc->target_bandwidth;
  211. cpi->oxcf.target_bandwidth = lc->target_bandwidth;
  212. cpi->oxcf.starting_buffer_level = lc->starting_buffer_level;
  213. cpi->oxcf.optimal_buffer_level = lc->optimal_buffer_level;
  214. cpi->oxcf.maximum_buffer_size = lc->maximum_buffer_size;
  215. cpi->oxcf.starting_buffer_level_in_ms = lc->starting_buffer_level_in_ms;
  216. cpi->oxcf.optimal_buffer_level_in_ms = lc->optimal_buffer_level_in_ms;
  217. cpi->oxcf.maximum_buffer_size_in_ms = lc->maximum_buffer_size_in_ms;
  218. cpi->buffer_level = lc->buffer_level;
  219. cpi->bits_off_target = lc->bits_off_target;
  220. cpi->total_actual_bits = lc->total_actual_bits;
  221. cpi->active_worst_quality = lc->active_worst_quality;
  222. cpi->active_best_quality = lc->active_best_quality;
  223. cpi->ni_av_qi = lc->ni_av_qi;
  224. cpi->ni_tot_qi = lc->ni_tot_qi;
  225. cpi->ni_frames = lc->ni_frames;
  226. cpi->avg_frame_qindex = lc->avg_frame_qindex;
  227. cpi->rate_correction_factor = lc->rate_correction_factor;
  228. cpi->key_frame_rate_correction_factor = lc->key_frame_rate_correction_factor;
  229. cpi->gf_rate_correction_factor = lc->gf_rate_correction_factor;
  230. cpi->mb.zbin_over_quant = lc->zbin_over_quant;
  231. cpi->inter_frame_target = lc->inter_frame_target;
  232. cpi->total_byte_count = lc->total_byte_count;
  233. cpi->common.filter_level = lc->filter_level;
  234. cpi->frames_since_last_drop_overshoot = lc->frames_since_last_drop_overshoot;
  235. cpi->force_maxqp = lc->force_maxqp;
  236. cpi->last_frame_percent_intra = lc->last_frame_percent_intra;
  237. cpi->last_q[0] = lc->last_q[0];
  238. cpi->last_q[1] = lc->last_q[1];
  239. memcpy(cpi->mb.count_mb_ref_frame_usage, lc->count_mb_ref_frame_usage,
  240. sizeof(cpi->mb.count_mb_ref_frame_usage));
  241. }
  242. static int rescale(int val, int num, int denom) {
  243. int64_t llnum = num;
  244. int64_t llden = denom;
  245. int64_t llval = val;
  246. return (int)(llval * llnum / llden);
  247. }
  248. static void init_temporal_layer_context(VP8_COMP *cpi, VP8_CONFIG *oxcf,
  249. const int layer,
  250. double prev_layer_framerate) {
  251. LAYER_CONTEXT *lc = &cpi->layer_context[layer];
  252. lc->framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[layer];
  253. lc->target_bandwidth = cpi->oxcf.target_bitrate[layer] * 1000;
  254. lc->starting_buffer_level_in_ms = oxcf->starting_buffer_level;
  255. lc->optimal_buffer_level_in_ms = oxcf->optimal_buffer_level;
  256. lc->maximum_buffer_size_in_ms = oxcf->maximum_buffer_size;
  257. lc->starting_buffer_level =
  258. rescale((int)(oxcf->starting_buffer_level), lc->target_bandwidth, 1000);
  259. if (oxcf->optimal_buffer_level == 0) {
  260. lc->optimal_buffer_level = lc->target_bandwidth / 8;
  261. } else {
  262. lc->optimal_buffer_level =
  263. rescale((int)(oxcf->optimal_buffer_level), lc->target_bandwidth, 1000);
  264. }
  265. if (oxcf->maximum_buffer_size == 0) {
  266. lc->maximum_buffer_size = lc->target_bandwidth / 8;
  267. } else {
  268. lc->maximum_buffer_size =
  269. rescale((int)(oxcf->maximum_buffer_size), lc->target_bandwidth, 1000);
  270. }
  271. /* Work out the average size of a frame within this layer */
  272. if (layer > 0) {
  273. lc->avg_frame_size_for_layer =
  274. (int)((cpi->oxcf.target_bitrate[layer] -
  275. cpi->oxcf.target_bitrate[layer - 1]) *
  276. 1000 / (lc->framerate - prev_layer_framerate));
  277. }
  278. lc->active_worst_quality = cpi->oxcf.worst_allowed_q;
  279. lc->active_best_quality = cpi->oxcf.best_allowed_q;
  280. lc->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
  281. lc->buffer_level = lc->starting_buffer_level;
  282. lc->bits_off_target = lc->starting_buffer_level;
  283. lc->total_actual_bits = 0;
  284. lc->ni_av_qi = 0;
  285. lc->ni_tot_qi = 0;
  286. lc->ni_frames = 0;
  287. lc->rate_correction_factor = 1.0;
  288. lc->key_frame_rate_correction_factor = 1.0;
  289. lc->gf_rate_correction_factor = 1.0;
  290. lc->inter_frame_target = 0;
  291. }
  292. // Upon a run-time change in temporal layers, reset the layer context parameters
  293. // for any "new" layers. For "existing" layers, let them inherit the parameters
  294. // from the previous layer state (at the same layer #). In future we may want
  295. // to better map the previous layer state(s) to the "new" ones.
  296. static void reset_temporal_layer_change(VP8_COMP *cpi, VP8_CONFIG *oxcf,
  297. const int prev_num_layers) {
  298. int i;
  299. double prev_layer_framerate = 0;
  300. const int curr_num_layers = cpi->oxcf.number_of_layers;
  301. // If the previous state was 1 layer, get current layer context from cpi.
  302. // We need this to set the layer context for the new layers below.
  303. if (prev_num_layers == 1) {
  304. cpi->current_layer = 0;
  305. save_layer_context(cpi);
  306. }
  307. for (i = 0; i < curr_num_layers; ++i) {
  308. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  309. if (i >= prev_num_layers) {
  310. init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
  311. }
  312. // The initial buffer levels are set based on their starting levels.
  313. // We could set the buffer levels based on the previous state (normalized
  314. // properly by the layer bandwidths) but we would need to keep track of
  315. // the previous set of layer bandwidths (i.e., target_bitrate[i])
  316. // before the layer change. For now, reset to the starting levels.
  317. lc->buffer_level =
  318. cpi->oxcf.starting_buffer_level_in_ms * cpi->oxcf.target_bitrate[i];
  319. lc->bits_off_target = lc->buffer_level;
  320. // TDOD(marpan): Should we set the rate_correction_factor and
  321. // active_worst/best_quality to values derived from the previous layer
  322. // state (to smooth-out quality dips/rate fluctuation at transition)?
  323. // We need to treat the 1 layer case separately: oxcf.target_bitrate[i]
  324. // is not set for 1 layer, and the restore_layer_context/save_context()
  325. // are not called in the encoding loop, so we need to call it here to
  326. // pass the layer context state to |cpi|.
  327. if (curr_num_layers == 1) {
  328. lc->target_bandwidth = cpi->oxcf.target_bandwidth;
  329. lc->buffer_level =
  330. cpi->oxcf.starting_buffer_level_in_ms * lc->target_bandwidth / 1000;
  331. lc->bits_off_target = lc->buffer_level;
  332. restore_layer_context(cpi, 0);
  333. }
  334. prev_layer_framerate = cpi->output_framerate / cpi->oxcf.rate_decimator[i];
  335. }
  336. }
  337. static void setup_features(VP8_COMP *cpi) {
  338. // If segmentation enabled set the update flags
  339. if (cpi->mb.e_mbd.segmentation_enabled) {
  340. cpi->mb.e_mbd.update_mb_segmentation_map = 1;
  341. cpi->mb.e_mbd.update_mb_segmentation_data = 1;
  342. } else {
  343. cpi->mb.e_mbd.update_mb_segmentation_map = 0;
  344. cpi->mb.e_mbd.update_mb_segmentation_data = 0;
  345. }
  346. cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 0;
  347. cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
  348. memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
  349. memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
  350. memset(cpi->mb.e_mbd.last_ref_lf_deltas, 0,
  351. sizeof(cpi->mb.e_mbd.ref_lf_deltas));
  352. memset(cpi->mb.e_mbd.last_mode_lf_deltas, 0,
  353. sizeof(cpi->mb.e_mbd.mode_lf_deltas));
  354. set_default_lf_deltas(cpi);
  355. }
  356. static void dealloc_raw_frame_buffers(VP8_COMP *cpi);
  357. void vp8_initialize_enc(void) {
  358. static volatile int init_done = 0;
  359. if (!init_done) {
  360. vpx_dsp_rtcd();
  361. vp8_init_intra_predictors();
  362. init_done = 1;
  363. }
  364. }
  365. static void dealloc_compressor_data(VP8_COMP *cpi) {
  366. vpx_free(cpi->tplist);
  367. cpi->tplist = NULL;
  368. /* Delete last frame MV storage buffers */
  369. vpx_free(cpi->lfmv);
  370. cpi->lfmv = 0;
  371. vpx_free(cpi->lf_ref_frame_sign_bias);
  372. cpi->lf_ref_frame_sign_bias = 0;
  373. vpx_free(cpi->lf_ref_frame);
  374. cpi->lf_ref_frame = 0;
  375. /* Delete sementation map */
  376. vpx_free(cpi->segmentation_map);
  377. cpi->segmentation_map = 0;
  378. vpx_free(cpi->active_map);
  379. cpi->active_map = 0;
  380. vp8_de_alloc_frame_buffers(&cpi->common);
  381. vp8_yv12_de_alloc_frame_buffer(&cpi->pick_lf_lvl_frame);
  382. vp8_yv12_de_alloc_frame_buffer(&cpi->scaled_source);
  383. dealloc_raw_frame_buffers(cpi);
  384. vpx_free(cpi->tok);
  385. cpi->tok = 0;
  386. /* Structure used to monitor GF usage */
  387. vpx_free(cpi->gf_active_flags);
  388. cpi->gf_active_flags = 0;
  389. /* Activity mask based per mb zbin adjustments */
  390. vpx_free(cpi->mb_activity_map);
  391. cpi->mb_activity_map = 0;
  392. vpx_free(cpi->mb.pip);
  393. cpi->mb.pip = 0;
  394. #if CONFIG_MULTITHREAD
  395. vpx_free(cpi->mt_current_mb_col);
  396. cpi->mt_current_mb_col = NULL;
  397. #endif
  398. }
  399. static void enable_segmentation(VP8_COMP *cpi) {
  400. /* Set the appropriate feature bit */
  401. cpi->mb.e_mbd.segmentation_enabled = 1;
  402. cpi->mb.e_mbd.update_mb_segmentation_map = 1;
  403. cpi->mb.e_mbd.update_mb_segmentation_data = 1;
  404. }
  405. static void disable_segmentation(VP8_COMP *cpi) {
  406. /* Clear the appropriate feature bit */
  407. cpi->mb.e_mbd.segmentation_enabled = 0;
  408. }
  409. /* Valid values for a segment are 0 to 3
  410. * Segmentation map is arrange as [Rows][Columns]
  411. */
  412. static void set_segmentation_map(VP8_COMP *cpi,
  413. unsigned char *segmentation_map) {
  414. /* Copy in the new segmentation map */
  415. memcpy(cpi->segmentation_map, segmentation_map,
  416. (cpi->common.mb_rows * cpi->common.mb_cols));
  417. /* Signal that the map should be updated. */
  418. cpi->mb.e_mbd.update_mb_segmentation_map = 1;
  419. cpi->mb.e_mbd.update_mb_segmentation_data = 1;
  420. }
  421. /* The values given for each segment can be either deltas (from the default
  422. * value chosen for the frame) or absolute values.
  423. *
  424. * Valid range for abs values is:
  425. * (0-127 for MB_LVL_ALT_Q), (0-63 for SEGMENT_ALT_LF)
  426. * Valid range for delta values are:
  427. * (+/-127 for MB_LVL_ALT_Q), (+/-63 for SEGMENT_ALT_LF)
  428. *
  429. * abs_delta = SEGMENT_DELTADATA (deltas)
  430. * abs_delta = SEGMENT_ABSDATA (use the absolute values given).
  431. *
  432. */
  433. static void set_segment_data(VP8_COMP *cpi, signed char *feature_data,
  434. unsigned char abs_delta) {
  435. cpi->mb.e_mbd.mb_segement_abs_delta = abs_delta;
  436. memcpy(cpi->segment_feature_data, feature_data,
  437. sizeof(cpi->segment_feature_data));
  438. }
  439. /* A simple function to cyclically refresh the background at a lower Q */
  440. static void cyclic_background_refresh(VP8_COMP *cpi, int Q, int lf_adjustment) {
  441. unsigned char *seg_map = cpi->segmentation_map;
  442. signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
  443. int i;
  444. int block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
  445. int mbs_in_frame = cpi->common.mb_rows * cpi->common.mb_cols;
  446. cpi->cyclic_refresh_q = Q / 2;
  447. if (cpi->oxcf.screen_content_mode) {
  448. // Modify quality ramp-up based on Q. Above some Q level, increase the
  449. // number of blocks to be refreshed, and reduce it below the thredhold.
  450. // Turn-off under certain conditions (i.e., away from key frame, and if
  451. // we are at good quality (low Q) and most of the blocks were
  452. // skipped-encoded
  453. // in previous frame.
  454. int qp_thresh = (cpi->oxcf.screen_content_mode == 2) ? 80 : 100;
  455. if (Q >= qp_thresh) {
  456. cpi->cyclic_refresh_mode_max_mbs_perframe =
  457. (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
  458. } else if (cpi->frames_since_key > 250 && Q < 20 &&
  459. cpi->mb.skip_true_count > (int)(0.95 * mbs_in_frame)) {
  460. cpi->cyclic_refresh_mode_max_mbs_perframe = 0;
  461. } else {
  462. cpi->cyclic_refresh_mode_max_mbs_perframe =
  463. (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
  464. }
  465. block_count = cpi->cyclic_refresh_mode_max_mbs_perframe;
  466. }
  467. // Set every macroblock to be eligible for update.
  468. // For key frame this will reset seg map to 0.
  469. memset(cpi->segmentation_map, 0, mbs_in_frame);
  470. if (cpi->common.frame_type != KEY_FRAME && block_count > 0) {
  471. /* Cycle through the macro_block rows */
  472. /* MB loop to set local segmentation map */
  473. i = cpi->cyclic_refresh_mode_index;
  474. assert(i < mbs_in_frame);
  475. do {
  476. /* If the MB is as a candidate for clean up then mark it for
  477. * possible boost/refresh (segment 1) The segment id may get
  478. * reset to 0 later if the MB gets coded anything other than
  479. * last frame 0,0 as only (last frame 0,0) MBs are eligable for
  480. * refresh : that is to say Mbs likely to be background blocks.
  481. */
  482. if (cpi->cyclic_refresh_map[i] == 0) {
  483. seg_map[i] = 1;
  484. block_count--;
  485. } else if (cpi->cyclic_refresh_map[i] < 0) {
  486. cpi->cyclic_refresh_map[i]++;
  487. }
  488. i++;
  489. if (i == mbs_in_frame) i = 0;
  490. } while (block_count && i != cpi->cyclic_refresh_mode_index);
  491. cpi->cyclic_refresh_mode_index = i;
  492. #if CONFIG_TEMPORAL_DENOISING
  493. if (cpi->oxcf.noise_sensitivity > 0) {
  494. if (cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive &&
  495. Q < (int)cpi->denoiser.denoise_pars.qp_thresh &&
  496. (cpi->frames_since_key >
  497. 2 * cpi->denoiser.denoise_pars.consec_zerolast)) {
  498. // Under aggressive denoising, use segmentation to turn off loop
  499. // filter below some qp thresh. The filter is reduced for all
  500. // blocks that have been encoded as ZEROMV LAST x frames in a row,
  501. // where x is set by cpi->denoiser.denoise_pars.consec_zerolast.
  502. // This is to avoid "dot" artifacts that can occur from repeated
  503. // loop filtering on noisy input source.
  504. cpi->cyclic_refresh_q = Q;
  505. // lf_adjustment = -MAX_LOOP_FILTER;
  506. lf_adjustment = -40;
  507. for (i = 0; i < mbs_in_frame; ++i) {
  508. seg_map[i] = (cpi->consec_zero_last[i] >
  509. cpi->denoiser.denoise_pars.consec_zerolast)
  510. ? 1
  511. : 0;
  512. }
  513. }
  514. }
  515. #endif
  516. }
  517. /* Activate segmentation. */
  518. cpi->mb.e_mbd.update_mb_segmentation_map = 1;
  519. cpi->mb.e_mbd.update_mb_segmentation_data = 1;
  520. enable_segmentation(cpi);
  521. /* Set up the quant segment data */
  522. feature_data[MB_LVL_ALT_Q][0] = 0;
  523. feature_data[MB_LVL_ALT_Q][1] = (cpi->cyclic_refresh_q - Q);
  524. feature_data[MB_LVL_ALT_Q][2] = 0;
  525. feature_data[MB_LVL_ALT_Q][3] = 0;
  526. /* Set up the loop segment data */
  527. feature_data[MB_LVL_ALT_LF][0] = 0;
  528. feature_data[MB_LVL_ALT_LF][1] = lf_adjustment;
  529. feature_data[MB_LVL_ALT_LF][2] = 0;
  530. feature_data[MB_LVL_ALT_LF][3] = 0;
  531. /* Initialise the feature data structure */
  532. set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
  533. }
  534. static void compute_skin_map(VP8_COMP *cpi) {
  535. int mb_row, mb_col, num_bl;
  536. VP8_COMMON *cm = &cpi->common;
  537. const uint8_t *src_y = cpi->Source->y_buffer;
  538. const uint8_t *src_u = cpi->Source->u_buffer;
  539. const uint8_t *src_v = cpi->Source->v_buffer;
  540. const int src_ystride = cpi->Source->y_stride;
  541. const int src_uvstride = cpi->Source->uv_stride;
  542. const SKIN_DETECTION_BLOCK_SIZE bsize =
  543. (cm->Width * cm->Height <= 352 * 288) ? SKIN_8X8 : SKIN_16X16;
  544. for (mb_row = 0; mb_row < cm->mb_rows; mb_row++) {
  545. num_bl = 0;
  546. for (mb_col = 0; mb_col < cm->mb_cols; mb_col++) {
  547. const int bl_index = mb_row * cm->mb_cols + mb_col;
  548. cpi->skin_map[bl_index] =
  549. vp8_compute_skin_block(src_y, src_u, src_v, src_ystride, src_uvstride,
  550. bsize, cpi->consec_zero_last[bl_index], 0);
  551. num_bl++;
  552. src_y += 16;
  553. src_u += 8;
  554. src_v += 8;
  555. }
  556. src_y += (src_ystride << 4) - (num_bl << 4);
  557. src_u += (src_uvstride << 3) - (num_bl << 3);
  558. src_v += (src_uvstride << 3) - (num_bl << 3);
  559. }
  560. // Remove isolated skin blocks (none of its neighbors are skin) and isolated
  561. // non-skin blocks (all of its neighbors are skin). Skip the boundary.
  562. for (mb_row = 1; mb_row < cm->mb_rows - 1; mb_row++) {
  563. for (mb_col = 1; mb_col < cm->mb_cols - 1; mb_col++) {
  564. const int bl_index = mb_row * cm->mb_cols + mb_col;
  565. int num_neighbor = 0;
  566. int mi, mj;
  567. int non_skin_threshold = 8;
  568. for (mi = -1; mi <= 1; mi += 1) {
  569. for (mj = -1; mj <= 1; mj += 1) {
  570. int bl_neighbor_index = (mb_row + mi) * cm->mb_cols + mb_col + mj;
  571. if (cpi->skin_map[bl_neighbor_index]) num_neighbor++;
  572. }
  573. }
  574. if (cpi->skin_map[bl_index] && num_neighbor < 2)
  575. cpi->skin_map[bl_index] = 0;
  576. if (!cpi->skin_map[bl_index] && num_neighbor == non_skin_threshold)
  577. cpi->skin_map[bl_index] = 1;
  578. }
  579. }
  580. }
  581. static void set_default_lf_deltas(VP8_COMP *cpi) {
  582. cpi->mb.e_mbd.mode_ref_lf_delta_enabled = 1;
  583. cpi->mb.e_mbd.mode_ref_lf_delta_update = 1;
  584. memset(cpi->mb.e_mbd.ref_lf_deltas, 0, sizeof(cpi->mb.e_mbd.ref_lf_deltas));
  585. memset(cpi->mb.e_mbd.mode_lf_deltas, 0, sizeof(cpi->mb.e_mbd.mode_lf_deltas));
  586. /* Test of ref frame deltas */
  587. cpi->mb.e_mbd.ref_lf_deltas[INTRA_FRAME] = 2;
  588. cpi->mb.e_mbd.ref_lf_deltas[LAST_FRAME] = 0;
  589. cpi->mb.e_mbd.ref_lf_deltas[GOLDEN_FRAME] = -2;
  590. cpi->mb.e_mbd.ref_lf_deltas[ALTREF_FRAME] = -2;
  591. cpi->mb.e_mbd.mode_lf_deltas[0] = 4; /* BPRED */
  592. if (cpi->oxcf.Mode == MODE_REALTIME) {
  593. cpi->mb.e_mbd.mode_lf_deltas[1] = -12; /* Zero */
  594. } else {
  595. cpi->mb.e_mbd.mode_lf_deltas[1] = -2; /* Zero */
  596. }
  597. cpi->mb.e_mbd.mode_lf_deltas[2] = 2; /* New mv */
  598. cpi->mb.e_mbd.mode_lf_deltas[3] = 4; /* Split mv */
  599. }
  600. /* Convenience macros for mapping speed and mode into a continuous
  601. * range
  602. */
  603. #define GOOD(x) ((x) + 1)
  604. #define RT(x) ((x) + 7)
  605. static int speed_map(int speed, const int *map) {
  606. int res;
  607. do {
  608. res = *map++;
  609. } while (speed >= *map++);
  610. return res;
  611. }
  612. static const int thresh_mult_map_znn[] = {
  613. /* map common to zero, nearest, and near */
  614. 0, GOOD(2), 1500, GOOD(3), 2000, RT(0), 1000, RT(2), 2000, INT_MAX
  615. };
  616. static const int thresh_mult_map_vhpred[] = { 1000, GOOD(2), 1500, GOOD(3),
  617. 2000, RT(0), 1000, RT(1),
  618. 2000, RT(7), INT_MAX, INT_MAX };
  619. static const int thresh_mult_map_bpred[] = { 2000, GOOD(0), 2500, GOOD(2),
  620. 5000, GOOD(3), 7500, RT(0),
  621. 2500, RT(1), 5000, RT(6),
  622. INT_MAX, INT_MAX };
  623. static const int thresh_mult_map_tm[] = { 1000, GOOD(2), 1500, GOOD(3),
  624. 2000, RT(0), 0, RT(1),
  625. 1000, RT(2), 2000, RT(7),
  626. INT_MAX, INT_MAX };
  627. static const int thresh_mult_map_new1[] = { 1000, GOOD(2), 2000,
  628. RT(0), 2000, INT_MAX };
  629. static const int thresh_mult_map_new2[] = { 1000, GOOD(2), 2000, GOOD(3),
  630. 2500, GOOD(5), 4000, RT(0),
  631. 2000, RT(2), 2500, RT(5),
  632. 4000, INT_MAX };
  633. static const int thresh_mult_map_split1[] = {
  634. 2500, GOOD(0), 1700, GOOD(2), 10000, GOOD(3), 25000, GOOD(4), INT_MAX,
  635. RT(0), 5000, RT(1), 10000, RT(2), 25000, RT(3), INT_MAX, INT_MAX
  636. };
  637. static const int thresh_mult_map_split2[] = {
  638. 5000, GOOD(0), 4500, GOOD(2), 20000, GOOD(3), 50000, GOOD(4), INT_MAX,
  639. RT(0), 10000, RT(1), 20000, RT(2), 50000, RT(3), INT_MAX, INT_MAX
  640. };
  641. static const int mode_check_freq_map_zn2[] = {
  642. /* {zero,nearest}{2,3} */
  643. 0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
  644. };
  645. static const int mode_check_freq_map_vhbpred[] = { 0, GOOD(5), 2, RT(0),
  646. 0, RT(3), 2, RT(5),
  647. 4, INT_MAX };
  648. static const int mode_check_freq_map_near2[] = {
  649. 0, GOOD(5), 2, RT(0), 0, RT(3), 2,
  650. RT(10), 1 << 2, RT(11), 1 << 3, RT(12), 1 << 4, INT_MAX
  651. };
  652. static const int mode_check_freq_map_new1[] = {
  653. 0, RT(10), 1 << 1, RT(11), 1 << 2, RT(12), 1 << 3, INT_MAX
  654. };
  655. static const int mode_check_freq_map_new2[] = { 0, GOOD(5), 4, RT(0),
  656. 0, RT(3), 4, RT(10),
  657. 1 << 3, RT(11), 1 << 4, RT(12),
  658. 1 << 5, INT_MAX };
  659. static const int mode_check_freq_map_split1[] = { 0, GOOD(2), 2, GOOD(3),
  660. 7, RT(1), 2, RT(2),
  661. 7, INT_MAX };
  662. static const int mode_check_freq_map_split2[] = { 0, GOOD(1), 2, GOOD(2),
  663. 4, GOOD(3), 15, RT(1),
  664. 4, RT(2), 15, INT_MAX };
  665. void vp8_set_speed_features(VP8_COMP *cpi) {
  666. SPEED_FEATURES *sf = &cpi->sf;
  667. int Mode = cpi->compressor_speed;
  668. int Speed = cpi->Speed;
  669. int Speed2;
  670. int i;
  671. VP8_COMMON *cm = &cpi->common;
  672. int last_improved_quant = sf->improved_quant;
  673. int ref_frames;
  674. /* Initialise default mode frequency sampling variables */
  675. for (i = 0; i < MAX_MODES; ++i) {
  676. cpi->mode_check_freq[i] = 0;
  677. }
  678. cpi->mb.mbs_tested_so_far = 0;
  679. cpi->mb.mbs_zero_last_dot_suppress = 0;
  680. /* best quality defaults */
  681. sf->RD = 1;
  682. sf->search_method = NSTEP;
  683. sf->improved_quant = 1;
  684. sf->improved_dct = 1;
  685. sf->auto_filter = 1;
  686. sf->recode_loop = 1;
  687. sf->quarter_pixel_search = 1;
  688. sf->half_pixel_search = 1;
  689. sf->iterative_sub_pixel = 1;
  690. sf->optimize_coefficients = 1;
  691. sf->use_fastquant_for_pick = 0;
  692. sf->no_skip_block4x4_search = 1;
  693. sf->first_step = 0;
  694. sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
  695. sf->improved_mv_pred = 1;
  696. /* default thresholds to 0 */
  697. for (i = 0; i < MAX_MODES; ++i) sf->thresh_mult[i] = 0;
  698. /* Count enabled references */
  699. ref_frames = 1;
  700. if (cpi->ref_frame_flags & VP8_LAST_FRAME) ref_frames++;
  701. if (cpi->ref_frame_flags & VP8_GOLD_FRAME) ref_frames++;
  702. if (cpi->ref_frame_flags & VP8_ALTR_FRAME) ref_frames++;
  703. /* Convert speed to continuous range, with clamping */
  704. if (Mode == 0) {
  705. Speed = 0;
  706. } else if (Mode == 2) {
  707. Speed = RT(Speed);
  708. } else {
  709. if (Speed > 5) Speed = 5;
  710. Speed = GOOD(Speed);
  711. }
  712. sf->thresh_mult[THR_ZERO1] = sf->thresh_mult[THR_NEAREST1] =
  713. sf->thresh_mult[THR_NEAR1] = sf->thresh_mult[THR_DC] = 0; /* always */
  714. sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO3] =
  715. sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST3] =
  716. sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR3] =
  717. speed_map(Speed, thresh_mult_map_znn);
  718. sf->thresh_mult[THR_V_PRED] = sf->thresh_mult[THR_H_PRED] =
  719. speed_map(Speed, thresh_mult_map_vhpred);
  720. sf->thresh_mult[THR_B_PRED] = speed_map(Speed, thresh_mult_map_bpred);
  721. sf->thresh_mult[THR_TM] = speed_map(Speed, thresh_mult_map_tm);
  722. sf->thresh_mult[THR_NEW1] = speed_map(Speed, thresh_mult_map_new1);
  723. sf->thresh_mult[THR_NEW2] = sf->thresh_mult[THR_NEW3] =
  724. speed_map(Speed, thresh_mult_map_new2);
  725. sf->thresh_mult[THR_SPLIT1] = speed_map(Speed, thresh_mult_map_split1);
  726. sf->thresh_mult[THR_SPLIT2] = sf->thresh_mult[THR_SPLIT3] =
  727. speed_map(Speed, thresh_mult_map_split2);
  728. // Special case for temporal layers.
  729. // Reduce the thresholds for zero/nearest/near for GOLDEN, if GOLDEN is
  730. // used as second reference. We don't modify thresholds for ALTREF case
  731. // since ALTREF is usually used as long-term reference in temporal layers.
  732. if ((cpi->Speed <= 6) && (cpi->oxcf.number_of_layers > 1) &&
  733. (cpi->ref_frame_flags & VP8_LAST_FRAME) &&
  734. (cpi->ref_frame_flags & VP8_GOLD_FRAME)) {
  735. if (cpi->closest_reference_frame == GOLDEN_FRAME) {
  736. sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 3;
  737. sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 3;
  738. sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 3;
  739. } else {
  740. sf->thresh_mult[THR_ZERO2] = sf->thresh_mult[THR_ZERO2] >> 1;
  741. sf->thresh_mult[THR_NEAREST2] = sf->thresh_mult[THR_NEAREST2] >> 1;
  742. sf->thresh_mult[THR_NEAR2] = sf->thresh_mult[THR_NEAR2] >> 1;
  743. }
  744. }
  745. cpi->mode_check_freq[THR_ZERO1] = cpi->mode_check_freq[THR_NEAREST1] =
  746. cpi->mode_check_freq[THR_NEAR1] = cpi->mode_check_freq[THR_TM] =
  747. cpi->mode_check_freq[THR_DC] = 0; /* always */
  748. cpi->mode_check_freq[THR_ZERO2] = cpi->mode_check_freq[THR_ZERO3] =
  749. cpi->mode_check_freq[THR_NEAREST2] = cpi->mode_check_freq[THR_NEAREST3] =
  750. speed_map(Speed, mode_check_freq_map_zn2);
  751. cpi->mode_check_freq[THR_NEAR2] = cpi->mode_check_freq[THR_NEAR3] =
  752. speed_map(Speed, mode_check_freq_map_near2);
  753. cpi->mode_check_freq[THR_V_PRED] = cpi->mode_check_freq[THR_H_PRED] =
  754. cpi->mode_check_freq[THR_B_PRED] =
  755. speed_map(Speed, mode_check_freq_map_vhbpred);
  756. // For real-time mode at speed 10 keep the mode_check_freq threshold
  757. // for NEW1 similar to that of speed 9.
  758. Speed2 = Speed;
  759. if (cpi->Speed == 10 && Mode == 2) Speed2 = RT(9);
  760. cpi->mode_check_freq[THR_NEW1] = speed_map(Speed2, mode_check_freq_map_new1);
  761. cpi->mode_check_freq[THR_NEW2] = cpi->mode_check_freq[THR_NEW3] =
  762. speed_map(Speed, mode_check_freq_map_new2);
  763. cpi->mode_check_freq[THR_SPLIT1] =
  764. speed_map(Speed, mode_check_freq_map_split1);
  765. cpi->mode_check_freq[THR_SPLIT2] = cpi->mode_check_freq[THR_SPLIT3] =
  766. speed_map(Speed, mode_check_freq_map_split2);
  767. Speed = cpi->Speed;
  768. switch (Mode) {
  769. #if !CONFIG_REALTIME_ONLY
  770. case 0: /* best quality mode */
  771. sf->first_step = 0;
  772. sf->max_step_search_steps = MAX_MVSEARCH_STEPS;
  773. break;
  774. case 1:
  775. case 3:
  776. if (Speed > 0) {
  777. /* Disable coefficient optimization above speed 0 */
  778. sf->optimize_coefficients = 0;
  779. sf->use_fastquant_for_pick = 1;
  780. sf->no_skip_block4x4_search = 0;
  781. sf->first_step = 1;
  782. }
  783. if (Speed > 2) {
  784. sf->improved_quant = 0;
  785. sf->improved_dct = 0;
  786. /* Only do recode loop on key frames, golden frames and
  787. * alt ref frames
  788. */
  789. sf->recode_loop = 2;
  790. }
  791. if (Speed > 3) {
  792. sf->auto_filter = 1;
  793. sf->recode_loop = 0; /* recode loop off */
  794. sf->RD = 0; /* Turn rd off */
  795. }
  796. if (Speed > 4) {
  797. sf->auto_filter = 0; /* Faster selection of loop filter */
  798. }
  799. break;
  800. #endif
  801. case 2:
  802. sf->optimize_coefficients = 0;
  803. sf->recode_loop = 0;
  804. sf->auto_filter = 1;
  805. sf->iterative_sub_pixel = 1;
  806. sf->search_method = NSTEP;
  807. if (Speed > 0) {
  808. sf->improved_quant = 0;
  809. sf->improved_dct = 0;
  810. sf->use_fastquant_for_pick = 1;
  811. sf->no_skip_block4x4_search = 0;
  812. sf->first_step = 1;
  813. }
  814. if (Speed > 2) sf->auto_filter = 0; /* Faster selection of loop filter */
  815. if (Speed > 3) {
  816. sf->RD = 0;
  817. sf->auto_filter = 1;
  818. }
  819. if (Speed > 4) {
  820. sf->auto_filter = 0; /* Faster selection of loop filter */
  821. sf->search_method = HEX;
  822. sf->iterative_sub_pixel = 0;
  823. }
  824. if (Speed > 6) {
  825. unsigned int sum = 0;
  826. unsigned int total_mbs = cm->MBs;
  827. int thresh;
  828. unsigned int total_skip;
  829. int min = 2000;
  830. if (cpi->oxcf.encode_breakout > 2000) min = cpi->oxcf.encode_breakout;
  831. min >>= 7;
  832. for (i = 0; i < min; ++i) {
  833. sum += cpi->mb.error_bins[i];
  834. }
  835. total_skip = sum;
  836. sum = 0;
  837. /* i starts from 2 to make sure thresh started from 2048 */
  838. for (; i < 1024; ++i) {
  839. sum += cpi->mb.error_bins[i];
  840. if (10 * sum >=
  841. (unsigned int)(cpi->Speed - 6) * (total_mbs - total_skip)) {
  842. break;
  843. }
  844. }
  845. i--;
  846. thresh = (i << 7);
  847. if (thresh < 2000) thresh = 2000;
  848. if (ref_frames > 1) {
  849. sf->thresh_mult[THR_NEW1] = thresh;
  850. sf->thresh_mult[THR_NEAREST1] = thresh >> 1;
  851. sf->thresh_mult[THR_NEAR1] = thresh >> 1;
  852. }
  853. if (ref_frames > 2) {
  854. sf->thresh_mult[THR_NEW2] = thresh << 1;
  855. sf->thresh_mult[THR_NEAREST2] = thresh;
  856. sf->thresh_mult[THR_NEAR2] = thresh;
  857. }
  858. if (ref_frames > 3) {
  859. sf->thresh_mult[THR_NEW3] = thresh << 1;
  860. sf->thresh_mult[THR_NEAREST3] = thresh;
  861. sf->thresh_mult[THR_NEAR3] = thresh;
  862. }
  863. sf->improved_mv_pred = 0;
  864. }
  865. if (Speed > 8) sf->quarter_pixel_search = 0;
  866. if (cm->version == 0) {
  867. cm->filter_type = NORMAL_LOOPFILTER;
  868. if (Speed >= 14) cm->filter_type = SIMPLE_LOOPFILTER;
  869. } else {
  870. cm->filter_type = SIMPLE_LOOPFILTER;
  871. }
  872. /* This has a big hit on quality. Last resort */
  873. if (Speed >= 15) sf->half_pixel_search = 0;
  874. memset(cpi->mb.error_bins, 0, sizeof(cpi->mb.error_bins));
  875. }; /* switch */
  876. /* Slow quant, dct and trellis not worthwhile for first pass
  877. * so make sure they are always turned off.
  878. */
  879. if (cpi->pass == 1) {
  880. sf->improved_quant = 0;
  881. sf->optimize_coefficients = 0;
  882. sf->improved_dct = 0;
  883. }
  884. if (cpi->sf.search_method == NSTEP) {
  885. vp8_init3smotion_compensation(&cpi->mb,
  886. cm->yv12_fb[cm->lst_fb_idx].y_stride);
  887. } else if (cpi->sf.search_method == DIAMOND) {
  888. vp8_init_dsmotion_compensation(&cpi->mb,
  889. cm->yv12_fb[cm->lst_fb_idx].y_stride);
  890. }
  891. if (cpi->sf.improved_dct) {
  892. cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
  893. cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
  894. } else {
  895. /* No fast FDCT defined for any platform at this time. */
  896. cpi->mb.short_fdct8x4 = vp8_short_fdct8x4;
  897. cpi->mb.short_fdct4x4 = vp8_short_fdct4x4;
  898. }
  899. cpi->mb.short_walsh4x4 = vp8_short_walsh4x4;
  900. if (cpi->sf.improved_quant) {
  901. cpi->mb.quantize_b = vp8_regular_quantize_b;
  902. } else {
  903. cpi->mb.quantize_b = vp8_fast_quantize_b;
  904. }
  905. if (cpi->sf.improved_quant != last_improved_quant) vp8cx_init_quantizer(cpi);
  906. if (cpi->sf.iterative_sub_pixel == 1) {
  907. cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step_iteratively;
  908. } else if (cpi->sf.quarter_pixel_search) {
  909. cpi->find_fractional_mv_step = vp8_find_best_sub_pixel_step;
  910. } else if (cpi->sf.half_pixel_search) {
  911. cpi->find_fractional_mv_step = vp8_find_best_half_pixel_step;
  912. } else {
  913. cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
  914. }
  915. if (cpi->sf.optimize_coefficients == 1 && cpi->pass != 1) {
  916. cpi->mb.optimize = 1;
  917. } else {
  918. cpi->mb.optimize = 0;
  919. }
  920. if (cpi->common.full_pixel) {
  921. cpi->find_fractional_mv_step = vp8_skip_fractional_mv_step;
  922. }
  923. #ifdef SPEEDSTATS
  924. frames_at_speed[cpi->Speed]++;
  925. #endif
  926. }
  927. #undef GOOD
  928. #undef RT
  929. static void alloc_raw_frame_buffers(VP8_COMP *cpi) {
  930. #if VP8_TEMPORAL_ALT_REF
  931. int width = (cpi->oxcf.Width + 15) & ~15;
  932. int height = (cpi->oxcf.Height + 15) & ~15;
  933. #endif
  934. cpi->lookahead = vp8_lookahead_init(cpi->oxcf.Width, cpi->oxcf.Height,
  935. cpi->oxcf.lag_in_frames);
  936. if (!cpi->lookahead) {
  937. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  938. "Failed to allocate lag buffers");
  939. }
  940. #if VP8_TEMPORAL_ALT_REF
  941. if (vp8_yv12_alloc_frame_buffer(&cpi->alt_ref_buffer, width, height,
  942. VP8BORDERINPIXELS)) {
  943. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  944. "Failed to allocate altref buffer");
  945. }
  946. #endif
  947. }
  948. static void dealloc_raw_frame_buffers(VP8_COMP *cpi) {
  949. #if VP8_TEMPORAL_ALT_REF
  950. vp8_yv12_de_alloc_frame_buffer(&cpi->alt_ref_buffer);
  951. #endif
  952. vp8_lookahead_destroy(cpi->lookahead);
  953. }
  954. static int vp8_alloc_partition_data(VP8_COMP *cpi) {
  955. vpx_free(cpi->mb.pip);
  956. cpi->mb.pip =
  957. vpx_calloc((cpi->common.mb_cols + 1) * (cpi->common.mb_rows + 1),
  958. sizeof(PARTITION_INFO));
  959. if (!cpi->mb.pip) return 1;
  960. cpi->mb.pi = cpi->mb.pip + cpi->common.mode_info_stride + 1;
  961. return 0;
  962. }
  963. void vp8_alloc_compressor_data(VP8_COMP *cpi) {
  964. VP8_COMMON *cm = &cpi->common;
  965. int width = cm->Width;
  966. int height = cm->Height;
  967. if (vp8_alloc_frame_buffers(cm, width, height)) {
  968. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  969. "Failed to allocate frame buffers");
  970. }
  971. if (vp8_alloc_partition_data(cpi)) {
  972. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  973. "Failed to allocate partition data");
  974. }
  975. if ((width & 0xf) != 0) width += 16 - (width & 0xf);
  976. if ((height & 0xf) != 0) height += 16 - (height & 0xf);
  977. if (vp8_yv12_alloc_frame_buffer(&cpi->pick_lf_lvl_frame, width, height,
  978. VP8BORDERINPIXELS)) {
  979. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  980. "Failed to allocate last frame buffer");
  981. }
  982. if (vp8_yv12_alloc_frame_buffer(&cpi->scaled_source, width, height,
  983. VP8BORDERINPIXELS)) {
  984. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  985. "Failed to allocate scaled source buffer");
  986. }
  987. vpx_free(cpi->tok);
  988. {
  989. #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
  990. unsigned int tokens = 8 * 24 * 16; /* one MB for each thread */
  991. #else
  992. unsigned int tokens = cm->mb_rows * cm->mb_cols * 24 * 16;
  993. #endif
  994. CHECK_MEM_ERROR(cpi->tok, vpx_calloc(tokens, sizeof(*cpi->tok)));
  995. }
  996. /* Data used for real time vc mode to see if gf needs refreshing */
  997. cpi->zeromv_count = 0;
  998. /* Structures used to monitor GF usage */
  999. vpx_free(cpi->gf_active_flags);
  1000. CHECK_MEM_ERROR(
  1001. cpi->gf_active_flags,
  1002. vpx_calloc(sizeof(*cpi->gf_active_flags), cm->mb_rows * cm->mb_cols));
  1003. cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
  1004. vpx_free(cpi->mb_activity_map);
  1005. CHECK_MEM_ERROR(
  1006. cpi->mb_activity_map,
  1007. vpx_calloc(sizeof(*cpi->mb_activity_map), cm->mb_rows * cm->mb_cols));
  1008. /* allocate memory for storing last frame's MVs for MV prediction. */
  1009. vpx_free(cpi->lfmv);
  1010. CHECK_MEM_ERROR(cpi->lfmv, vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
  1011. sizeof(*cpi->lfmv)));
  1012. vpx_free(cpi->lf_ref_frame_sign_bias);
  1013. CHECK_MEM_ERROR(cpi->lf_ref_frame_sign_bias,
  1014. vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
  1015. sizeof(*cpi->lf_ref_frame_sign_bias)));
  1016. vpx_free(cpi->lf_ref_frame);
  1017. CHECK_MEM_ERROR(cpi->lf_ref_frame,
  1018. vpx_calloc((cm->mb_rows + 2) * (cm->mb_cols + 2),
  1019. sizeof(*cpi->lf_ref_frame)));
  1020. /* Create the encoder segmentation map and set all entries to 0 */
  1021. vpx_free(cpi->segmentation_map);
  1022. CHECK_MEM_ERROR(
  1023. cpi->segmentation_map,
  1024. vpx_calloc(cm->mb_rows * cm->mb_cols, sizeof(*cpi->segmentation_map)));
  1025. cpi->cyclic_refresh_mode_index = 0;
  1026. vpx_free(cpi->active_map);
  1027. CHECK_MEM_ERROR(cpi->active_map, vpx_calloc(cm->mb_rows * cm->mb_cols,
  1028. sizeof(*cpi->active_map)));
  1029. memset(cpi->active_map, 1, (cm->mb_rows * cm->mb_cols));
  1030. #if CONFIG_MULTITHREAD
  1031. if (width < 640) {
  1032. cpi->mt_sync_range = 1;
  1033. } else if (width <= 1280) {
  1034. cpi->mt_sync_range = 4;
  1035. } else if (width <= 2560) {
  1036. cpi->mt_sync_range = 8;
  1037. } else {
  1038. cpi->mt_sync_range = 16;
  1039. }
  1040. if (cpi->oxcf.multi_threaded > 1) {
  1041. int i;
  1042. vpx_free(cpi->mt_current_mb_col);
  1043. CHECK_MEM_ERROR(cpi->mt_current_mb_col,
  1044. vpx_malloc(sizeof(*cpi->mt_current_mb_col) * cm->mb_rows));
  1045. for (i = 0; i < cm->mb_rows; ++i)
  1046. vpx_atomic_init(&cpi->mt_current_mb_col[i], 0);
  1047. }
  1048. #endif
  1049. vpx_free(cpi->tplist);
  1050. CHECK_MEM_ERROR(cpi->tplist, vpx_malloc(sizeof(TOKENLIST) * cm->mb_rows));
  1051. #if CONFIG_TEMPORAL_DENOISING
  1052. if (cpi->oxcf.noise_sensitivity > 0) {
  1053. vp8_denoiser_free(&cpi->denoiser);
  1054. if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
  1055. cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
  1056. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  1057. "Failed to allocate denoiser");
  1058. }
  1059. }
  1060. #endif
  1061. }
  1062. /* Quant MOD */
  1063. static const int q_trans[] = {
  1064. 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15, 17, 18, 19,
  1065. 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 35, 37, 39, 41,
  1066. 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 64, 67, 70, 73, 76, 79,
  1067. 82, 85, 88, 91, 94, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124, 127,
  1068. };
  1069. int vp8_reverse_trans(int x) {
  1070. int i;
  1071. for (i = 0; i < 64; ++i) {
  1072. if (q_trans[i] >= x) return i;
  1073. }
  1074. return 63;
  1075. }
  1076. void vp8_new_framerate(VP8_COMP *cpi, double framerate) {
  1077. if (framerate < .1) framerate = 30;
  1078. cpi->framerate = framerate;
  1079. cpi->output_framerate = framerate;
  1080. cpi->per_frame_bandwidth =
  1081. (int)(cpi->oxcf.target_bandwidth / cpi->output_framerate);
  1082. cpi->av_per_frame_bandwidth = cpi->per_frame_bandwidth;
  1083. cpi->min_frame_bandwidth = (int)(cpi->av_per_frame_bandwidth *
  1084. cpi->oxcf.two_pass_vbrmin_section / 100);
  1085. /* Set Maximum gf/arf interval */
  1086. cpi->max_gf_interval = ((int)(cpi->output_framerate / 2.0) + 2);
  1087. if (cpi->max_gf_interval < 12) cpi->max_gf_interval = 12;
  1088. /* Extended interval for genuinely static scenes */
  1089. cpi->twopass.static_scene_max_gf_interval = cpi->key_frame_frequency >> 1;
  1090. /* Special conditions when altr ref frame enabled in lagged compress mode */
  1091. if (cpi->oxcf.play_alternate && cpi->oxcf.lag_in_frames) {
  1092. if (cpi->max_gf_interval > cpi->oxcf.lag_in_frames - 1) {
  1093. cpi->max_gf_interval = cpi->oxcf.lag_in_frames - 1;
  1094. }
  1095. if (cpi->twopass.static_scene_max_gf_interval >
  1096. cpi->oxcf.lag_in_frames - 1) {
  1097. cpi->twopass.static_scene_max_gf_interval = cpi->oxcf.lag_in_frames - 1;
  1098. }
  1099. }
  1100. if (cpi->max_gf_interval > cpi->twopass.static_scene_max_gf_interval) {
  1101. cpi->max_gf_interval = cpi->twopass.static_scene_max_gf_interval;
  1102. }
  1103. }
  1104. static void init_config(VP8_COMP *cpi, VP8_CONFIG *oxcf) {
  1105. VP8_COMMON *cm = &cpi->common;
  1106. cpi->oxcf = *oxcf;
  1107. cpi->auto_gold = 1;
  1108. cpi->auto_adjust_gold_quantizer = 1;
  1109. cm->version = oxcf->Version;
  1110. vp8_setup_version(cm);
  1111. /* Frame rate is not available on the first frame, as it's derived from
  1112. * the observed timestamps. The actual value used here doesn't matter
  1113. * too much, as it will adapt quickly.
  1114. */
  1115. if (oxcf->timebase.num > 0) {
  1116. cpi->framerate =
  1117. (double)(oxcf->timebase.den) / (double)(oxcf->timebase.num);
  1118. } else {
  1119. cpi->framerate = 30;
  1120. }
  1121. /* If the reciprocal of the timebase seems like a reasonable framerate,
  1122. * then use that as a guess, otherwise use 30.
  1123. */
  1124. if (cpi->framerate > 180) cpi->framerate = 30;
  1125. cpi->ref_framerate = cpi->framerate;
  1126. cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
  1127. cm->refresh_golden_frame = 0;
  1128. cm->refresh_last_frame = 1;
  1129. cm->refresh_entropy_probs = 1;
  1130. /* change includes all joint functionality */
  1131. vp8_change_config(cpi, oxcf);
  1132. /* Initialize active best and worst q and average q values. */
  1133. cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
  1134. cpi->active_best_quality = cpi->oxcf.best_allowed_q;
  1135. cpi->avg_frame_qindex = cpi->oxcf.worst_allowed_q;
  1136. /* Initialise the starting buffer levels */
  1137. cpi->buffer_level = cpi->oxcf.starting_buffer_level;
  1138. cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
  1139. cpi->rolling_target_bits = cpi->av_per_frame_bandwidth;
  1140. cpi->rolling_actual_bits = cpi->av_per_frame_bandwidth;
  1141. cpi->long_rolling_target_bits = cpi->av_per_frame_bandwidth;
  1142. cpi->long_rolling_actual_bits = cpi->av_per_frame_bandwidth;
  1143. cpi->total_actual_bits = 0;
  1144. cpi->total_target_vs_actual = 0;
  1145. /* Temporal scalabilty */
  1146. if (cpi->oxcf.number_of_layers > 1) {
  1147. unsigned int i;
  1148. double prev_layer_framerate = 0;
  1149. for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
  1150. init_temporal_layer_context(cpi, oxcf, i, prev_layer_framerate);
  1151. prev_layer_framerate =
  1152. cpi->output_framerate / cpi->oxcf.rate_decimator[i];
  1153. }
  1154. }
  1155. #if VP8_TEMPORAL_ALT_REF
  1156. {
  1157. int i;
  1158. cpi->fixed_divide[0] = 0;
  1159. for (i = 1; i < 512; ++i) cpi->fixed_divide[i] = 0x80000 / i;
  1160. }
  1161. #endif
  1162. }
  1163. static void update_layer_contexts(VP8_COMP *cpi) {
  1164. VP8_CONFIG *oxcf = &cpi->oxcf;
  1165. /* Update snapshots of the layer contexts to reflect new parameters */
  1166. if (oxcf->number_of_layers > 1) {
  1167. unsigned int i;
  1168. double prev_layer_framerate = 0;
  1169. assert(oxcf->number_of_layers <= VPX_TS_MAX_LAYERS);
  1170. for (i = 0; i < oxcf->number_of_layers && i < VPX_TS_MAX_LAYERS; ++i) {
  1171. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  1172. lc->framerate = cpi->ref_framerate / oxcf->rate_decimator[i];
  1173. lc->target_bandwidth = oxcf->target_bitrate[i] * 1000;
  1174. lc->starting_buffer_level = rescale(
  1175. (int)oxcf->starting_buffer_level_in_ms, lc->target_bandwidth, 1000);
  1176. if (oxcf->optimal_buffer_level == 0) {
  1177. lc->optimal_buffer_level = lc->target_bandwidth / 8;
  1178. } else {
  1179. lc->optimal_buffer_level = rescale(
  1180. (int)oxcf->optimal_buffer_level_in_ms, lc->target_bandwidth, 1000);
  1181. }
  1182. if (oxcf->maximum_buffer_size == 0) {
  1183. lc->maximum_buffer_size = lc->target_bandwidth / 8;
  1184. } else {
  1185. lc->maximum_buffer_size = rescale((int)oxcf->maximum_buffer_size_in_ms,
  1186. lc->target_bandwidth, 1000);
  1187. }
  1188. /* Work out the average size of a frame within this layer */
  1189. if (i > 0) {
  1190. lc->avg_frame_size_for_layer =
  1191. (int)((oxcf->target_bitrate[i] - oxcf->target_bitrate[i - 1]) *
  1192. 1000 / (lc->framerate - prev_layer_framerate));
  1193. }
  1194. prev_layer_framerate = lc->framerate;
  1195. }
  1196. }
  1197. }
  1198. void vp8_change_config(VP8_COMP *cpi, VP8_CONFIG *oxcf) {
  1199. VP8_COMMON *cm = &cpi->common;
  1200. int last_w, last_h;
  1201. unsigned int prev_number_of_layers;
  1202. if (!cpi) return;
  1203. if (!oxcf) return;
  1204. if (cm->version != oxcf->Version) {
  1205. cm->version = oxcf->Version;
  1206. vp8_setup_version(cm);
  1207. }
  1208. last_w = cpi->oxcf.Width;
  1209. last_h = cpi->oxcf.Height;
  1210. prev_number_of_layers = cpi->oxcf.number_of_layers;
  1211. if (cpi->initial_width) {
  1212. // TODO(https://crbug.com/1486441): Allow changing thread counts; the
  1213. // allocation is done once in vp8_create_compressor().
  1214. oxcf->multi_threaded = cpi->oxcf.multi_threaded;
  1215. }
  1216. cpi->oxcf = *oxcf;
  1217. switch (cpi->oxcf.Mode) {
  1218. case MODE_REALTIME:
  1219. cpi->pass = 0;
  1220. cpi->compressor_speed = 2;
  1221. if (cpi->oxcf.cpu_used < -16) {
  1222. cpi->oxcf.cpu_used = -16;
  1223. }
  1224. if (cpi->oxcf.cpu_used > 16) cpi->oxcf.cpu_used = 16;
  1225. break;
  1226. case MODE_GOODQUALITY:
  1227. cpi->pass = 0;
  1228. cpi->compressor_speed = 1;
  1229. if (cpi->oxcf.cpu_used < -5) {
  1230. cpi->oxcf.cpu_used = -5;
  1231. }
  1232. if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
  1233. break;
  1234. case MODE_BESTQUALITY:
  1235. cpi->pass = 0;
  1236. cpi->compressor_speed = 0;
  1237. break;
  1238. case MODE_FIRSTPASS:
  1239. cpi->pass = 1;
  1240. cpi->compressor_speed = 1;
  1241. break;
  1242. case MODE_SECONDPASS:
  1243. cpi->pass = 2;
  1244. cpi->compressor_speed = 1;
  1245. if (cpi->oxcf.cpu_used < -5) {
  1246. cpi->oxcf.cpu_used = -5;
  1247. }
  1248. if (cpi->oxcf.cpu_used > 5) cpi->oxcf.cpu_used = 5;
  1249. break;
  1250. case MODE_SECONDPASS_BEST:
  1251. cpi->pass = 2;
  1252. cpi->compressor_speed = 0;
  1253. break;
  1254. }
  1255. if (cpi->pass == 0) cpi->auto_worst_q = 1;
  1256. cpi->oxcf.worst_allowed_q = q_trans[oxcf->worst_allowed_q];
  1257. cpi->oxcf.best_allowed_q = q_trans[oxcf->best_allowed_q];
  1258. cpi->oxcf.cq_level = q_trans[cpi->oxcf.cq_level];
  1259. if (oxcf->fixed_q >= 0) {
  1260. if (oxcf->worst_allowed_q < 0) {
  1261. cpi->oxcf.fixed_q = q_trans[0];
  1262. } else {
  1263. cpi->oxcf.fixed_q = q_trans[oxcf->worst_allowed_q];
  1264. }
  1265. if (oxcf->alt_q < 0) {
  1266. cpi->oxcf.alt_q = q_trans[0];
  1267. } else {
  1268. cpi->oxcf.alt_q = q_trans[oxcf->alt_q];
  1269. }
  1270. if (oxcf->key_q < 0) {
  1271. cpi->oxcf.key_q = q_trans[0];
  1272. } else {
  1273. cpi->oxcf.key_q = q_trans[oxcf->key_q];
  1274. }
  1275. if (oxcf->gold_q < 0) {
  1276. cpi->oxcf.gold_q = q_trans[0];
  1277. } else {
  1278. cpi->oxcf.gold_q = q_trans[oxcf->gold_q];
  1279. }
  1280. }
  1281. cpi->ext_refresh_frame_flags_pending = 0;
  1282. cpi->baseline_gf_interval =
  1283. cpi->oxcf.alt_freq ? cpi->oxcf.alt_freq : DEFAULT_GF_INTERVAL;
  1284. // GF behavior for 1 pass CBR, used when error_resilience is off.
  1285. if (!cpi->oxcf.error_resilient_mode &&
  1286. cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
  1287. cpi->oxcf.Mode == MODE_REALTIME)
  1288. cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
  1289. #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
  1290. cpi->oxcf.token_partitions = 3;
  1291. #endif
  1292. if (cpi->oxcf.token_partitions >= 0 && cpi->oxcf.token_partitions <= 3) {
  1293. cm->multi_token_partition = (TOKEN_PARTITION)cpi->oxcf.token_partitions;
  1294. }
  1295. setup_features(cpi);
  1296. if (!cpi->use_roi_static_threshold) {
  1297. int i;
  1298. for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
  1299. cpi->segment_encode_breakout[i] = cpi->oxcf.encode_breakout;
  1300. }
  1301. }
  1302. /* At the moment the first order values may not be > MAXQ */
  1303. if (cpi->oxcf.fixed_q > MAXQ) cpi->oxcf.fixed_q = MAXQ;
  1304. /* local file playback mode == really big buffer */
  1305. if (cpi->oxcf.end_usage == USAGE_LOCAL_FILE_PLAYBACK) {
  1306. cpi->oxcf.starting_buffer_level = 60000;
  1307. cpi->oxcf.optimal_buffer_level = 60000;
  1308. cpi->oxcf.maximum_buffer_size = 240000;
  1309. cpi->oxcf.starting_buffer_level_in_ms = 60000;
  1310. cpi->oxcf.optimal_buffer_level_in_ms = 60000;
  1311. cpi->oxcf.maximum_buffer_size_in_ms = 240000;
  1312. }
  1313. /* Convert target bandwidth from Kbit/s to Bit/s */
  1314. cpi->oxcf.target_bandwidth *= 1000;
  1315. cpi->oxcf.starting_buffer_level = rescale(
  1316. (int)cpi->oxcf.starting_buffer_level, cpi->oxcf.target_bandwidth, 1000);
  1317. /* Set or reset optimal and maximum buffer levels. */
  1318. if (cpi->oxcf.optimal_buffer_level == 0) {
  1319. cpi->oxcf.optimal_buffer_level = cpi->oxcf.target_bandwidth / 8;
  1320. } else {
  1321. cpi->oxcf.optimal_buffer_level = rescale(
  1322. (int)cpi->oxcf.optimal_buffer_level, cpi->oxcf.target_bandwidth, 1000);
  1323. }
  1324. if (cpi->oxcf.maximum_buffer_size == 0) {
  1325. cpi->oxcf.maximum_buffer_size = cpi->oxcf.target_bandwidth / 8;
  1326. } else {
  1327. cpi->oxcf.maximum_buffer_size = rescale((int)cpi->oxcf.maximum_buffer_size,
  1328. cpi->oxcf.target_bandwidth, 1000);
  1329. }
  1330. // Under a configuration change, where maximum_buffer_size may change,
  1331. // keep buffer level clipped to the maximum allowed buffer size.
  1332. if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
  1333. cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
  1334. cpi->buffer_level = cpi->bits_off_target;
  1335. }
  1336. /* Set up frame rate and related parameters rate control values. */
  1337. vp8_new_framerate(cpi, cpi->framerate);
  1338. /* Set absolute upper and lower quality limits */
  1339. cpi->worst_quality = cpi->oxcf.worst_allowed_q;
  1340. cpi->best_quality = cpi->oxcf.best_allowed_q;
  1341. /* active values should only be modified if out of new range */
  1342. if (cpi->active_worst_quality > cpi->oxcf.worst_allowed_q) {
  1343. cpi->active_worst_quality = cpi->oxcf.worst_allowed_q;
  1344. }
  1345. /* less likely */
  1346. else if (cpi->active_worst_quality < cpi->oxcf.best_allowed_q) {
  1347. cpi->active_worst_quality = cpi->oxcf.best_allowed_q;
  1348. }
  1349. if (cpi->active_best_quality < cpi->oxcf.best_allowed_q) {
  1350. cpi->active_best_quality = cpi->oxcf.best_allowed_q;
  1351. }
  1352. /* less likely */
  1353. else if (cpi->active_best_quality > cpi->oxcf.worst_allowed_q) {
  1354. cpi->active_best_quality = cpi->oxcf.worst_allowed_q;
  1355. }
  1356. cpi->buffered_mode = cpi->oxcf.optimal_buffer_level > 0;
  1357. cpi->cq_target_quality = cpi->oxcf.cq_level;
  1358. /* Only allow dropped frames in buffered mode */
  1359. cpi->drop_frames_allowed = cpi->oxcf.allow_df && cpi->buffered_mode;
  1360. cpi->target_bandwidth = cpi->oxcf.target_bandwidth;
  1361. // Check if the number of temporal layers has changed, and if so reset the
  1362. // pattern counter and set/initialize the temporal layer context for the
  1363. // new layer configuration.
  1364. if (cpi->oxcf.number_of_layers != prev_number_of_layers) {
  1365. // If the number of temporal layers are changed we must start at the
  1366. // base of the pattern cycle, so set the layer id to 0 and reset
  1367. // the temporal pattern counter.
  1368. if (cpi->temporal_layer_id > 0) {
  1369. cpi->temporal_layer_id = 0;
  1370. }
  1371. cpi->temporal_pattern_counter = 0;
  1372. reset_temporal_layer_change(cpi, oxcf, prev_number_of_layers);
  1373. }
  1374. if (!cpi->initial_width) {
  1375. cpi->initial_width = cpi->oxcf.Width;
  1376. cpi->initial_height = cpi->oxcf.Height;
  1377. }
  1378. cm->Width = cpi->oxcf.Width;
  1379. cm->Height = cpi->oxcf.Height;
  1380. assert(cm->Width <= cpi->initial_width);
  1381. assert(cm->Height <= cpi->initial_height);
  1382. /* TODO(jkoleszar): if an internal spatial resampling is active,
  1383. * and we downsize the input image, maybe we should clear the
  1384. * internal scale immediately rather than waiting for it to
  1385. * correct.
  1386. */
  1387. /* VP8 sharpness level mapping 0-7 (vs 0-10 in general VPx dialogs) */
  1388. if (cpi->oxcf.Sharpness > 7) cpi->oxcf.Sharpness = 7;
  1389. cm->sharpness_level = cpi->oxcf.Sharpness;
  1390. if (cm->horiz_scale != NORMAL || cm->vert_scale != NORMAL) {
  1391. int hr, hs, vr, vs;
  1392. Scale2Ratio(cm->horiz_scale, &hr, &hs);
  1393. Scale2Ratio(cm->vert_scale, &vr, &vs);
  1394. /* always go to the next whole number */
  1395. cm->Width = (hs - 1 + cpi->oxcf.Width * hr) / hs;
  1396. cm->Height = (vs - 1 + cpi->oxcf.Height * vr) / vs;
  1397. }
  1398. if (last_w != cpi->oxcf.Width || last_h != cpi->oxcf.Height) {
  1399. cpi->force_next_frame_intra = 1;
  1400. }
  1401. if (((cm->Width + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_width ||
  1402. ((cm->Height + 15) & ~15) != cm->yv12_fb[cm->lst_fb_idx].y_height ||
  1403. cm->yv12_fb[cm->lst_fb_idx].y_width == 0) {
  1404. dealloc_raw_frame_buffers(cpi);
  1405. alloc_raw_frame_buffers(cpi);
  1406. vp8_alloc_compressor_data(cpi);
  1407. }
  1408. if (cpi->oxcf.fixed_q >= 0) {
  1409. cpi->last_q[0] = cpi->oxcf.fixed_q;
  1410. cpi->last_q[1] = cpi->oxcf.fixed_q;
  1411. }
  1412. cpi->Speed = cpi->oxcf.cpu_used;
  1413. /* force to allowlag to 0 if lag_in_frames is 0; */
  1414. if (cpi->oxcf.lag_in_frames == 0) {
  1415. cpi->oxcf.allow_lag = 0;
  1416. }
  1417. /* Limit on lag buffers as these are not currently dynamically allocated */
  1418. else if (cpi->oxcf.lag_in_frames > MAX_LAG_BUFFERS) {
  1419. cpi->oxcf.lag_in_frames = MAX_LAG_BUFFERS;
  1420. }
  1421. /* YX Temp */
  1422. cpi->alt_ref_source = NULL;
  1423. cpi->is_src_frame_alt_ref = 0;
  1424. #if CONFIG_TEMPORAL_DENOISING
  1425. if (cpi->oxcf.noise_sensitivity) {
  1426. if (!cpi->denoiser.yv12_mc_running_avg.buffer_alloc) {
  1427. int width = (cpi->oxcf.Width + 15) & ~15;
  1428. int height = (cpi->oxcf.Height + 15) & ~15;
  1429. if (vp8_denoiser_allocate(&cpi->denoiser, width, height, cm->mb_rows,
  1430. cm->mb_cols, cpi->oxcf.noise_sensitivity)) {
  1431. vpx_internal_error(&cpi->common.error, VPX_CODEC_MEM_ERROR,
  1432. "Failed to allocate denoiser");
  1433. }
  1434. }
  1435. }
  1436. #endif
  1437. #if 0
  1438. /* Experimental RD Code */
  1439. cpi->frame_distortion = 0;
  1440. cpi->last_frame_distortion = 0;
  1441. #endif
  1442. }
  1443. #ifndef M_LOG2_E
  1444. #define M_LOG2_E 0.693147180559945309417
  1445. #endif
  1446. #define log2f(x) (log(x) / (float)M_LOG2_E)
  1447. static void cal_mvsadcosts(int *mvsadcost[2]) {
  1448. int i = 1;
  1449. mvsadcost[0][0] = 300;
  1450. mvsadcost[1][0] = 300;
  1451. do {
  1452. double z = 256 * (2 * (log2f(8 * i) + .6));
  1453. mvsadcost[0][i] = (int)z;
  1454. mvsadcost[1][i] = (int)z;
  1455. mvsadcost[0][-i] = (int)z;
  1456. mvsadcost[1][-i] = (int)z;
  1457. } while (++i <= mvfp_max);
  1458. }
  1459. struct VP8_COMP *vp8_create_compressor(VP8_CONFIG *oxcf) {
  1460. int i;
  1461. VP8_COMP *cpi;
  1462. VP8_COMMON *cm;
  1463. cpi = vpx_memalign(32, sizeof(VP8_COMP));
  1464. /* Check that the CPI instance is valid */
  1465. if (!cpi) return 0;
  1466. cm = &cpi->common;
  1467. memset(cpi, 0, sizeof(VP8_COMP));
  1468. if (setjmp(cm->error.jmp)) {
  1469. cpi->common.error.setjmp = 0;
  1470. vp8_remove_compressor(&cpi);
  1471. return 0;
  1472. }
  1473. cpi->common.error.setjmp = 1;
  1474. CHECK_MEM_ERROR(cpi->mb.ss, vpx_calloc(sizeof(search_site),
  1475. (MAX_MVSEARCH_STEPS * 8) + 1));
  1476. vp8_create_common(&cpi->common);
  1477. init_config(cpi, oxcf);
  1478. memcpy(cpi->base_skip_false_prob, vp8cx_base_skip_false_prob,
  1479. sizeof(vp8cx_base_skip_false_prob));
  1480. cpi->common.current_video_frame = 0;
  1481. cpi->temporal_pattern_counter = 0;
  1482. cpi->temporal_layer_id = -1;
  1483. cpi->kf_overspend_bits = 0;
  1484. cpi->kf_bitrate_adjustment = 0;
  1485. cpi->frames_till_gf_update_due = 0;
  1486. cpi->gf_overspend_bits = 0;
  1487. cpi->non_gf_bitrate_adjustment = 0;
  1488. cpi->prob_last_coded = 128;
  1489. cpi->prob_gf_coded = 128;
  1490. cpi->prob_intra_coded = 63;
  1491. /* Prime the recent reference frame usage counters.
  1492. * Hereafter they will be maintained as a sort of moving average
  1493. */
  1494. cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
  1495. cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
  1496. cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
  1497. cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
  1498. /* Set reference frame sign bias for ALTREF frame to 1 (for now) */
  1499. cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
  1500. cpi->twopass.gf_decay_rate = 0;
  1501. cpi->baseline_gf_interval = DEFAULT_GF_INTERVAL;
  1502. cpi->gold_is_last = 0;
  1503. cpi->alt_is_last = 0;
  1504. cpi->gold_is_alt = 0;
  1505. cpi->active_map_enabled = 0;
  1506. cpi->use_roi_static_threshold = 0;
  1507. #if 0
  1508. /* Experimental code for lagged and one pass */
  1509. /* Initialise one_pass GF frames stats */
  1510. /* Update stats used for GF selection */
  1511. if (cpi->pass == 0)
  1512. {
  1513. cpi->one_pass_frame_index = 0;
  1514. for (i = 0; i < MAX_LAG_BUFFERS; ++i)
  1515. {
  1516. cpi->one_pass_frame_stats[i].frames_so_far = 0;
  1517. cpi->one_pass_frame_stats[i].frame_intra_error = 0.0;
  1518. cpi->one_pass_frame_stats[i].frame_coded_error = 0.0;
  1519. cpi->one_pass_frame_stats[i].frame_pcnt_inter = 0.0;
  1520. cpi->one_pass_frame_stats[i].frame_pcnt_motion = 0.0;
  1521. cpi->one_pass_frame_stats[i].frame_mvr = 0.0;
  1522. cpi->one_pass_frame_stats[i].frame_mvr_abs = 0.0;
  1523. cpi->one_pass_frame_stats[i].frame_mvc = 0.0;
  1524. cpi->one_pass_frame_stats[i].frame_mvc_abs = 0.0;
  1525. }
  1526. }
  1527. #endif
  1528. cpi->mse_source_denoised = 0;
  1529. /* Should we use the cyclic refresh method.
  1530. * Currently there is no external control for this.
  1531. * Enable it for error_resilient_mode, or for 1 pass CBR mode.
  1532. */
  1533. cpi->cyclic_refresh_mode_enabled =
  1534. (cpi->oxcf.error_resilient_mode ||
  1535. (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER &&
  1536. cpi->oxcf.Mode <= 2));
  1537. cpi->cyclic_refresh_mode_max_mbs_perframe =
  1538. (cpi->common.mb_rows * cpi->common.mb_cols) / 7;
  1539. if (cpi->oxcf.number_of_layers == 1) {
  1540. cpi->cyclic_refresh_mode_max_mbs_perframe =
  1541. (cpi->common.mb_rows * cpi->common.mb_cols) / 20;
  1542. } else if (cpi->oxcf.number_of_layers == 2) {
  1543. cpi->cyclic_refresh_mode_max_mbs_perframe =
  1544. (cpi->common.mb_rows * cpi->common.mb_cols) / 10;
  1545. }
  1546. cpi->cyclic_refresh_mode_index = 0;
  1547. cpi->cyclic_refresh_q = 32;
  1548. // GF behavior for 1 pass CBR, used when error_resilience is off.
  1549. cpi->gf_update_onepass_cbr = 0;
  1550. cpi->gf_noboost_onepass_cbr = 0;
  1551. if (!cpi->oxcf.error_resilient_mode &&
  1552. cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER && cpi->oxcf.Mode <= 2) {
  1553. cpi->gf_update_onepass_cbr = 1;
  1554. cpi->gf_noboost_onepass_cbr = 1;
  1555. cpi->gf_interval_onepass_cbr =
  1556. cpi->cyclic_refresh_mode_max_mbs_perframe > 0
  1557. ? (2 * (cpi->common.mb_rows * cpi->common.mb_cols) /
  1558. cpi->cyclic_refresh_mode_max_mbs_perframe)
  1559. : 10;
  1560. cpi->gf_interval_onepass_cbr =
  1561. VPXMIN(40, VPXMAX(6, cpi->gf_interval_onepass_cbr));
  1562. cpi->baseline_gf_interval = cpi->gf_interval_onepass_cbr;
  1563. }
  1564. if (cpi->cyclic_refresh_mode_enabled) {
  1565. CHECK_MEM_ERROR(cpi->cyclic_refresh_map,
  1566. vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
  1567. } else {
  1568. cpi->cyclic_refresh_map = (signed char *)NULL;
  1569. }
  1570. CHECK_MEM_ERROR(cpi->skin_map, vpx_calloc(cm->mb_rows * cm->mb_cols,
  1571. sizeof(cpi->skin_map[0])));
  1572. CHECK_MEM_ERROR(cpi->consec_zero_last,
  1573. vpx_calloc(cm->mb_rows * cm->mb_cols, 1));
  1574. CHECK_MEM_ERROR(cpi->consec_zero_last_mvbias,
  1575. vpx_calloc((cpi->common.mb_rows * cpi->common.mb_cols), 1));
  1576. /*Initialize the feed-forward activity masking.*/
  1577. cpi->activity_avg = 90 << 12;
  1578. /* Give a sensible default for the first frame. */
  1579. cpi->frames_since_key = 8;
  1580. cpi->key_frame_frequency = cpi->oxcf.key_freq;
  1581. cpi->this_key_frame_forced = 0;
  1582. cpi->next_key_frame_forced = 0;
  1583. cpi->source_alt_ref_pending = 0;
  1584. cpi->source_alt_ref_active = 0;
  1585. cpi->common.refresh_alt_ref_frame = 0;
  1586. cpi->force_maxqp = 0;
  1587. cpi->frames_since_last_drop_overshoot = 0;
  1588. cpi->b_calculate_psnr = CONFIG_INTERNAL_STATS;
  1589. #if CONFIG_INTERNAL_STATS
  1590. cpi->b_calculate_ssimg = 0;
  1591. cpi->count = 0;
  1592. cpi->bytes = 0;
  1593. if (cpi->b_calculate_psnr) {
  1594. cpi->total_sq_error = 0.0;
  1595. cpi->total_sq_error2 = 0.0;
  1596. cpi->total_y = 0.0;
  1597. cpi->total_u = 0.0;
  1598. cpi->total_v = 0.0;
  1599. cpi->total = 0.0;
  1600. cpi->totalp_y = 0.0;
  1601. cpi->totalp_u = 0.0;
  1602. cpi->totalp_v = 0.0;
  1603. cpi->totalp = 0.0;
  1604. cpi->tot_recode_hits = 0;
  1605. cpi->summed_quality = 0;
  1606. cpi->summed_weights = 0;
  1607. }
  1608. #endif
  1609. cpi->first_time_stamp_ever = 0x7FFFFFFF;
  1610. cpi->frames_till_gf_update_due = 0;
  1611. cpi->key_frame_count = 1;
  1612. cpi->ni_av_qi = cpi->oxcf.worst_allowed_q;
  1613. cpi->ni_tot_qi = 0;
  1614. cpi->ni_frames = 0;
  1615. cpi->total_byte_count = 0;
  1616. cpi->drop_frame = 0;
  1617. cpi->rate_correction_factor = 1.0;
  1618. cpi->key_frame_rate_correction_factor = 1.0;
  1619. cpi->gf_rate_correction_factor = 1.0;
  1620. cpi->twopass.est_max_qcorrection_factor = 1.0;
  1621. for (i = 0; i < KEY_FRAME_CONTEXT; ++i) {
  1622. cpi->prior_key_frame_distance[i] = (int)cpi->output_framerate;
  1623. }
  1624. #ifdef OUTPUT_YUV_SRC
  1625. yuv_file = fopen("bd.yuv", "ab");
  1626. #endif
  1627. #ifdef OUTPUT_YUV_DENOISED
  1628. yuv_denoised_file = fopen("denoised.yuv", "ab");
  1629. #endif
  1630. #ifdef OUTPUT_YUV_SKINMAP
  1631. yuv_skinmap_file = fopen("skinmap.yuv", "wb");
  1632. #endif
  1633. #if 0
  1634. framepsnr = fopen("framepsnr.stt", "a");
  1635. kf_list = fopen("kf_list.stt", "w");
  1636. #endif
  1637. cpi->output_pkt_list = oxcf->output_pkt_list;
  1638. #if !CONFIG_REALTIME_ONLY
  1639. if (cpi->pass == 1) {
  1640. vp8_init_first_pass(cpi);
  1641. } else if (cpi->pass == 2) {
  1642. size_t packet_sz = sizeof(FIRSTPASS_STATS);
  1643. int packets = (int)(oxcf->two_pass_stats_in.sz / packet_sz);
  1644. cpi->twopass.stats_in_start = oxcf->two_pass_stats_in.buf;
  1645. cpi->twopass.stats_in = cpi->twopass.stats_in_start;
  1646. cpi->twopass.stats_in_end =
  1647. (void *)((char *)cpi->twopass.stats_in + (packets - 1) * packet_sz);
  1648. vp8_init_second_pass(cpi);
  1649. }
  1650. #endif
  1651. if (cpi->compressor_speed == 2) {
  1652. cpi->avg_encode_time = 0;
  1653. cpi->avg_pick_mode_time = 0;
  1654. }
  1655. vp8_set_speed_features(cpi);
  1656. /* Set starting values of RD threshold multipliers (128 = *1) */
  1657. for (i = 0; i < MAX_MODES; ++i) {
  1658. cpi->mb.rd_thresh_mult[i] = 128;
  1659. }
  1660. #if CONFIG_MULTITHREAD
  1661. if (vp8cx_create_encoder_threads(cpi)) {
  1662. vp8_remove_compressor(&cpi);
  1663. return 0;
  1664. }
  1665. #endif
  1666. cpi->fn_ptr[BLOCK_16X16].sdf = vpx_sad16x16;
  1667. cpi->fn_ptr[BLOCK_16X16].vf = vpx_variance16x16;
  1668. cpi->fn_ptr[BLOCK_16X16].svf = vpx_sub_pixel_variance16x16;
  1669. cpi->fn_ptr[BLOCK_16X16].sdx3f = vpx_sad16x16x3;
  1670. cpi->fn_ptr[BLOCK_16X16].sdx8f = vpx_sad16x16x8;
  1671. cpi->fn_ptr[BLOCK_16X16].sdx4df = vpx_sad16x16x4d;
  1672. cpi->fn_ptr[BLOCK_16X8].sdf = vpx_sad16x8;
  1673. cpi->fn_ptr[BLOCK_16X8].vf = vpx_variance16x8;
  1674. cpi->fn_ptr[BLOCK_16X8].svf = vpx_sub_pixel_variance16x8;
  1675. cpi->fn_ptr[BLOCK_16X8].sdx3f = vpx_sad16x8x3;
  1676. cpi->fn_ptr[BLOCK_16X8].sdx8f = vpx_sad16x8x8;
  1677. cpi->fn_ptr[BLOCK_16X8].sdx4df = vpx_sad16x8x4d;
  1678. cpi->fn_ptr[BLOCK_8X16].sdf = vpx_sad8x16;
  1679. cpi->fn_ptr[BLOCK_8X16].vf = vpx_variance8x16;
  1680. cpi->fn_ptr[BLOCK_8X16].svf = vpx_sub_pixel_variance8x16;
  1681. cpi->fn_ptr[BLOCK_8X16].sdx3f = vpx_sad8x16x3;
  1682. cpi->fn_ptr[BLOCK_8X16].sdx8f = vpx_sad8x16x8;
  1683. cpi->fn_ptr[BLOCK_8X16].sdx4df = vpx_sad8x16x4d;
  1684. cpi->fn_ptr[BLOCK_8X8].sdf = vpx_sad8x8;
  1685. cpi->fn_ptr[BLOCK_8X8].vf = vpx_variance8x8;
  1686. cpi->fn_ptr[BLOCK_8X8].svf = vpx_sub_pixel_variance8x8;
  1687. cpi->fn_ptr[BLOCK_8X8].sdx3f = vpx_sad8x8x3;
  1688. cpi->fn_ptr[BLOCK_8X8].sdx8f = vpx_sad8x8x8;
  1689. cpi->fn_ptr[BLOCK_8X8].sdx4df = vpx_sad8x8x4d;
  1690. cpi->fn_ptr[BLOCK_4X4].sdf = vpx_sad4x4;
  1691. cpi->fn_ptr[BLOCK_4X4].vf = vpx_variance4x4;
  1692. cpi->fn_ptr[BLOCK_4X4].svf = vpx_sub_pixel_variance4x4;
  1693. cpi->fn_ptr[BLOCK_4X4].sdx3f = vpx_sad4x4x3;
  1694. cpi->fn_ptr[BLOCK_4X4].sdx8f = vpx_sad4x4x8;
  1695. cpi->fn_ptr[BLOCK_4X4].sdx4df = vpx_sad4x4x4d;
  1696. #if ARCH_X86 || ARCH_X86_64
  1697. cpi->fn_ptr[BLOCK_16X16].copymem = vp8_copy32xn;
  1698. cpi->fn_ptr[BLOCK_16X8].copymem = vp8_copy32xn;
  1699. cpi->fn_ptr[BLOCK_8X16].copymem = vp8_copy32xn;
  1700. cpi->fn_ptr[BLOCK_8X8].copymem = vp8_copy32xn;
  1701. cpi->fn_ptr[BLOCK_4X4].copymem = vp8_copy32xn;
  1702. #endif
  1703. cpi->full_search_sad = vp8_full_search_sad;
  1704. cpi->diamond_search_sad = vp8_diamond_search_sad;
  1705. cpi->refining_search_sad = vp8_refining_search_sad;
  1706. /* make sure frame 1 is okay */
  1707. cpi->mb.error_bins[0] = cpi->common.MBs;
  1708. /* vp8cx_init_quantizer() is first called here. Add check in
  1709. * vp8cx_frame_init_quantizer() so that vp8cx_init_quantizer is only
  1710. * called later when needed. This will avoid unnecessary calls of
  1711. * vp8cx_init_quantizer() for every frame.
  1712. */
  1713. vp8cx_init_quantizer(cpi);
  1714. vp8_loop_filter_init(cm);
  1715. cpi->common.error.setjmp = 0;
  1716. #if CONFIG_MULTI_RES_ENCODING
  1717. /* Calculate # of MBs in a row in lower-resolution level image. */
  1718. if (cpi->oxcf.mr_encoder_id > 0) vp8_cal_low_res_mb_cols(cpi);
  1719. #endif
  1720. /* setup RD costs to MACROBLOCK struct */
  1721. cpi->mb.mvcost[0] = &cpi->rd_costs.mvcosts[0][mv_max + 1];
  1722. cpi->mb.mvcost[1] = &cpi->rd_costs.mvcosts[1][mv_max + 1];
  1723. cpi->mb.mvsadcost[0] = &cpi->rd_costs.mvsadcosts[0][mvfp_max + 1];
  1724. cpi->mb.mvsadcost[1] = &cpi->rd_costs.mvsadcosts[1][mvfp_max + 1];
  1725. cal_mvsadcosts(cpi->mb.mvsadcost);
  1726. cpi->mb.mbmode_cost = cpi->rd_costs.mbmode_cost;
  1727. cpi->mb.intra_uv_mode_cost = cpi->rd_costs.intra_uv_mode_cost;
  1728. cpi->mb.bmode_costs = cpi->rd_costs.bmode_costs;
  1729. cpi->mb.inter_bmode_costs = cpi->rd_costs.inter_bmode_costs;
  1730. cpi->mb.token_costs = cpi->rd_costs.token_costs;
  1731. /* setup block ptrs & offsets */
  1732. vp8_setup_block_ptrs(&cpi->mb);
  1733. vp8_setup_block_dptrs(&cpi->mb.e_mbd);
  1734. return cpi;
  1735. }
  1736. void vp8_remove_compressor(VP8_COMP **comp) {
  1737. VP8_COMP *cpi = *comp;
  1738. if (!cpi) return;
  1739. if (cpi && (cpi->common.current_video_frame > 0)) {
  1740. #if !CONFIG_REALTIME_ONLY
  1741. if (cpi->pass == 2) {
  1742. vp8_end_second_pass(cpi);
  1743. }
  1744. #endif
  1745. #if CONFIG_INTERNAL_STATS
  1746. if (cpi->pass != 1) {
  1747. FILE *f = fopen("opsnr.stt", "a");
  1748. double time_encoded =
  1749. (cpi->last_end_time_stamp_seen - cpi->first_time_stamp_ever) /
  1750. 10000000.000;
  1751. double dr = (double)cpi->bytes * 8.0 / 1000.0 / time_encoded;
  1752. if (cpi->b_calculate_psnr) {
  1753. if (cpi->oxcf.number_of_layers > 1) {
  1754. int i;
  1755. fprintf(f,
  1756. "Layer\tBitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
  1757. "GLPsnrP\tVPXSSIM\n");
  1758. for (i = 0; i < (int)cpi->oxcf.number_of_layers; ++i) {
  1759. double dr =
  1760. (double)cpi->bytes_in_layer[i] * 8.0 / 1000.0 / time_encoded;
  1761. double samples = 3.0 / 2 * cpi->frames_in_layer[i] *
  1762. cpi->common.Width * cpi->common.Height;
  1763. double total_psnr =
  1764. vpx_sse_to_psnr(samples, 255.0, cpi->total_error2[i]);
  1765. double total_psnr2 =
  1766. vpx_sse_to_psnr(samples, 255.0, cpi->total_error2_p[i]);
  1767. double total_ssim =
  1768. 100 * pow(cpi->sum_ssim[i] / cpi->sum_weights[i], 8.0);
  1769. fprintf(f,
  1770. "%5d\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
  1771. "%7.3f\t%7.3f\n",
  1772. i, dr, cpi->sum_psnr[i] / cpi->frames_in_layer[i],
  1773. total_psnr, cpi->sum_psnr_p[i] / cpi->frames_in_layer[i],
  1774. total_psnr2, total_ssim);
  1775. }
  1776. } else {
  1777. double samples =
  1778. 3.0 / 2 * cpi->count * cpi->common.Width * cpi->common.Height;
  1779. double total_psnr =
  1780. vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error);
  1781. double total_psnr2 =
  1782. vpx_sse_to_psnr(samples, 255.0, cpi->total_sq_error2);
  1783. double total_ssim =
  1784. 100 * pow(cpi->summed_quality / cpi->summed_weights, 8.0);
  1785. fprintf(f,
  1786. "Bitrate\tAVGPsnr\tGLBPsnr\tAVPsnrP\t"
  1787. "GLPsnrP\tVPXSSIM\n");
  1788. fprintf(f,
  1789. "%7.3f\t%7.3f\t%7.3f\t%7.3f\t%7.3f\t"
  1790. "%7.3f\n",
  1791. dr, cpi->total / cpi->count, total_psnr,
  1792. cpi->totalp / cpi->count, total_psnr2, total_ssim);
  1793. }
  1794. }
  1795. fclose(f);
  1796. #if 0
  1797. f = fopen("qskip.stt", "a");
  1798. fprintf(f, "minq:%d -maxq:%d skiptrue:skipfalse = %d:%d\n", cpi->oxcf.best_allowed_q, cpi->oxcf.worst_allowed_q, skiptruecount, skipfalsecount);
  1799. fclose(f);
  1800. #endif
  1801. }
  1802. #endif
  1803. #ifdef SPEEDSTATS
  1804. if (cpi->compressor_speed == 2) {
  1805. int i;
  1806. FILE *f = fopen("cxspeed.stt", "a");
  1807. cnt_pm /= cpi->common.MBs;
  1808. for (i = 0; i < 16; ++i) fprintf(f, "%5d", frames_at_speed[i]);
  1809. fprintf(f, "\n");
  1810. fclose(f);
  1811. }
  1812. #endif
  1813. #ifdef MODE_STATS
  1814. {
  1815. extern int count_mb_seg[4];
  1816. FILE *f = fopen("modes.stt", "a");
  1817. double dr = (double)cpi->framerate * (double)bytes * (double)8 /
  1818. (double)count / (double)1000;
  1819. fprintf(f, "intra_mode in Intra Frames:\n");
  1820. fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d\n", y_modes[0], y_modes[1],
  1821. y_modes[2], y_modes[3], y_modes[4]);
  1822. fprintf(f, "UV:%8d, %8d, %8d, %8d\n", uv_modes[0], uv_modes[1],
  1823. uv_modes[2], uv_modes[3]);
  1824. fprintf(f, "B: ");
  1825. {
  1826. int i;
  1827. for (i = 0; i < 10; ++i) fprintf(f, "%8d, ", b_modes[i]);
  1828. fprintf(f, "\n");
  1829. }
  1830. fprintf(f, "Modes in Inter Frames:\n");
  1831. fprintf(f, "Y: %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d, %8d\n",
  1832. inter_y_modes[0], inter_y_modes[1], inter_y_modes[2],
  1833. inter_y_modes[3], inter_y_modes[4], inter_y_modes[5],
  1834. inter_y_modes[6], inter_y_modes[7], inter_y_modes[8],
  1835. inter_y_modes[9]);
  1836. fprintf(f, "UV:%8d, %8d, %8d, %8d\n", inter_uv_modes[0],
  1837. inter_uv_modes[1], inter_uv_modes[2], inter_uv_modes[3]);
  1838. fprintf(f, "B: ");
  1839. {
  1840. int i;
  1841. for (i = 0; i < 15; ++i) fprintf(f, "%8d, ", inter_b_modes[i]);
  1842. fprintf(f, "\n");
  1843. }
  1844. fprintf(f, "P:%8d, %8d, %8d, %8d\n", count_mb_seg[0], count_mb_seg[1],
  1845. count_mb_seg[2], count_mb_seg[3]);
  1846. fprintf(f, "PB:%8d, %8d, %8d, %8d\n", inter_b_modes[LEFT4X4],
  1847. inter_b_modes[ABOVE4X4], inter_b_modes[ZERO4X4],
  1848. inter_b_modes[NEW4X4]);
  1849. fclose(f);
  1850. }
  1851. #endif
  1852. #if defined(SECTIONBITS_OUTPUT)
  1853. if (0) {
  1854. int i;
  1855. FILE *f = fopen("tokenbits.stt", "a");
  1856. for (i = 0; i < 28; ++i) fprintf(f, "%8d", (int)(Sectionbits[i] / 256));
  1857. fprintf(f, "\n");
  1858. fclose(f);
  1859. }
  1860. #endif
  1861. #if 0
  1862. {
  1863. printf("\n_pick_loop_filter_level:%d\n", cpi->time_pick_lpf / 1000);
  1864. printf("\n_frames recive_data encod_mb_row compress_frame Total\n");
  1865. printf("%6d %10ld %10ld %10ld %10ld\n", cpi->common.current_video_frame, cpi->time_receive_data / 1000, cpi->time_encode_mb_row / 1000, cpi->time_compress_data / 1000, (cpi->time_receive_data + cpi->time_compress_data) / 1000);
  1866. }
  1867. #endif
  1868. }
  1869. #if CONFIG_MULTITHREAD
  1870. vp8cx_remove_encoder_threads(cpi);
  1871. #endif
  1872. #if CONFIG_TEMPORAL_DENOISING
  1873. vp8_denoiser_free(&cpi->denoiser);
  1874. #endif
  1875. dealloc_compressor_data(cpi);
  1876. vpx_free(cpi->mb.ss);
  1877. vpx_free(cpi->tok);
  1878. vpx_free(cpi->skin_map);
  1879. vpx_free(cpi->cyclic_refresh_map);
  1880. vpx_free(cpi->consec_zero_last);
  1881. vpx_free(cpi->consec_zero_last_mvbias);
  1882. vp8_remove_common(&cpi->common);
  1883. vpx_free(cpi);
  1884. *comp = 0;
  1885. #ifdef OUTPUT_YUV_SRC
  1886. fclose(yuv_file);
  1887. #endif
  1888. #ifdef OUTPUT_YUV_DENOISED
  1889. fclose(yuv_denoised_file);
  1890. #endif
  1891. #ifdef OUTPUT_YUV_SKINMAP
  1892. fclose(yuv_skinmap_file);
  1893. #endif
  1894. #if 0
  1895. if (keyfile)
  1896. fclose(keyfile);
  1897. if (framepsnr)
  1898. fclose(framepsnr);
  1899. if (kf_list)
  1900. fclose(kf_list);
  1901. #endif
  1902. }
  1903. static uint64_t calc_plane_error(unsigned char *orig, int orig_stride,
  1904. unsigned char *recon, int recon_stride,
  1905. unsigned int cols, unsigned int rows) {
  1906. unsigned int row, col;
  1907. uint64_t total_sse = 0;
  1908. int diff;
  1909. for (row = 0; row + 16 <= rows; row += 16) {
  1910. for (col = 0; col + 16 <= cols; col += 16) {
  1911. unsigned int sse;
  1912. vpx_mse16x16(orig + col, orig_stride, recon + col, recon_stride, &sse);
  1913. total_sse += sse;
  1914. }
  1915. /* Handle odd-sized width */
  1916. if (col < cols) {
  1917. unsigned int border_row, border_col;
  1918. unsigned char *border_orig = orig;
  1919. unsigned char *border_recon = recon;
  1920. for (border_row = 0; border_row < 16; ++border_row) {
  1921. for (border_col = col; border_col < cols; ++border_col) {
  1922. diff = border_orig[border_col] - border_recon[border_col];
  1923. total_sse += diff * diff;
  1924. }
  1925. border_orig += orig_stride;
  1926. border_recon += recon_stride;
  1927. }
  1928. }
  1929. orig += orig_stride * 16;
  1930. recon += recon_stride * 16;
  1931. }
  1932. /* Handle odd-sized height */
  1933. for (; row < rows; ++row) {
  1934. for (col = 0; col < cols; ++col) {
  1935. diff = orig[col] - recon[col];
  1936. total_sse += diff * diff;
  1937. }
  1938. orig += orig_stride;
  1939. recon += recon_stride;
  1940. }
  1941. vpx_clear_system_state();
  1942. return total_sse;
  1943. }
  1944. static void generate_psnr_packet(VP8_COMP *cpi) {
  1945. YV12_BUFFER_CONFIG *orig = cpi->Source;
  1946. YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
  1947. struct vpx_codec_cx_pkt pkt;
  1948. uint64_t sse;
  1949. int i;
  1950. unsigned int width = cpi->common.Width;
  1951. unsigned int height = cpi->common.Height;
  1952. pkt.kind = VPX_CODEC_PSNR_PKT;
  1953. sse = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
  1954. recon->y_stride, width, height);
  1955. pkt.data.psnr.sse[0] = sse;
  1956. pkt.data.psnr.sse[1] = sse;
  1957. pkt.data.psnr.samples[0] = width * height;
  1958. pkt.data.psnr.samples[1] = width * height;
  1959. width = (width + 1) / 2;
  1960. height = (height + 1) / 2;
  1961. sse = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
  1962. recon->uv_stride, width, height);
  1963. pkt.data.psnr.sse[0] += sse;
  1964. pkt.data.psnr.sse[2] = sse;
  1965. pkt.data.psnr.samples[0] += width * height;
  1966. pkt.data.psnr.samples[2] = width * height;
  1967. sse = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
  1968. recon->uv_stride, width, height);
  1969. pkt.data.psnr.sse[0] += sse;
  1970. pkt.data.psnr.sse[3] = sse;
  1971. pkt.data.psnr.samples[0] += width * height;
  1972. pkt.data.psnr.samples[3] = width * height;
  1973. for (i = 0; i < 4; ++i) {
  1974. pkt.data.psnr.psnr[i] = vpx_sse_to_psnr(pkt.data.psnr.samples[i], 255.0,
  1975. (double)(pkt.data.psnr.sse[i]));
  1976. }
  1977. vpx_codec_pkt_list_add(cpi->output_pkt_list, &pkt);
  1978. }
  1979. int vp8_use_as_reference(VP8_COMP *cpi, int ref_frame_flags) {
  1980. if (ref_frame_flags > 7) return -1;
  1981. cpi->ref_frame_flags = ref_frame_flags;
  1982. return 0;
  1983. }
  1984. int vp8_update_reference(VP8_COMP *cpi, int ref_frame_flags) {
  1985. if (ref_frame_flags > 7) return -1;
  1986. cpi->common.refresh_golden_frame = 0;
  1987. cpi->common.refresh_alt_ref_frame = 0;
  1988. cpi->common.refresh_last_frame = 0;
  1989. if (ref_frame_flags & VP8_LAST_FRAME) cpi->common.refresh_last_frame = 1;
  1990. if (ref_frame_flags & VP8_GOLD_FRAME) cpi->common.refresh_golden_frame = 1;
  1991. if (ref_frame_flags & VP8_ALTR_FRAME) cpi->common.refresh_alt_ref_frame = 1;
  1992. cpi->ext_refresh_frame_flags_pending = 1;
  1993. return 0;
  1994. }
  1995. int vp8_get_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
  1996. YV12_BUFFER_CONFIG *sd) {
  1997. VP8_COMMON *cm = &cpi->common;
  1998. int ref_fb_idx;
  1999. if (ref_frame_flag == VP8_LAST_FRAME) {
  2000. ref_fb_idx = cm->lst_fb_idx;
  2001. } else if (ref_frame_flag == VP8_GOLD_FRAME) {
  2002. ref_fb_idx = cm->gld_fb_idx;
  2003. } else if (ref_frame_flag == VP8_ALTR_FRAME) {
  2004. ref_fb_idx = cm->alt_fb_idx;
  2005. } else {
  2006. return -1;
  2007. }
  2008. vp8_yv12_copy_frame(&cm->yv12_fb[ref_fb_idx], sd);
  2009. return 0;
  2010. }
  2011. int vp8_set_reference(VP8_COMP *cpi, enum vpx_ref_frame_type ref_frame_flag,
  2012. YV12_BUFFER_CONFIG *sd) {
  2013. VP8_COMMON *cm = &cpi->common;
  2014. int ref_fb_idx;
  2015. if (ref_frame_flag == VP8_LAST_FRAME) {
  2016. ref_fb_idx = cm->lst_fb_idx;
  2017. } else if (ref_frame_flag == VP8_GOLD_FRAME) {
  2018. ref_fb_idx = cm->gld_fb_idx;
  2019. } else if (ref_frame_flag == VP8_ALTR_FRAME) {
  2020. ref_fb_idx = cm->alt_fb_idx;
  2021. } else {
  2022. return -1;
  2023. }
  2024. vp8_yv12_copy_frame(sd, &cm->yv12_fb[ref_fb_idx]);
  2025. return 0;
  2026. }
  2027. int vp8_update_entropy(VP8_COMP *cpi, int update) {
  2028. VP8_COMMON *cm = &cpi->common;
  2029. cm->refresh_entropy_probs = update;
  2030. return 0;
  2031. }
  2032. static void scale_and_extend_source(YV12_BUFFER_CONFIG *sd, VP8_COMP *cpi) {
  2033. VP8_COMMON *cm = &cpi->common;
  2034. /* are we resizing the image */
  2035. if (cm->horiz_scale != 0 || cm->vert_scale != 0) {
  2036. #if CONFIG_SPATIAL_RESAMPLING
  2037. int hr, hs, vr, vs;
  2038. int tmp_height;
  2039. if (cm->vert_scale == 3) {
  2040. tmp_height = 9;
  2041. } else {
  2042. tmp_height = 11;
  2043. }
  2044. Scale2Ratio(cm->horiz_scale, &hr, &hs);
  2045. Scale2Ratio(cm->vert_scale, &vr, &vs);
  2046. vpx_scale_frame(sd, &cpi->scaled_source, cm->temp_scale_frame.y_buffer,
  2047. tmp_height, hs, hr, vs, vr, 0);
  2048. vp8_yv12_extend_frame_borders(&cpi->scaled_source);
  2049. cpi->Source = &cpi->scaled_source;
  2050. #endif
  2051. } else {
  2052. cpi->Source = sd;
  2053. }
  2054. }
  2055. static int resize_key_frame(VP8_COMP *cpi) {
  2056. #if CONFIG_SPATIAL_RESAMPLING
  2057. VP8_COMMON *cm = &cpi->common;
  2058. /* Do we need to apply resampling for one pass cbr.
  2059. * In one pass this is more limited than in two pass cbr.
  2060. * The test and any change is only made once per key frame sequence.
  2061. */
  2062. if (cpi->oxcf.allow_spatial_resampling &&
  2063. (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) {
  2064. int hr, hs, vr, vs;
  2065. int new_width, new_height;
  2066. /* If we are below the resample DOWN watermark then scale down a
  2067. * notch.
  2068. */
  2069. if (cpi->buffer_level < (cpi->oxcf.resample_down_water_mark *
  2070. cpi->oxcf.optimal_buffer_level / 100)) {
  2071. cm->horiz_scale =
  2072. (cm->horiz_scale < ONETWO) ? cm->horiz_scale + 1 : ONETWO;
  2073. cm->vert_scale = (cm->vert_scale < ONETWO) ? cm->vert_scale + 1 : ONETWO;
  2074. }
  2075. /* Should we now start scaling back up */
  2076. else if (cpi->buffer_level > (cpi->oxcf.resample_up_water_mark *
  2077. cpi->oxcf.optimal_buffer_level / 100)) {
  2078. cm->horiz_scale =
  2079. (cm->horiz_scale > NORMAL) ? cm->horiz_scale - 1 : NORMAL;
  2080. cm->vert_scale = (cm->vert_scale > NORMAL) ? cm->vert_scale - 1 : NORMAL;
  2081. }
  2082. /* Get the new height and width */
  2083. Scale2Ratio(cm->horiz_scale, &hr, &hs);
  2084. Scale2Ratio(cm->vert_scale, &vr, &vs);
  2085. new_width = ((hs - 1) + (cpi->oxcf.Width * hr)) / hs;
  2086. new_height = ((vs - 1) + (cpi->oxcf.Height * vr)) / vs;
  2087. /* If the image size has changed we need to reallocate the buffers
  2088. * and resample the source image
  2089. */
  2090. if ((cm->Width != new_width) || (cm->Height != new_height)) {
  2091. cm->Width = new_width;
  2092. cm->Height = new_height;
  2093. vp8_alloc_compressor_data(cpi);
  2094. scale_and_extend_source(cpi->un_scaled_source, cpi);
  2095. return 1;
  2096. }
  2097. }
  2098. #endif
  2099. return 0;
  2100. }
  2101. static void update_alt_ref_frame_stats(VP8_COMP *cpi) {
  2102. VP8_COMMON *cm = &cpi->common;
  2103. /* Select an interval before next GF or altref */
  2104. if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
  2105. if ((cpi->pass != 2) && cpi->frames_till_gf_update_due) {
  2106. cpi->current_gf_interval = cpi->frames_till_gf_update_due;
  2107. /* Set the bits per frame that we should try and recover in
  2108. * subsequent inter frames to account for the extra GF spend...
  2109. * note that his does not apply for GF updates that occur
  2110. * coincident with a key frame as the extra cost of key frames is
  2111. * dealt with elsewhere.
  2112. */
  2113. cpi->gf_overspend_bits += cpi->projected_frame_size;
  2114. cpi->non_gf_bitrate_adjustment =
  2115. cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
  2116. }
  2117. /* Update data structure that monitors level of reference to last GF */
  2118. memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
  2119. cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
  2120. /* this frame refreshes means next frames don't unless specified by user */
  2121. cpi->frames_since_golden = 0;
  2122. /* Clear the alternate reference update pending flag. */
  2123. cpi->source_alt_ref_pending = 0;
  2124. /* Set the alternate reference frame active flag */
  2125. cpi->source_alt_ref_active = 1;
  2126. }
  2127. static void update_golden_frame_stats(VP8_COMP *cpi) {
  2128. VP8_COMMON *cm = &cpi->common;
  2129. /* Update the Golden frame usage counts. */
  2130. if (cm->refresh_golden_frame) {
  2131. /* Select an interval before next GF */
  2132. if (!cpi->auto_gold) cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
  2133. if ((cpi->pass != 2) && (cpi->frames_till_gf_update_due > 0)) {
  2134. cpi->current_gf_interval = cpi->frames_till_gf_update_due;
  2135. /* Set the bits per frame that we should try and recover in
  2136. * subsequent inter frames to account for the extra GF spend...
  2137. * note that his does not apply for GF updates that occur
  2138. * coincident with a key frame as the extra cost of key frames
  2139. * is dealt with elsewhere.
  2140. */
  2141. if ((cm->frame_type != KEY_FRAME) && !cpi->source_alt_ref_active) {
  2142. /* Calcluate GF bits to be recovered
  2143. * Projected size - av frame bits available for inter
  2144. * frames for clip as a whole
  2145. */
  2146. cpi->gf_overspend_bits +=
  2147. (cpi->projected_frame_size - cpi->inter_frame_target);
  2148. }
  2149. cpi->non_gf_bitrate_adjustment =
  2150. cpi->gf_overspend_bits / cpi->frames_till_gf_update_due;
  2151. }
  2152. /* Update data structure that monitors level of reference to last GF */
  2153. memset(cpi->gf_active_flags, 1, (cm->mb_rows * cm->mb_cols));
  2154. cpi->gf_active_count = cm->mb_rows * cm->mb_cols;
  2155. /* this frame refreshes means next frames don't unless specified by
  2156. * user
  2157. */
  2158. cm->refresh_golden_frame = 0;
  2159. cpi->frames_since_golden = 0;
  2160. cpi->recent_ref_frame_usage[INTRA_FRAME] = 1;
  2161. cpi->recent_ref_frame_usage[LAST_FRAME] = 1;
  2162. cpi->recent_ref_frame_usage[GOLDEN_FRAME] = 1;
  2163. cpi->recent_ref_frame_usage[ALTREF_FRAME] = 1;
  2164. /* ******** Fixed Q test code only ************ */
  2165. /* If we are going to use the ALT reference for the next group of
  2166. * frames set a flag to say so.
  2167. */
  2168. if (cpi->oxcf.fixed_q >= 0 && cpi->oxcf.play_alternate &&
  2169. !cpi->common.refresh_alt_ref_frame) {
  2170. cpi->source_alt_ref_pending = 1;
  2171. cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
  2172. }
  2173. if (!cpi->source_alt_ref_pending) cpi->source_alt_ref_active = 0;
  2174. /* Decrement count down till next gf */
  2175. if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
  2176. } else if (!cpi->common.refresh_alt_ref_frame) {
  2177. /* Decrement count down till next gf */
  2178. if (cpi->frames_till_gf_update_due > 0) cpi->frames_till_gf_update_due--;
  2179. if (cpi->frames_till_alt_ref_frame) cpi->frames_till_alt_ref_frame--;
  2180. cpi->frames_since_golden++;
  2181. if (cpi->frames_since_golden > 1) {
  2182. cpi->recent_ref_frame_usage[INTRA_FRAME] +=
  2183. cpi->mb.count_mb_ref_frame_usage[INTRA_FRAME];
  2184. cpi->recent_ref_frame_usage[LAST_FRAME] +=
  2185. cpi->mb.count_mb_ref_frame_usage[LAST_FRAME];
  2186. cpi->recent_ref_frame_usage[GOLDEN_FRAME] +=
  2187. cpi->mb.count_mb_ref_frame_usage[GOLDEN_FRAME];
  2188. cpi->recent_ref_frame_usage[ALTREF_FRAME] +=
  2189. cpi->mb.count_mb_ref_frame_usage[ALTREF_FRAME];
  2190. }
  2191. }
  2192. }
  2193. /* This function updates the reference frame probability estimates that
  2194. * will be used during mode selection
  2195. */
  2196. static void update_rd_ref_frame_probs(VP8_COMP *cpi) {
  2197. VP8_COMMON *cm = &cpi->common;
  2198. const int *const rfct = cpi->mb.count_mb_ref_frame_usage;
  2199. const int rf_intra = rfct[INTRA_FRAME];
  2200. const int rf_inter =
  2201. rfct[LAST_FRAME] + rfct[GOLDEN_FRAME] + rfct[ALTREF_FRAME];
  2202. if (cm->frame_type == KEY_FRAME) {
  2203. cpi->prob_intra_coded = 255;
  2204. cpi->prob_last_coded = 128;
  2205. cpi->prob_gf_coded = 128;
  2206. } else if (!(rf_intra + rf_inter)) {
  2207. cpi->prob_intra_coded = 63;
  2208. cpi->prob_last_coded = 128;
  2209. cpi->prob_gf_coded = 128;
  2210. }
  2211. /* update reference frame costs since we can do better than what we got
  2212. * last frame.
  2213. */
  2214. if (cpi->oxcf.number_of_layers == 1) {
  2215. if (cpi->common.refresh_alt_ref_frame) {
  2216. cpi->prob_intra_coded += 40;
  2217. if (cpi->prob_intra_coded > 255) cpi->prob_intra_coded = 255;
  2218. cpi->prob_last_coded = 200;
  2219. cpi->prob_gf_coded = 1;
  2220. } else if (cpi->frames_since_golden == 0) {
  2221. cpi->prob_last_coded = 214;
  2222. } else if (cpi->frames_since_golden == 1) {
  2223. cpi->prob_last_coded = 192;
  2224. cpi->prob_gf_coded = 220;
  2225. } else if (cpi->source_alt_ref_active) {
  2226. cpi->prob_gf_coded -= 20;
  2227. if (cpi->prob_gf_coded < 10) cpi->prob_gf_coded = 10;
  2228. }
  2229. if (!cpi->source_alt_ref_active) cpi->prob_gf_coded = 255;
  2230. }
  2231. }
  2232. #if !CONFIG_REALTIME_ONLY
  2233. /* 1 = key, 0 = inter */
  2234. static int decide_key_frame(VP8_COMP *cpi) {
  2235. VP8_COMMON *cm = &cpi->common;
  2236. int code_key_frame = 0;
  2237. cpi->kf_boost = 0;
  2238. if (cpi->Speed > 11) return 0;
  2239. /* Clear down mmx registers */
  2240. vpx_clear_system_state();
  2241. if ((cpi->compressor_speed == 2) && (cpi->Speed >= 5) && (cpi->sf.RD == 0)) {
  2242. double change = 1.0 *
  2243. abs((int)(cpi->mb.intra_error - cpi->last_intra_error)) /
  2244. (1 + cpi->last_intra_error);
  2245. double change2 =
  2246. 1.0 *
  2247. abs((int)(cpi->mb.prediction_error - cpi->last_prediction_error)) /
  2248. (1 + cpi->last_prediction_error);
  2249. double minerror = cm->MBs * 256;
  2250. cpi->last_intra_error = cpi->mb.intra_error;
  2251. cpi->last_prediction_error = cpi->mb.prediction_error;
  2252. if (10 * cpi->mb.intra_error / (1 + cpi->mb.prediction_error) < 15 &&
  2253. cpi->mb.prediction_error > minerror &&
  2254. (change > .25 || change2 > .25)) {
  2255. /*(change > 1.4 || change < .75)&& cpi->this_frame_percent_intra >
  2256. * cpi->last_frame_percent_intra + 3*/
  2257. return 1;
  2258. }
  2259. return 0;
  2260. }
  2261. /* If the following are true we might as well code a key frame */
  2262. if (((cpi->this_frame_percent_intra == 100) &&
  2263. (cpi->this_frame_percent_intra > (cpi->last_frame_percent_intra + 2))) ||
  2264. ((cpi->this_frame_percent_intra > 95) &&
  2265. (cpi->this_frame_percent_intra >=
  2266. (cpi->last_frame_percent_intra + 5)))) {
  2267. code_key_frame = 1;
  2268. }
  2269. /* in addition if the following are true and this is not a golden frame
  2270. * then code a key frame Note that on golden frames there often seems
  2271. * to be a pop in intra useage anyway hence this restriction is
  2272. * designed to prevent spurious key frames. The Intra pop needs to be
  2273. * investigated.
  2274. */
  2275. else if (((cpi->this_frame_percent_intra > 60) &&
  2276. (cpi->this_frame_percent_intra >
  2277. (cpi->last_frame_percent_intra * 2))) ||
  2278. ((cpi->this_frame_percent_intra > 75) &&
  2279. (cpi->this_frame_percent_intra >
  2280. (cpi->last_frame_percent_intra * 3 / 2))) ||
  2281. ((cpi->this_frame_percent_intra > 90) &&
  2282. (cpi->this_frame_percent_intra >
  2283. (cpi->last_frame_percent_intra + 10)))) {
  2284. if (!cm->refresh_golden_frame) code_key_frame = 1;
  2285. }
  2286. return code_key_frame;
  2287. }
  2288. static void Pass1Encode(VP8_COMP *cpi, size_t *size, unsigned char *dest,
  2289. unsigned int *frame_flags) {
  2290. (void)size;
  2291. (void)dest;
  2292. (void)frame_flags;
  2293. vp8_set_quantizer(cpi, 26);
  2294. vp8_first_pass(cpi);
  2295. }
  2296. #endif
  2297. #if 0
  2298. void write_cx_frame_to_file(YV12_BUFFER_CONFIG *frame, int this_frame)
  2299. {
  2300. /* write the frame */
  2301. FILE *yframe;
  2302. int i;
  2303. char filename[255];
  2304. sprintf(filename, "cx\\y%04d.raw", this_frame);
  2305. yframe = fopen(filename, "wb");
  2306. for (i = 0; i < frame->y_height; ++i)
  2307. fwrite(frame->y_buffer + i * frame->y_stride, frame->y_width, 1, yframe);
  2308. fclose(yframe);
  2309. sprintf(filename, "cx\\u%04d.raw", this_frame);
  2310. yframe = fopen(filename, "wb");
  2311. for (i = 0; i < frame->uv_height; ++i)
  2312. fwrite(frame->u_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
  2313. fclose(yframe);
  2314. sprintf(filename, "cx\\v%04d.raw", this_frame);
  2315. yframe = fopen(filename, "wb");
  2316. for (i = 0; i < frame->uv_height; ++i)
  2317. fwrite(frame->v_buffer + i * frame->uv_stride, frame->uv_width, 1, yframe);
  2318. fclose(yframe);
  2319. }
  2320. #endif
  2321. #if !CONFIG_REALTIME_ONLY
  2322. /* Function to test for conditions that indeicate we should loop
  2323. * back and recode a frame.
  2324. */
  2325. static int recode_loop_test(VP8_COMP *cpi, int high_limit, int low_limit, int q,
  2326. int maxq, int minq) {
  2327. int force_recode = 0;
  2328. VP8_COMMON *cm = &cpi->common;
  2329. /* Is frame recode allowed at all
  2330. * Yes if either recode mode 1 is selected or mode two is selcted
  2331. * and the frame is a key frame. golden frame or alt_ref_frame
  2332. */
  2333. if ((cpi->sf.recode_loop == 1) ||
  2334. ((cpi->sf.recode_loop == 2) &&
  2335. ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
  2336. cm->refresh_alt_ref_frame))) {
  2337. /* General over and under shoot tests */
  2338. if (((cpi->projected_frame_size > high_limit) && (q < maxq)) ||
  2339. ((cpi->projected_frame_size < low_limit) && (q > minq))) {
  2340. force_recode = 1;
  2341. }
  2342. /* Special Constrained quality tests */
  2343. else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
  2344. /* Undershoot and below auto cq level */
  2345. if ((q > cpi->cq_target_quality) &&
  2346. (cpi->projected_frame_size < ((cpi->this_frame_target * 7) >> 3))) {
  2347. force_recode = 1;
  2348. }
  2349. /* Severe undershoot and between auto and user cq level */
  2350. else if ((q > cpi->oxcf.cq_level) &&
  2351. (cpi->projected_frame_size < cpi->min_frame_bandwidth) &&
  2352. (cpi->active_best_quality > cpi->oxcf.cq_level)) {
  2353. force_recode = 1;
  2354. cpi->active_best_quality = cpi->oxcf.cq_level;
  2355. }
  2356. }
  2357. }
  2358. return force_recode;
  2359. }
  2360. #endif // !CONFIG_REALTIME_ONLY
  2361. static void update_reference_frames(VP8_COMP *cpi) {
  2362. VP8_COMMON *cm = &cpi->common;
  2363. YV12_BUFFER_CONFIG *yv12_fb = cm->yv12_fb;
  2364. /* At this point the new frame has been encoded.
  2365. * If any buffer copy / swapping is signaled it should be done here.
  2366. */
  2367. if (cm->frame_type == KEY_FRAME) {
  2368. yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME | VP8_ALTR_FRAME;
  2369. yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
  2370. yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
  2371. cm->alt_fb_idx = cm->gld_fb_idx = cm->new_fb_idx;
  2372. cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
  2373. cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
  2374. } else {
  2375. if (cm->refresh_alt_ref_frame) {
  2376. assert(!cm->copy_buffer_to_arf);
  2377. cm->yv12_fb[cm->new_fb_idx].flags |= VP8_ALTR_FRAME;
  2378. cm->yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
  2379. cm->alt_fb_idx = cm->new_fb_idx;
  2380. cpi->current_ref_frames[ALTREF_FRAME] = cm->current_video_frame;
  2381. } else if (cm->copy_buffer_to_arf) {
  2382. assert(!(cm->copy_buffer_to_arf & ~0x3));
  2383. if (cm->copy_buffer_to_arf == 1) {
  2384. if (cm->alt_fb_idx != cm->lst_fb_idx) {
  2385. yv12_fb[cm->lst_fb_idx].flags |= VP8_ALTR_FRAME;
  2386. yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
  2387. cm->alt_fb_idx = cm->lst_fb_idx;
  2388. cpi->current_ref_frames[ALTREF_FRAME] =
  2389. cpi->current_ref_frames[LAST_FRAME];
  2390. }
  2391. } else {
  2392. if (cm->alt_fb_idx != cm->gld_fb_idx) {
  2393. yv12_fb[cm->gld_fb_idx].flags |= VP8_ALTR_FRAME;
  2394. yv12_fb[cm->alt_fb_idx].flags &= ~VP8_ALTR_FRAME;
  2395. cm->alt_fb_idx = cm->gld_fb_idx;
  2396. cpi->current_ref_frames[ALTREF_FRAME] =
  2397. cpi->current_ref_frames[GOLDEN_FRAME];
  2398. }
  2399. }
  2400. }
  2401. if (cm->refresh_golden_frame) {
  2402. assert(!cm->copy_buffer_to_gf);
  2403. cm->yv12_fb[cm->new_fb_idx].flags |= VP8_GOLD_FRAME;
  2404. cm->yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
  2405. cm->gld_fb_idx = cm->new_fb_idx;
  2406. cpi->current_ref_frames[GOLDEN_FRAME] = cm->current_video_frame;
  2407. } else if (cm->copy_buffer_to_gf) {
  2408. assert(!(cm->copy_buffer_to_arf & ~0x3));
  2409. if (cm->copy_buffer_to_gf == 1) {
  2410. if (cm->gld_fb_idx != cm->lst_fb_idx) {
  2411. yv12_fb[cm->lst_fb_idx].flags |= VP8_GOLD_FRAME;
  2412. yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
  2413. cm->gld_fb_idx = cm->lst_fb_idx;
  2414. cpi->current_ref_frames[GOLDEN_FRAME] =
  2415. cpi->current_ref_frames[LAST_FRAME];
  2416. }
  2417. } else {
  2418. if (cm->alt_fb_idx != cm->gld_fb_idx) {
  2419. yv12_fb[cm->alt_fb_idx].flags |= VP8_GOLD_FRAME;
  2420. yv12_fb[cm->gld_fb_idx].flags &= ~VP8_GOLD_FRAME;
  2421. cm->gld_fb_idx = cm->alt_fb_idx;
  2422. cpi->current_ref_frames[GOLDEN_FRAME] =
  2423. cpi->current_ref_frames[ALTREF_FRAME];
  2424. }
  2425. }
  2426. }
  2427. }
  2428. if (cm->refresh_last_frame) {
  2429. cm->yv12_fb[cm->new_fb_idx].flags |= VP8_LAST_FRAME;
  2430. cm->yv12_fb[cm->lst_fb_idx].flags &= ~VP8_LAST_FRAME;
  2431. cm->lst_fb_idx = cm->new_fb_idx;
  2432. cpi->current_ref_frames[LAST_FRAME] = cm->current_video_frame;
  2433. }
  2434. #if CONFIG_TEMPORAL_DENOISING
  2435. if (cpi->oxcf.noise_sensitivity) {
  2436. /* we shouldn't have to keep multiple copies as we know in advance which
  2437. * buffer we should start - for now to get something up and running
  2438. * I've chosen to copy the buffers
  2439. */
  2440. if (cm->frame_type == KEY_FRAME) {
  2441. int i;
  2442. for (i = LAST_FRAME; i < MAX_REF_FRAMES; ++i)
  2443. vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_running_avg[i]);
  2444. } else {
  2445. vp8_yv12_extend_frame_borders(
  2446. &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
  2447. if (cm->refresh_alt_ref_frame || cm->copy_buffer_to_arf) {
  2448. vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
  2449. &cpi->denoiser.yv12_running_avg[ALTREF_FRAME]);
  2450. }
  2451. if (cm->refresh_golden_frame || cm->copy_buffer_to_gf) {
  2452. vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
  2453. &cpi->denoiser.yv12_running_avg[GOLDEN_FRAME]);
  2454. }
  2455. if (cm->refresh_last_frame) {
  2456. vp8_yv12_copy_frame(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
  2457. &cpi->denoiser.yv12_running_avg[LAST_FRAME]);
  2458. }
  2459. }
  2460. if (cpi->oxcf.noise_sensitivity == 4)
  2461. vp8_yv12_copy_frame(cpi->Source, &cpi->denoiser.yv12_last_source);
  2462. }
  2463. #endif
  2464. }
  2465. static int measure_square_diff_partial(YV12_BUFFER_CONFIG *source,
  2466. YV12_BUFFER_CONFIG *dest,
  2467. VP8_COMP *cpi) {
  2468. int i, j;
  2469. int Total = 0;
  2470. int num_blocks = 0;
  2471. int skip = 2;
  2472. int min_consec_zero_last = 10;
  2473. int tot_num_blocks = (source->y_height * source->y_width) >> 8;
  2474. unsigned char *src = source->y_buffer;
  2475. unsigned char *dst = dest->y_buffer;
  2476. /* Loop through the Y plane, every |skip| blocks along rows and colmumns,
  2477. * summing the square differences, and only for blocks that have been
  2478. * zero_last mode at least |x| frames in a row.
  2479. */
  2480. for (i = 0; i < source->y_height; i += 16 * skip) {
  2481. int block_index_row = (i >> 4) * cpi->common.mb_cols;
  2482. for (j = 0; j < source->y_width; j += 16 * skip) {
  2483. int index = block_index_row + (j >> 4);
  2484. if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
  2485. unsigned int sse;
  2486. Total += vpx_mse16x16(src + j, source->y_stride, dst + j,
  2487. dest->y_stride, &sse);
  2488. num_blocks++;
  2489. }
  2490. }
  2491. src += 16 * skip * source->y_stride;
  2492. dst += 16 * skip * dest->y_stride;
  2493. }
  2494. // Only return non-zero if we have at least ~1/16 samples for estimate.
  2495. if (num_blocks > (tot_num_blocks >> 4)) {
  2496. assert(num_blocks != 0);
  2497. return num_blocks ? (Total / num_blocks) : 0;
  2498. } else {
  2499. return 0;
  2500. }
  2501. }
  2502. #if CONFIG_TEMPORAL_DENOISING
  2503. static void process_denoiser_mode_change(VP8_COMP *cpi) {
  2504. const VP8_COMMON *const cm = &cpi->common;
  2505. int i, j;
  2506. int total = 0;
  2507. int num_blocks = 0;
  2508. // Number of blocks skipped along row/column in computing the
  2509. // nmse (normalized mean square error) of source.
  2510. int skip = 2;
  2511. // Only select blocks for computing nmse that have been encoded
  2512. // as ZERO LAST min_consec_zero_last frames in a row.
  2513. // Scale with number of temporal layers.
  2514. int min_consec_zero_last = 12 / cpi->oxcf.number_of_layers;
  2515. // Decision is tested for changing the denoising mode every
  2516. // num_mode_change times this function is called. Note that this
  2517. // function called every 8 frames, so (8 * num_mode_change) is number
  2518. // of frames where denoising mode change is tested for switch.
  2519. int num_mode_change = 20;
  2520. // Framerate factor, to compensate for larger mse at lower framerates.
  2521. // Use ref_framerate, which is full source framerate for temporal layers.
  2522. // TODO(marpan): Adjust this factor.
  2523. int fac_framerate = cpi->ref_framerate < 25.0f ? 80 : 100;
  2524. int tot_num_blocks = cm->mb_rows * cm->mb_cols;
  2525. int ystride = cpi->Source->y_stride;
  2526. unsigned char *src = cpi->Source->y_buffer;
  2527. unsigned char *dst = cpi->denoiser.yv12_last_source.y_buffer;
  2528. static const unsigned char const_source[16] = { 128, 128, 128, 128, 128, 128,
  2529. 128, 128, 128, 128, 128, 128,
  2530. 128, 128, 128, 128 };
  2531. int bandwidth = (int)(cpi->target_bandwidth);
  2532. // For temporal layers, use full bandwidth (top layer).
  2533. if (cpi->oxcf.number_of_layers > 1) {
  2534. LAYER_CONTEXT *lc = &cpi->layer_context[cpi->oxcf.number_of_layers - 1];
  2535. bandwidth = (int)(lc->target_bandwidth);
  2536. }
  2537. // Loop through the Y plane, every skip blocks along rows and columns,
  2538. // summing the normalized mean square error, only for blocks that have
  2539. // been encoded as ZEROMV LAST at least min_consec_zero_last least frames in
  2540. // a row and have small sum difference between current and previous frame.
  2541. // Normalization here is by the contrast of the current frame block.
  2542. for (i = 0; i < cm->Height; i += 16 * skip) {
  2543. int block_index_row = (i >> 4) * cm->mb_cols;
  2544. for (j = 0; j < cm->Width; j += 16 * skip) {
  2545. int index = block_index_row + (j >> 4);
  2546. if (cpi->consec_zero_last[index] >= min_consec_zero_last) {
  2547. unsigned int sse;
  2548. const unsigned int var =
  2549. vpx_variance16x16(src + j, ystride, dst + j, ystride, &sse);
  2550. // Only consider this block as valid for noise measurement
  2551. // if the sum_diff average of the current and previous frame
  2552. // is small (to avoid effects from lighting change).
  2553. if ((sse - var) < 128) {
  2554. unsigned int sse2;
  2555. const unsigned int act =
  2556. vpx_variance16x16(src + j, ystride, const_source, 0, &sse2);
  2557. if (act > 0) total += sse / act;
  2558. num_blocks++;
  2559. }
  2560. }
  2561. }
  2562. src += 16 * skip * ystride;
  2563. dst += 16 * skip * ystride;
  2564. }
  2565. total = total * fac_framerate / 100;
  2566. // Only consider this frame as valid sample if we have computed nmse over
  2567. // at least ~1/16 blocks, and Total > 0 (Total == 0 can happen if the
  2568. // application inputs duplicate frames, or contrast is all zero).
  2569. if (total > 0 && (num_blocks > (tot_num_blocks >> 4))) {
  2570. // Update the recursive mean square source_diff.
  2571. total = (total << 8) / num_blocks;
  2572. if (cpi->denoiser.nmse_source_diff_count == 0) {
  2573. // First sample in new interval.
  2574. cpi->denoiser.nmse_source_diff = total;
  2575. cpi->denoiser.qp_avg = cm->base_qindex;
  2576. } else {
  2577. // For subsequent samples, use average with weight ~1/4 for new sample.
  2578. cpi->denoiser.nmse_source_diff =
  2579. (int)((total + 3 * cpi->denoiser.nmse_source_diff) >> 2);
  2580. cpi->denoiser.qp_avg =
  2581. (int)((cm->base_qindex + 3 * cpi->denoiser.qp_avg) >> 2);
  2582. }
  2583. cpi->denoiser.nmse_source_diff_count++;
  2584. }
  2585. // Check for changing the denoiser mode, when we have obtained #samples =
  2586. // num_mode_change. Condition the change also on the bitrate and QP.
  2587. if (cpi->denoiser.nmse_source_diff_count == num_mode_change) {
  2588. // Check for going up: from normal to aggressive mode.
  2589. if ((cpi->denoiser.denoiser_mode == kDenoiserOnYUV) &&
  2590. (cpi->denoiser.nmse_source_diff >
  2591. cpi->denoiser.threshold_aggressive_mode) &&
  2592. (cpi->denoiser.qp_avg < cpi->denoiser.qp_threshold_up &&
  2593. bandwidth > cpi->denoiser.bitrate_threshold)) {
  2594. vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUVAggressive);
  2595. } else {
  2596. // Check for going down: from aggressive to normal mode.
  2597. if (((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
  2598. (cpi->denoiser.nmse_source_diff <
  2599. cpi->denoiser.threshold_aggressive_mode)) ||
  2600. ((cpi->denoiser.denoiser_mode == kDenoiserOnYUVAggressive) &&
  2601. (cpi->denoiser.qp_avg > cpi->denoiser.qp_threshold_down ||
  2602. bandwidth < cpi->denoiser.bitrate_threshold))) {
  2603. vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
  2604. }
  2605. }
  2606. // Reset metric and counter for next interval.
  2607. cpi->denoiser.nmse_source_diff = 0;
  2608. cpi->denoiser.qp_avg = 0;
  2609. cpi->denoiser.nmse_source_diff_count = 0;
  2610. }
  2611. }
  2612. #endif
  2613. void vp8_loopfilter_frame(VP8_COMP *cpi, VP8_COMMON *cm) {
  2614. const FRAME_TYPE frame_type = cm->frame_type;
  2615. int update_any_ref_buffers = 1;
  2616. if (cpi->common.refresh_last_frame == 0 &&
  2617. cpi->common.refresh_golden_frame == 0 &&
  2618. cpi->common.refresh_alt_ref_frame == 0) {
  2619. update_any_ref_buffers = 0;
  2620. }
  2621. if (cm->no_lpf) {
  2622. cm->filter_level = 0;
  2623. } else {
  2624. struct vpx_usec_timer timer;
  2625. vpx_clear_system_state();
  2626. vpx_usec_timer_start(&timer);
  2627. if (cpi->sf.auto_filter == 0) {
  2628. #if CONFIG_TEMPORAL_DENOISING
  2629. if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
  2630. // Use the denoised buffer for selecting base loop filter level.
  2631. // Denoised signal for current frame is stored in INTRA_FRAME.
  2632. // No denoising on key frames.
  2633. vp8cx_pick_filter_level_fast(
  2634. &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi);
  2635. } else {
  2636. vp8cx_pick_filter_level_fast(cpi->Source, cpi);
  2637. }
  2638. #else
  2639. vp8cx_pick_filter_level_fast(cpi->Source, cpi);
  2640. #endif
  2641. } else {
  2642. #if CONFIG_TEMPORAL_DENOISING
  2643. if (cpi->oxcf.noise_sensitivity && cm->frame_type != KEY_FRAME) {
  2644. // Use the denoised buffer for selecting base loop filter level.
  2645. // Denoised signal for current frame is stored in INTRA_FRAME.
  2646. // No denoising on key frames.
  2647. vp8cx_pick_filter_level(&cpi->denoiser.yv12_running_avg[INTRA_FRAME],
  2648. cpi);
  2649. } else {
  2650. vp8cx_pick_filter_level(cpi->Source, cpi);
  2651. }
  2652. #else
  2653. vp8cx_pick_filter_level(cpi->Source, cpi);
  2654. #endif
  2655. }
  2656. if (cm->filter_level > 0) {
  2657. vp8cx_set_alt_lf_level(cpi, cm->filter_level);
  2658. }
  2659. vpx_usec_timer_mark(&timer);
  2660. cpi->time_pick_lpf += vpx_usec_timer_elapsed(&timer);
  2661. }
  2662. #if CONFIG_MULTITHREAD
  2663. if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
  2664. sem_post(&cpi->h_event_end_lpf); /* signal that we have set filter_level */
  2665. }
  2666. #endif
  2667. // No need to apply loop-filter if the encoded frame does not update
  2668. // any reference buffers.
  2669. if (cm->filter_level > 0 && update_any_ref_buffers) {
  2670. vp8_loop_filter_frame(cm, &cpi->mb.e_mbd, frame_type);
  2671. }
  2672. vp8_yv12_extend_frame_borders(cm->frame_to_show);
  2673. }
  2674. static void encode_frame_to_data_rate(VP8_COMP *cpi, size_t *size,
  2675. unsigned char *dest,
  2676. unsigned char *dest_end,
  2677. unsigned int *frame_flags) {
  2678. int Q;
  2679. int frame_over_shoot_limit;
  2680. int frame_under_shoot_limit;
  2681. int Loop = 0;
  2682. int loop_count;
  2683. VP8_COMMON *cm = &cpi->common;
  2684. int active_worst_qchanged = 0;
  2685. #if !CONFIG_REALTIME_ONLY
  2686. int q_low;
  2687. int q_high;
  2688. int zbin_oq_high;
  2689. int zbin_oq_low = 0;
  2690. int top_index;
  2691. int bottom_index;
  2692. int overshoot_seen = 0;
  2693. int undershoot_seen = 0;
  2694. #endif
  2695. int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
  2696. cpi->oxcf.optimal_buffer_level / 100);
  2697. int drop_mark75 = drop_mark * 2 / 3;
  2698. int drop_mark50 = drop_mark / 4;
  2699. int drop_mark25 = drop_mark / 8;
  2700. /* Clear down mmx registers to allow floating point in what follows */
  2701. vpx_clear_system_state();
  2702. if (cpi->force_next_frame_intra) {
  2703. cm->frame_type = KEY_FRAME; /* delayed intra frame */
  2704. cpi->force_next_frame_intra = 0;
  2705. }
  2706. /* For an alt ref frame in 2 pass we skip the call to the second pass
  2707. * function that sets the target bandwidth
  2708. */
  2709. switch (cpi->pass) {
  2710. #if !CONFIG_REALTIME_ONLY
  2711. case 2:
  2712. if (cpi->common.refresh_alt_ref_frame) {
  2713. /* Per frame bit target for the alt ref frame */
  2714. cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
  2715. /* per second target bitrate */
  2716. cpi->target_bandwidth =
  2717. (int)(cpi->twopass.gf_bits * cpi->output_framerate);
  2718. }
  2719. break;
  2720. #endif // !CONFIG_REALTIME_ONLY
  2721. default:
  2722. cpi->per_frame_bandwidth =
  2723. (int)(cpi->target_bandwidth / cpi->output_framerate);
  2724. break;
  2725. }
  2726. /* Default turn off buffer to buffer copying */
  2727. cm->copy_buffer_to_gf = 0;
  2728. cm->copy_buffer_to_arf = 0;
  2729. /* Clear zbin over-quant value and mode boost values. */
  2730. cpi->mb.zbin_over_quant = 0;
  2731. cpi->mb.zbin_mode_boost = 0;
  2732. /* Enable or disable mode based tweaking of the zbin
  2733. * For 2 Pass Only used where GF/ARF prediction quality
  2734. * is above a threshold
  2735. */
  2736. cpi->mb.zbin_mode_boost_enabled = 1;
  2737. if (cpi->pass == 2) {
  2738. if (cpi->gfu_boost <= 400) {
  2739. cpi->mb.zbin_mode_boost_enabled = 0;
  2740. }
  2741. }
  2742. /* Current default encoder behaviour for the altref sign bias */
  2743. if (cpi->source_alt_ref_active) {
  2744. cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 1;
  2745. } else {
  2746. cpi->common.ref_frame_sign_bias[ALTREF_FRAME] = 0;
  2747. }
  2748. /* Check to see if a key frame is signaled
  2749. * For two pass with auto key frame enabled cm->frame_type may already
  2750. * be set, but not for one pass.
  2751. */
  2752. if ((cm->current_video_frame == 0) || (cm->frame_flags & FRAMEFLAGS_KEY) ||
  2753. (cpi->oxcf.auto_key &&
  2754. (cpi->frames_since_key % cpi->key_frame_frequency == 0))) {
  2755. /* Key frame from VFW/auto-keyframe/first frame */
  2756. cm->frame_type = KEY_FRAME;
  2757. #if CONFIG_TEMPORAL_DENOISING
  2758. if (cpi->oxcf.noise_sensitivity == 4) {
  2759. // For adaptive mode, reset denoiser to normal mode on key frame.
  2760. vp8_denoiser_set_parameters(&cpi->denoiser, kDenoiserOnYUV);
  2761. }
  2762. #endif
  2763. }
  2764. #if CONFIG_MULTI_RES_ENCODING
  2765. if (cpi->oxcf.mr_total_resolutions > 1) {
  2766. LOWER_RES_FRAME_INFO *low_res_frame_info =
  2767. (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
  2768. if (cpi->oxcf.mr_encoder_id) {
  2769. // Check if lower resolution is available for motion vector reuse.
  2770. if (cm->frame_type != KEY_FRAME) {
  2771. cpi->mr_low_res_mv_avail = 1;
  2772. cpi->mr_low_res_mv_avail &= !(low_res_frame_info->is_frame_dropped);
  2773. if (cpi->ref_frame_flags & VP8_LAST_FRAME)
  2774. cpi->mr_low_res_mv_avail &=
  2775. (cpi->current_ref_frames[LAST_FRAME] ==
  2776. low_res_frame_info->low_res_ref_frames[LAST_FRAME]);
  2777. if (cpi->ref_frame_flags & VP8_GOLD_FRAME)
  2778. cpi->mr_low_res_mv_avail &=
  2779. (cpi->current_ref_frames[GOLDEN_FRAME] ==
  2780. low_res_frame_info->low_res_ref_frames[GOLDEN_FRAME]);
  2781. // Don't use altref to determine whether low res is available.
  2782. // TODO (marpan): Should we make this type of condition on a
  2783. // per-reference frame basis?
  2784. /*
  2785. if (cpi->ref_frame_flags & VP8_ALTR_FRAME)
  2786. cpi->mr_low_res_mv_avail &= (cpi->current_ref_frames[ALTREF_FRAME]
  2787. == low_res_frame_info->low_res_ref_frames[ALTREF_FRAME]);
  2788. */
  2789. }
  2790. // Disable motion vector reuse (i.e., disable any usage of the low_res)
  2791. // if the previous lower stream is skipped/disabled.
  2792. if (low_res_frame_info->skip_encoding_prev_stream) {
  2793. cpi->mr_low_res_mv_avail = 0;
  2794. }
  2795. }
  2796. // This stream is not skipped (i.e., it's being encoded), so set this skip
  2797. // flag to 0. This is needed for the next stream (i.e., which is the next
  2798. // frame to be encoded).
  2799. low_res_frame_info->skip_encoding_prev_stream = 0;
  2800. // On a key frame: For the lowest resolution, keep track of the key frame
  2801. // counter value. For the higher resolutions, reset the current video
  2802. // frame counter to that of the lowest resolution.
  2803. // This is done to the handle the case where we may stop/start encoding
  2804. // higher layer(s). The restart-encoding of higher layer is only signaled
  2805. // by a key frame for now.
  2806. // TODO (marpan): Add flag to indicate restart-encoding of higher layer.
  2807. if (cm->frame_type == KEY_FRAME) {
  2808. if (cpi->oxcf.mr_encoder_id) {
  2809. // If the initial starting value of the buffer level is zero (this can
  2810. // happen because we may have not started encoding this higher stream),
  2811. // then reset it to non-zero value based on |starting_buffer_level|.
  2812. if (cpi->common.current_video_frame == 0 && cpi->buffer_level == 0) {
  2813. unsigned int i;
  2814. cpi->bits_off_target = cpi->oxcf.starting_buffer_level;
  2815. cpi->buffer_level = cpi->oxcf.starting_buffer_level;
  2816. for (i = 0; i < cpi->oxcf.number_of_layers; ++i) {
  2817. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  2818. lc->bits_off_target = lc->starting_buffer_level;
  2819. lc->buffer_level = lc->starting_buffer_level;
  2820. }
  2821. }
  2822. cpi->common.current_video_frame =
  2823. low_res_frame_info->key_frame_counter_value;
  2824. } else {
  2825. low_res_frame_info->key_frame_counter_value =
  2826. cpi->common.current_video_frame;
  2827. }
  2828. }
  2829. }
  2830. #endif
  2831. // Find the reference frame closest to the current frame.
  2832. cpi->closest_reference_frame = LAST_FRAME;
  2833. if (cm->frame_type != KEY_FRAME) {
  2834. int i;
  2835. MV_REFERENCE_FRAME closest_ref = INTRA_FRAME;
  2836. if (cpi->ref_frame_flags & VP8_LAST_FRAME) {
  2837. closest_ref = LAST_FRAME;
  2838. } else if (cpi->ref_frame_flags & VP8_GOLD_FRAME) {
  2839. closest_ref = GOLDEN_FRAME;
  2840. } else if (cpi->ref_frame_flags & VP8_ALTR_FRAME) {
  2841. closest_ref = ALTREF_FRAME;
  2842. }
  2843. for (i = 1; i <= 3; ++i) {
  2844. vpx_ref_frame_type_t ref_frame_type =
  2845. (vpx_ref_frame_type_t)((i == 3) ? 4 : i);
  2846. if (cpi->ref_frame_flags & ref_frame_type) {
  2847. if ((cm->current_video_frame - cpi->current_ref_frames[i]) <
  2848. (cm->current_video_frame - cpi->current_ref_frames[closest_ref])) {
  2849. closest_ref = i;
  2850. }
  2851. }
  2852. }
  2853. cpi->closest_reference_frame = closest_ref;
  2854. }
  2855. /* Set various flags etc to special state if it is a key frame */
  2856. if (cm->frame_type == KEY_FRAME) {
  2857. int i;
  2858. // Set the loop filter deltas and segmentation map update
  2859. setup_features(cpi);
  2860. /* The alternate reference frame cannot be active for a key frame */
  2861. cpi->source_alt_ref_active = 0;
  2862. /* Reset the RD threshold multipliers to default of * 1 (128) */
  2863. for (i = 0; i < MAX_MODES; ++i) {
  2864. cpi->mb.rd_thresh_mult[i] = 128;
  2865. }
  2866. // Reset the zero_last counter to 0 on key frame.
  2867. memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
  2868. memset(cpi->consec_zero_last_mvbias, 0,
  2869. (cpi->common.mb_rows * cpi->common.mb_cols));
  2870. }
  2871. #if 0
  2872. /* Experimental code for lagged compress and one pass
  2873. * Initialise one_pass GF frames stats
  2874. * Update stats used for GF selection
  2875. */
  2876. {
  2877. cpi->one_pass_frame_index = cm->current_video_frame % MAX_LAG_BUFFERS;
  2878. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frames_so_far = 0;
  2879. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_intra_error = 0.0;
  2880. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_coded_error = 0.0;
  2881. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_inter = 0.0;
  2882. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_pcnt_motion = 0.0;
  2883. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr = 0.0;
  2884. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvr_abs = 0.0;
  2885. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc = 0.0;
  2886. cpi->one_pass_frame_stats[cpi->one_pass_frame_index ].frame_mvc_abs = 0.0;
  2887. }
  2888. #endif
  2889. update_rd_ref_frame_probs(cpi);
  2890. if (cpi->drop_frames_allowed) {
  2891. /* The reset to decimation 0 is only done here for one pass.
  2892. * Once it is set two pass leaves decimation on till the next kf.
  2893. */
  2894. if ((cpi->buffer_level > drop_mark) && (cpi->decimation_factor > 0)) {
  2895. cpi->decimation_factor--;
  2896. }
  2897. if (cpi->buffer_level > drop_mark75 && cpi->decimation_factor > 0) {
  2898. cpi->decimation_factor = 1;
  2899. } else if (cpi->buffer_level < drop_mark25 &&
  2900. (cpi->decimation_factor == 2 || cpi->decimation_factor == 3)) {
  2901. cpi->decimation_factor = 3;
  2902. } else if (cpi->buffer_level < drop_mark50 &&
  2903. (cpi->decimation_factor == 1 || cpi->decimation_factor == 2)) {
  2904. cpi->decimation_factor = 2;
  2905. } else if (cpi->buffer_level < drop_mark75 &&
  2906. (cpi->decimation_factor == 0 || cpi->decimation_factor == 1)) {
  2907. cpi->decimation_factor = 1;
  2908. }
  2909. }
  2910. /* The following decimates the frame rate according to a regular
  2911. * pattern (i.e. to 1/2 or 2/3 frame rate) This can be used to help
  2912. * prevent buffer under-run in CBR mode. Alternatively it might be
  2913. * desirable in some situations to drop frame rate but throw more bits
  2914. * at each frame.
  2915. *
  2916. * Note that dropping a key frame can be problematic if spatial
  2917. * resampling is also active
  2918. */
  2919. if (cpi->decimation_factor > 0) {
  2920. switch (cpi->decimation_factor) {
  2921. case 1:
  2922. cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 3 / 2;
  2923. break;
  2924. case 2:
  2925. cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
  2926. break;
  2927. case 3:
  2928. cpi->per_frame_bandwidth = cpi->per_frame_bandwidth * 5 / 4;
  2929. break;
  2930. }
  2931. /* Note that we should not throw out a key frame (especially when
  2932. * spatial resampling is enabled).
  2933. */
  2934. if (cm->frame_type == KEY_FRAME) {
  2935. cpi->decimation_count = cpi->decimation_factor;
  2936. } else if (cpi->decimation_count > 0) {
  2937. cpi->decimation_count--;
  2938. cpi->bits_off_target += cpi->av_per_frame_bandwidth;
  2939. if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
  2940. cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
  2941. }
  2942. #if CONFIG_MULTI_RES_ENCODING
  2943. vp8_store_drop_frame_info(cpi);
  2944. #endif
  2945. cm->current_video_frame++;
  2946. cpi->frames_since_key++;
  2947. cpi->ext_refresh_frame_flags_pending = 0;
  2948. // We advance the temporal pattern for dropped frames.
  2949. cpi->temporal_pattern_counter++;
  2950. #if CONFIG_INTERNAL_STATS
  2951. cpi->count++;
  2952. #endif
  2953. cpi->buffer_level = cpi->bits_off_target;
  2954. if (cpi->oxcf.number_of_layers > 1) {
  2955. unsigned int i;
  2956. /* Propagate bits saved by dropping the frame to higher
  2957. * layers
  2958. */
  2959. for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
  2960. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  2961. lc->bits_off_target += (int)(lc->target_bandwidth / lc->framerate);
  2962. if (lc->bits_off_target > lc->maximum_buffer_size) {
  2963. lc->bits_off_target = lc->maximum_buffer_size;
  2964. }
  2965. lc->buffer_level = lc->bits_off_target;
  2966. }
  2967. }
  2968. return;
  2969. } else {
  2970. cpi->decimation_count = cpi->decimation_factor;
  2971. }
  2972. } else {
  2973. cpi->decimation_count = 0;
  2974. }
  2975. /* Decide how big to make the frame */
  2976. if (!vp8_pick_frame_size(cpi)) {
  2977. /*TODO: 2 drop_frame and return code could be put together. */
  2978. #if CONFIG_MULTI_RES_ENCODING
  2979. vp8_store_drop_frame_info(cpi);
  2980. #endif
  2981. cm->current_video_frame++;
  2982. cpi->frames_since_key++;
  2983. cpi->ext_refresh_frame_flags_pending = 0;
  2984. // We advance the temporal pattern for dropped frames.
  2985. cpi->temporal_pattern_counter++;
  2986. return;
  2987. }
  2988. /* Reduce active_worst_allowed_q for CBR if our buffer is getting too full.
  2989. * This has a knock on effect on active best quality as well.
  2990. * For CBR if the buffer reaches its maximum level then we can no longer
  2991. * save up bits for later frames so we might as well use them up
  2992. * on the current frame.
  2993. */
  2994. if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
  2995. (cpi->buffer_level >= cpi->oxcf.optimal_buffer_level) &&
  2996. cpi->buffered_mode) {
  2997. /* Max adjustment is 1/4 */
  2998. int Adjustment = cpi->active_worst_quality / 4;
  2999. if (Adjustment) {
  3000. int buff_lvl_step;
  3001. if (cpi->buffer_level < cpi->oxcf.maximum_buffer_size) {
  3002. buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
  3003. cpi->oxcf.optimal_buffer_level) /
  3004. Adjustment);
  3005. if (buff_lvl_step) {
  3006. Adjustment =
  3007. (int)((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) /
  3008. buff_lvl_step);
  3009. } else {
  3010. Adjustment = 0;
  3011. }
  3012. }
  3013. cpi->active_worst_quality -= Adjustment;
  3014. if (cpi->active_worst_quality < cpi->active_best_quality) {
  3015. cpi->active_worst_quality = cpi->active_best_quality;
  3016. }
  3017. }
  3018. }
  3019. /* Set an active best quality and if necessary active worst quality
  3020. * There is some odd behavior for one pass here that needs attention.
  3021. */
  3022. if ((cpi->pass == 2) || (cpi->ni_frames > 150)) {
  3023. vpx_clear_system_state();
  3024. Q = cpi->active_worst_quality;
  3025. if (cm->frame_type == KEY_FRAME) {
  3026. if (cpi->pass == 2) {
  3027. if (cpi->gfu_boost > 600) {
  3028. cpi->active_best_quality = kf_low_motion_minq[Q];
  3029. } else {
  3030. cpi->active_best_quality = kf_high_motion_minq[Q];
  3031. }
  3032. /* Special case for key frames forced because we have reached
  3033. * the maximum key frame interval. Here force the Q to a range
  3034. * based on the ambient Q to reduce the risk of popping
  3035. */
  3036. if (cpi->this_key_frame_forced) {
  3037. if (cpi->active_best_quality > cpi->avg_frame_qindex * 7 / 8) {
  3038. cpi->active_best_quality = cpi->avg_frame_qindex * 7 / 8;
  3039. } else if (cpi->active_best_quality<cpi->avg_frame_qindex>> 2) {
  3040. cpi->active_best_quality = cpi->avg_frame_qindex >> 2;
  3041. }
  3042. }
  3043. }
  3044. /* One pass more conservative */
  3045. else {
  3046. cpi->active_best_quality = kf_high_motion_minq[Q];
  3047. }
  3048. }
  3049. else if (cpi->oxcf.number_of_layers == 1 &&
  3050. (cm->refresh_golden_frame || cpi->common.refresh_alt_ref_frame)) {
  3051. /* Use the lower of cpi->active_worst_quality and recent
  3052. * average Q as basis for GF/ARF Q limit unless last frame was
  3053. * a key frame.
  3054. */
  3055. if ((cpi->frames_since_key > 1) &&
  3056. (cpi->avg_frame_qindex < cpi->active_worst_quality)) {
  3057. Q = cpi->avg_frame_qindex;
  3058. }
  3059. /* For constrained quality dont allow Q less than the cq level */
  3060. if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
  3061. (Q < cpi->cq_target_quality)) {
  3062. Q = cpi->cq_target_quality;
  3063. }
  3064. if (cpi->pass == 2) {
  3065. if (cpi->gfu_boost > 1000) {
  3066. cpi->active_best_quality = gf_low_motion_minq[Q];
  3067. } else if (cpi->gfu_boost < 400) {
  3068. cpi->active_best_quality = gf_high_motion_minq[Q];
  3069. } else {
  3070. cpi->active_best_quality = gf_mid_motion_minq[Q];
  3071. }
  3072. /* Constrained quality use slightly lower active best. */
  3073. if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
  3074. cpi->active_best_quality = cpi->active_best_quality * 15 / 16;
  3075. }
  3076. }
  3077. /* One pass more conservative */
  3078. else {
  3079. cpi->active_best_quality = gf_high_motion_minq[Q];
  3080. }
  3081. } else {
  3082. cpi->active_best_quality = inter_minq[Q];
  3083. /* For the constant/constrained quality mode we dont want
  3084. * q to fall below the cq level.
  3085. */
  3086. if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
  3087. (cpi->active_best_quality < cpi->cq_target_quality)) {
  3088. /* If we are strongly undershooting the target rate in the last
  3089. * frames then use the user passed in cq value not the auto
  3090. * cq value.
  3091. */
  3092. if (cpi->rolling_actual_bits < cpi->min_frame_bandwidth) {
  3093. cpi->active_best_quality = cpi->oxcf.cq_level;
  3094. } else {
  3095. cpi->active_best_quality = cpi->cq_target_quality;
  3096. }
  3097. }
  3098. }
  3099. /* If CBR and the buffer is as full then it is reasonable to allow
  3100. * higher quality on the frames to prevent bits just going to waste.
  3101. */
  3102. if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  3103. /* Note that the use of >= here elliminates the risk of a devide
  3104. * by 0 error in the else if clause
  3105. */
  3106. if (cpi->buffer_level >= cpi->oxcf.maximum_buffer_size) {
  3107. cpi->active_best_quality = cpi->best_quality;
  3108. } else if (cpi->buffer_level > cpi->oxcf.optimal_buffer_level) {
  3109. int Fraction =
  3110. (int)(((cpi->buffer_level - cpi->oxcf.optimal_buffer_level) * 128) /
  3111. (cpi->oxcf.maximum_buffer_size -
  3112. cpi->oxcf.optimal_buffer_level));
  3113. int min_qadjustment =
  3114. ((cpi->active_best_quality - cpi->best_quality) * Fraction) / 128;
  3115. cpi->active_best_quality -= min_qadjustment;
  3116. }
  3117. }
  3118. }
  3119. /* Make sure constrained quality mode limits are adhered to for the first
  3120. * few frames of one pass encodes
  3121. */
  3122. else if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
  3123. if ((cm->frame_type == KEY_FRAME) || cm->refresh_golden_frame ||
  3124. cpi->common.refresh_alt_ref_frame) {
  3125. cpi->active_best_quality = cpi->best_quality;
  3126. } else if (cpi->active_best_quality < cpi->cq_target_quality) {
  3127. cpi->active_best_quality = cpi->cq_target_quality;
  3128. }
  3129. }
  3130. /* Clip the active best and worst quality values to limits */
  3131. if (cpi->active_worst_quality > cpi->worst_quality) {
  3132. cpi->active_worst_quality = cpi->worst_quality;
  3133. }
  3134. if (cpi->active_best_quality < cpi->best_quality) {
  3135. cpi->active_best_quality = cpi->best_quality;
  3136. }
  3137. if (cpi->active_worst_quality < cpi->active_best_quality) {
  3138. cpi->active_worst_quality = cpi->active_best_quality;
  3139. }
  3140. /* Determine initial Q to try */
  3141. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3142. #if !CONFIG_REALTIME_ONLY
  3143. /* Set highest allowed value for Zbin over quant */
  3144. if (cm->frame_type == KEY_FRAME) {
  3145. zbin_oq_high = 0;
  3146. } else if ((cpi->oxcf.number_of_layers == 1) &&
  3147. ((cm->refresh_alt_ref_frame ||
  3148. (cm->refresh_golden_frame && !cpi->source_alt_ref_active)))) {
  3149. zbin_oq_high = 16;
  3150. } else {
  3151. zbin_oq_high = ZBIN_OQ_MAX;
  3152. }
  3153. #endif
  3154. compute_skin_map(cpi);
  3155. /* Setup background Q adjustment for error resilient mode.
  3156. * For multi-layer encodes only enable this for the base layer.
  3157. */
  3158. if (cpi->cyclic_refresh_mode_enabled) {
  3159. // Special case for screen_content_mode with golden frame updates.
  3160. int disable_cr_gf =
  3161. (cpi->oxcf.screen_content_mode == 2 && cm->refresh_golden_frame);
  3162. if (cpi->current_layer == 0 && cpi->force_maxqp == 0 && !disable_cr_gf) {
  3163. cyclic_background_refresh(cpi, Q, 0);
  3164. } else {
  3165. disable_segmentation(cpi);
  3166. }
  3167. }
  3168. vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
  3169. &frame_over_shoot_limit);
  3170. #if !CONFIG_REALTIME_ONLY
  3171. /* Limit Q range for the adaptive loop. */
  3172. bottom_index = cpi->active_best_quality;
  3173. top_index = cpi->active_worst_quality;
  3174. q_low = cpi->active_best_quality;
  3175. q_high = cpi->active_worst_quality;
  3176. #endif
  3177. vp8_save_coding_context(cpi);
  3178. loop_count = 0;
  3179. scale_and_extend_source(cpi->un_scaled_source, cpi);
  3180. #if CONFIG_TEMPORAL_DENOISING && CONFIG_POSTPROC
  3181. // Option to apply spatial blur under the aggressive or adaptive
  3182. // (temporal denoising) mode.
  3183. if (cpi->oxcf.noise_sensitivity >= 3) {
  3184. if (cpi->denoiser.denoise_pars.spatial_blur != 0) {
  3185. vp8_de_noise(cm, cpi->Source, cpi->Source,
  3186. cpi->denoiser.denoise_pars.spatial_blur, 1, 0, 0);
  3187. }
  3188. }
  3189. #endif
  3190. #if !(CONFIG_REALTIME_ONLY) && CONFIG_POSTPROC && !(CONFIG_TEMPORAL_DENOISING)
  3191. if (cpi->oxcf.noise_sensitivity > 0) {
  3192. unsigned char *src;
  3193. int l = 0;
  3194. switch (cpi->oxcf.noise_sensitivity) {
  3195. case 1: l = 20; break;
  3196. case 2: l = 40; break;
  3197. case 3: l = 60; break;
  3198. case 4: l = 80; break;
  3199. case 5: l = 100; break;
  3200. case 6: l = 150; break;
  3201. }
  3202. if (cm->frame_type == KEY_FRAME) {
  3203. vp8_de_noise(cm, cpi->Source, cpi->Source, l, 1, 0, 1);
  3204. } else {
  3205. vp8_de_noise(cm, cpi->Source, cpi->Source, l, 1, 0, 1);
  3206. src = cpi->Source->y_buffer;
  3207. if (cpi->Source->y_stride < 0) {
  3208. src += cpi->Source->y_stride * (cpi->Source->y_height - 1);
  3209. }
  3210. }
  3211. }
  3212. #endif
  3213. #ifdef OUTPUT_YUV_SRC
  3214. vpx_write_yuv_frame(yuv_file, cpi->Source);
  3215. #endif
  3216. do {
  3217. vpx_clear_system_state();
  3218. vp8_set_quantizer(cpi, Q);
  3219. /* setup skip prob for costing in mode/mv decision */
  3220. if (cpi->common.mb_no_coeff_skip) {
  3221. cpi->prob_skip_false = cpi->base_skip_false_prob[Q];
  3222. if (cm->frame_type != KEY_FRAME) {
  3223. if (cpi->common.refresh_alt_ref_frame) {
  3224. if (cpi->last_skip_false_probs[2] != 0) {
  3225. cpi->prob_skip_false = cpi->last_skip_false_probs[2];
  3226. }
  3227. /*
  3228. if(cpi->last_skip_false_probs[2]!=0 && abs(Q-
  3229. cpi->last_skip_probs_q[2])<=16 )
  3230. cpi->prob_skip_false = cpi->last_skip_false_probs[2];
  3231. else if (cpi->last_skip_false_probs[2]!=0)
  3232. cpi->prob_skip_false = (cpi->last_skip_false_probs[2] +
  3233. cpi->prob_skip_false ) / 2;
  3234. */
  3235. } else if (cpi->common.refresh_golden_frame) {
  3236. if (cpi->last_skip_false_probs[1] != 0) {
  3237. cpi->prob_skip_false = cpi->last_skip_false_probs[1];
  3238. }
  3239. /*
  3240. if(cpi->last_skip_false_probs[1]!=0 && abs(Q-
  3241. cpi->last_skip_probs_q[1])<=16 )
  3242. cpi->prob_skip_false = cpi->last_skip_false_probs[1];
  3243. else if (cpi->last_skip_false_probs[1]!=0)
  3244. cpi->prob_skip_false = (cpi->last_skip_false_probs[1] +
  3245. cpi->prob_skip_false ) / 2;
  3246. */
  3247. } else {
  3248. if (cpi->last_skip_false_probs[0] != 0) {
  3249. cpi->prob_skip_false = cpi->last_skip_false_probs[0];
  3250. }
  3251. /*
  3252. if(cpi->last_skip_false_probs[0]!=0 && abs(Q-
  3253. cpi->last_skip_probs_q[0])<=16 )
  3254. cpi->prob_skip_false = cpi->last_skip_false_probs[0];
  3255. else if(cpi->last_skip_false_probs[0]!=0)
  3256. cpi->prob_skip_false = (cpi->last_skip_false_probs[0] +
  3257. cpi->prob_skip_false ) / 2;
  3258. */
  3259. }
  3260. /* as this is for cost estimate, let's make sure it does not
  3261. * go extreme eitehr way
  3262. */
  3263. if (cpi->prob_skip_false < 5) cpi->prob_skip_false = 5;
  3264. if (cpi->prob_skip_false > 250) cpi->prob_skip_false = 250;
  3265. if (cpi->oxcf.number_of_layers == 1 && cpi->is_src_frame_alt_ref) {
  3266. cpi->prob_skip_false = 1;
  3267. }
  3268. }
  3269. #if 0
  3270. if (cpi->pass != 1)
  3271. {
  3272. FILE *f = fopen("skip.stt", "a");
  3273. fprintf(f, "%d, %d, %4d ", cpi->common.refresh_golden_frame, cpi->common.refresh_alt_ref_frame, cpi->prob_skip_false);
  3274. fclose(f);
  3275. }
  3276. #endif
  3277. }
  3278. if (cm->frame_type == KEY_FRAME) {
  3279. if (resize_key_frame(cpi)) {
  3280. /* If the frame size has changed, need to reset Q, quantizer,
  3281. * and background refresh.
  3282. */
  3283. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3284. if (cpi->cyclic_refresh_mode_enabled) {
  3285. if (cpi->current_layer == 0) {
  3286. cyclic_background_refresh(cpi, Q, 0);
  3287. } else {
  3288. disable_segmentation(cpi);
  3289. }
  3290. }
  3291. // Reset the zero_last counter to 0 on key frame.
  3292. memset(cpi->consec_zero_last, 0, cm->mb_rows * cm->mb_cols);
  3293. memset(cpi->consec_zero_last_mvbias, 0,
  3294. (cpi->common.mb_rows * cpi->common.mb_cols));
  3295. vp8_set_quantizer(cpi, Q);
  3296. }
  3297. vp8_setup_key_frame(cpi);
  3298. }
  3299. #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
  3300. {
  3301. if (cpi->oxcf.error_resilient_mode) cm->refresh_entropy_probs = 0;
  3302. if (cpi->oxcf.error_resilient_mode & VPX_ERROR_RESILIENT_PARTITIONS) {
  3303. if (cm->frame_type == KEY_FRAME) cm->refresh_entropy_probs = 1;
  3304. }
  3305. if (cm->refresh_entropy_probs == 0) {
  3306. /* save a copy for later refresh */
  3307. memcpy(&cm->lfc, &cm->fc, sizeof(cm->fc));
  3308. }
  3309. vp8_update_coef_context(cpi);
  3310. vp8_update_coef_probs(cpi);
  3311. /* transform / motion compensation build reconstruction frame
  3312. * +pack coef partitions
  3313. */
  3314. vp8_encode_frame(cpi);
  3315. /* cpi->projected_frame_size is not needed for RT mode */
  3316. }
  3317. #else
  3318. /* transform / motion compensation build reconstruction frame */
  3319. vp8_encode_frame(cpi);
  3320. if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
  3321. if (vp8_drop_encodedframe_overshoot(cpi, Q)) return;
  3322. if (cm->frame_type != KEY_FRAME)
  3323. cpi->last_pred_err_mb =
  3324. (int)(cpi->mb.prediction_error / cpi->common.MBs);
  3325. }
  3326. cpi->projected_frame_size -= vp8_estimate_entropy_savings(cpi);
  3327. cpi->projected_frame_size =
  3328. (cpi->projected_frame_size > 0) ? cpi->projected_frame_size : 0;
  3329. #endif
  3330. vpx_clear_system_state();
  3331. /* Test to see if the stats generated for this frame indicate that
  3332. * we should have coded a key frame (assuming that we didn't)!
  3333. */
  3334. if (cpi->pass != 2 && cpi->oxcf.auto_key && cm->frame_type != KEY_FRAME &&
  3335. cpi->compressor_speed != 2) {
  3336. #if !CONFIG_REALTIME_ONLY
  3337. if (decide_key_frame(cpi)) {
  3338. /* Reset all our sizing numbers and recode */
  3339. cm->frame_type = KEY_FRAME;
  3340. vp8_pick_frame_size(cpi);
  3341. /* Clear the Alt reference frame active flag when we have
  3342. * a key frame
  3343. */
  3344. cpi->source_alt_ref_active = 0;
  3345. // Set the loop filter deltas and segmentation map update
  3346. setup_features(cpi);
  3347. vp8_restore_coding_context(cpi);
  3348. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3349. vp8_compute_frame_size_bounds(cpi, &frame_under_shoot_limit,
  3350. &frame_over_shoot_limit);
  3351. /* Limit Q range for the adaptive loop. */
  3352. bottom_index = cpi->active_best_quality;
  3353. top_index = cpi->active_worst_quality;
  3354. q_low = cpi->active_best_quality;
  3355. q_high = cpi->active_worst_quality;
  3356. loop_count++;
  3357. Loop = 1;
  3358. continue;
  3359. }
  3360. #endif
  3361. }
  3362. vpx_clear_system_state();
  3363. if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
  3364. /* Are we are overshooting and up against the limit of active max Q. */
  3365. if (((cpi->pass != 2) ||
  3366. (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)) &&
  3367. (Q == cpi->active_worst_quality) &&
  3368. (cpi->active_worst_quality < cpi->worst_quality) &&
  3369. (cpi->projected_frame_size > frame_over_shoot_limit)) {
  3370. int over_size_percent =
  3371. ((cpi->projected_frame_size - frame_over_shoot_limit) * 100) /
  3372. frame_over_shoot_limit;
  3373. /* If so is there any scope for relaxing it */
  3374. while ((cpi->active_worst_quality < cpi->worst_quality) &&
  3375. (over_size_percent > 0)) {
  3376. cpi->active_worst_quality++;
  3377. /* Assume 1 qstep = about 4% on frame size. */
  3378. over_size_percent = (int)(over_size_percent * 0.96);
  3379. }
  3380. #if !CONFIG_REALTIME_ONLY
  3381. top_index = cpi->active_worst_quality;
  3382. #endif // !CONFIG_REALTIME_ONLY
  3383. /* If we have updated the active max Q do not call
  3384. * vp8_update_rate_correction_factors() this loop.
  3385. */
  3386. active_worst_qchanged = 1;
  3387. } else {
  3388. active_worst_qchanged = 0;
  3389. }
  3390. #if CONFIG_REALTIME_ONLY
  3391. Loop = 0;
  3392. #else
  3393. /* Special case handling for forced key frames */
  3394. if ((cm->frame_type == KEY_FRAME) && cpi->this_key_frame_forced) {
  3395. int last_q = Q;
  3396. int kf_err = vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
  3397. /* The key frame is not good enough */
  3398. if (kf_err > ((cpi->ambient_err * 7) >> 3)) {
  3399. /* Lower q_high */
  3400. q_high = (Q > q_low) ? (Q - 1) : q_low;
  3401. /* Adjust Q */
  3402. Q = (q_high + q_low) >> 1;
  3403. }
  3404. /* The key frame is much better than the previous frame */
  3405. else if (kf_err < (cpi->ambient_err >> 1)) {
  3406. /* Raise q_low */
  3407. q_low = (Q < q_high) ? (Q + 1) : q_high;
  3408. /* Adjust Q */
  3409. Q = (q_high + q_low + 1) >> 1;
  3410. }
  3411. /* Clamp Q to upper and lower limits: */
  3412. if (Q > q_high) {
  3413. Q = q_high;
  3414. } else if (Q < q_low) {
  3415. Q = q_low;
  3416. }
  3417. Loop = Q != last_q;
  3418. }
  3419. /* Is the projected frame size out of range and are we allowed
  3420. * to attempt to recode.
  3421. */
  3422. else if (recode_loop_test(cpi, frame_over_shoot_limit,
  3423. frame_under_shoot_limit, Q, top_index,
  3424. bottom_index)) {
  3425. int last_q = Q;
  3426. int Retries = 0;
  3427. /* Frame size out of permitted range. Update correction factor
  3428. * & compute new Q to try...
  3429. */
  3430. /* Frame is too large */
  3431. if (cpi->projected_frame_size > cpi->this_frame_target) {
  3432. /* Raise Qlow as to at least the current value */
  3433. q_low = (Q < q_high) ? (Q + 1) : q_high;
  3434. /* If we are using over quant do the same for zbin_oq_low */
  3435. if (cpi->mb.zbin_over_quant > 0) {
  3436. zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
  3437. ? (cpi->mb.zbin_over_quant + 1)
  3438. : zbin_oq_high;
  3439. }
  3440. if (undershoot_seen) {
  3441. /* Update rate_correction_factor unless
  3442. * cpi->active_worst_quality has changed.
  3443. */
  3444. if (!active_worst_qchanged) {
  3445. vp8_update_rate_correction_factors(cpi, 1);
  3446. }
  3447. Q = (q_high + q_low + 1) / 2;
  3448. /* Adjust cpi->zbin_over_quant (only allowed when Q
  3449. * is max)
  3450. */
  3451. if (Q < MAXQ) {
  3452. cpi->mb.zbin_over_quant = 0;
  3453. } else {
  3454. zbin_oq_low = (cpi->mb.zbin_over_quant < zbin_oq_high)
  3455. ? (cpi->mb.zbin_over_quant + 1)
  3456. : zbin_oq_high;
  3457. cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
  3458. }
  3459. } else {
  3460. /* Update rate_correction_factor unless
  3461. * cpi->active_worst_quality has changed.
  3462. */
  3463. if (!active_worst_qchanged) {
  3464. vp8_update_rate_correction_factors(cpi, 0);
  3465. }
  3466. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3467. while (((Q < q_low) || (cpi->mb.zbin_over_quant < zbin_oq_low)) &&
  3468. (Retries < 10)) {
  3469. vp8_update_rate_correction_factors(cpi, 0);
  3470. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3471. Retries++;
  3472. }
  3473. }
  3474. overshoot_seen = 1;
  3475. }
  3476. /* Frame is too small */
  3477. else {
  3478. if (cpi->mb.zbin_over_quant == 0) {
  3479. /* Lower q_high if not using over quant */
  3480. q_high = (Q > q_low) ? (Q - 1) : q_low;
  3481. } else {
  3482. /* else lower zbin_oq_high */
  3483. zbin_oq_high = (cpi->mb.zbin_over_quant > zbin_oq_low)
  3484. ? (cpi->mb.zbin_over_quant - 1)
  3485. : zbin_oq_low;
  3486. }
  3487. if (overshoot_seen) {
  3488. /* Update rate_correction_factor unless
  3489. * cpi->active_worst_quality has changed.
  3490. */
  3491. if (!active_worst_qchanged) {
  3492. vp8_update_rate_correction_factors(cpi, 1);
  3493. }
  3494. Q = (q_high + q_low) / 2;
  3495. /* Adjust cpi->zbin_over_quant (only allowed when Q
  3496. * is max)
  3497. */
  3498. if (Q < MAXQ) {
  3499. cpi->mb.zbin_over_quant = 0;
  3500. } else {
  3501. cpi->mb.zbin_over_quant = (zbin_oq_high + zbin_oq_low) / 2;
  3502. }
  3503. } else {
  3504. /* Update rate_correction_factor unless
  3505. * cpi->active_worst_quality has changed.
  3506. */
  3507. if (!active_worst_qchanged) {
  3508. vp8_update_rate_correction_factors(cpi, 0);
  3509. }
  3510. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3511. /* Special case reset for qlow for constrained quality.
  3512. * This should only trigger where there is very substantial
  3513. * undershoot on a frame and the auto cq level is above
  3514. * the user passsed in value.
  3515. */
  3516. if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
  3517. (Q < q_low)) {
  3518. q_low = Q;
  3519. }
  3520. while (((Q > q_high) || (cpi->mb.zbin_over_quant > zbin_oq_high)) &&
  3521. (Retries < 10)) {
  3522. vp8_update_rate_correction_factors(cpi, 0);
  3523. Q = vp8_regulate_q(cpi, cpi->this_frame_target);
  3524. Retries++;
  3525. }
  3526. }
  3527. undershoot_seen = 1;
  3528. }
  3529. /* Clamp Q to upper and lower limits: */
  3530. if (Q > q_high) {
  3531. Q = q_high;
  3532. } else if (Q < q_low) {
  3533. Q = q_low;
  3534. }
  3535. /* Clamp cpi->zbin_over_quant */
  3536. cpi->mb.zbin_over_quant = (cpi->mb.zbin_over_quant < zbin_oq_low)
  3537. ? zbin_oq_low
  3538. : (cpi->mb.zbin_over_quant > zbin_oq_high)
  3539. ? zbin_oq_high
  3540. : cpi->mb.zbin_over_quant;
  3541. Loop = Q != last_q;
  3542. } else {
  3543. Loop = 0;
  3544. }
  3545. #endif // CONFIG_REALTIME_ONLY
  3546. if (cpi->is_src_frame_alt_ref) Loop = 0;
  3547. if (Loop == 1) {
  3548. vp8_restore_coding_context(cpi);
  3549. loop_count++;
  3550. #if CONFIG_INTERNAL_STATS
  3551. cpi->tot_recode_hits++;
  3552. #endif
  3553. }
  3554. } while (Loop == 1);
  3555. #if defined(DROP_UNCODED_FRAMES)
  3556. /* if there are no coded macroblocks at all drop this frame */
  3557. if (cpi->common.MBs == cpi->mb.skip_true_count &&
  3558. (cpi->drop_frame_count & 7) != 7 && cm->frame_type != KEY_FRAME) {
  3559. cpi->common.current_video_frame++;
  3560. cpi->frames_since_key++;
  3561. cpi->drop_frame_count++;
  3562. cpi->ext_refresh_frame_flags_pending = 0;
  3563. // We advance the temporal pattern for dropped frames.
  3564. cpi->temporal_pattern_counter++;
  3565. return;
  3566. }
  3567. cpi->drop_frame_count = 0;
  3568. #endif
  3569. #if 0
  3570. /* Experimental code for lagged and one pass
  3571. * Update stats used for one pass GF selection
  3572. */
  3573. {
  3574. cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_coded_error = (double)cpi->prediction_error;
  3575. cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_intra_error = (double)cpi->intra_error;
  3576. cpi->one_pass_frame_stats[cpi->one_pass_frame_index].frame_pcnt_inter = (double)(100 - cpi->this_frame_percent_intra) / 100.0;
  3577. }
  3578. #endif
  3579. /* Special case code to reduce pulsing when key frames are forced at a
  3580. * fixed interval. Note the reconstruction error if it is the frame before
  3581. * the force key frame
  3582. */
  3583. if (cpi->next_key_frame_forced && (cpi->twopass.frames_to_key == 0)) {
  3584. cpi->ambient_err =
  3585. vp8_calc_ss_err(cpi->Source, &cm->yv12_fb[cm->new_fb_idx]);
  3586. }
  3587. /* This frame's MVs are saved and will be used in next frame's MV predictor.
  3588. * Last frame has one more line(add to bottom) and one more column(add to
  3589. * right) than cm->mip. The edge elements are initialized to 0.
  3590. */
  3591. #if CONFIG_MULTI_RES_ENCODING
  3592. if (!cpi->oxcf.mr_encoder_id && cm->show_frame)
  3593. #else
  3594. if (cm->show_frame) /* do not save for altref frame */
  3595. #endif
  3596. {
  3597. int mb_row;
  3598. int mb_col;
  3599. /* Point to beginning of allocated MODE_INFO arrays. */
  3600. MODE_INFO *tmp = cm->mip;
  3601. if (cm->frame_type != KEY_FRAME) {
  3602. for (mb_row = 0; mb_row < cm->mb_rows + 1; ++mb_row) {
  3603. for (mb_col = 0; mb_col < cm->mb_cols + 1; ++mb_col) {
  3604. if (tmp->mbmi.ref_frame != INTRA_FRAME) {
  3605. cpi->lfmv[mb_col + mb_row * (cm->mode_info_stride + 1)].as_int =
  3606. tmp->mbmi.mv.as_int;
  3607. }
  3608. cpi->lf_ref_frame_sign_bias[mb_col +
  3609. mb_row * (cm->mode_info_stride + 1)] =
  3610. cm->ref_frame_sign_bias[tmp->mbmi.ref_frame];
  3611. cpi->lf_ref_frame[mb_col + mb_row * (cm->mode_info_stride + 1)] =
  3612. tmp->mbmi.ref_frame;
  3613. tmp++;
  3614. }
  3615. }
  3616. }
  3617. }
  3618. /* Count last ref frame 0,0 usage on current encoded frame. */
  3619. {
  3620. int mb_row;
  3621. int mb_col;
  3622. /* Point to beginning of MODE_INFO arrays. */
  3623. MODE_INFO *tmp = cm->mi;
  3624. cpi->zeromv_count = 0;
  3625. if (cm->frame_type != KEY_FRAME) {
  3626. for (mb_row = 0; mb_row < cm->mb_rows; ++mb_row) {
  3627. for (mb_col = 0; mb_col < cm->mb_cols; ++mb_col) {
  3628. if (tmp->mbmi.mode == ZEROMV && tmp->mbmi.ref_frame == LAST_FRAME) {
  3629. cpi->zeromv_count++;
  3630. }
  3631. tmp++;
  3632. }
  3633. tmp++;
  3634. }
  3635. }
  3636. }
  3637. #if CONFIG_MULTI_RES_ENCODING
  3638. vp8_cal_dissimilarity(cpi);
  3639. #endif
  3640. /* Update the GF useage maps.
  3641. * This is done after completing the compression of a frame when all
  3642. * modes etc. are finalized but before loop filter
  3643. */
  3644. if (cpi->oxcf.number_of_layers == 1) {
  3645. vp8_update_gf_useage_maps(cpi, cm, &cpi->mb);
  3646. }
  3647. if (cm->frame_type == KEY_FRAME) cm->refresh_last_frame = 1;
  3648. #if 0
  3649. {
  3650. FILE *f = fopen("gfactive.stt", "a");
  3651. fprintf(f, "%8d %8d %8d %8d %8d\n", cm->current_video_frame, (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols), cpi->this_iiratio, cpi->next_iiratio, cm->refresh_golden_frame);
  3652. fclose(f);
  3653. }
  3654. #endif
  3655. /* For inter frames the current default behavior is that when
  3656. * cm->refresh_golden_frame is set we copy the old GF over to the ARF buffer
  3657. * This is purely an encoder decision at present.
  3658. * Avoid this behavior when refresh flags are set by the user.
  3659. */
  3660. if (!cpi->oxcf.error_resilient_mode && cm->refresh_golden_frame &&
  3661. !cpi->ext_refresh_frame_flags_pending) {
  3662. cm->copy_buffer_to_arf = 2;
  3663. } else {
  3664. cm->copy_buffer_to_arf = 0;
  3665. }
  3666. cm->frame_to_show = &cm->yv12_fb[cm->new_fb_idx];
  3667. #if CONFIG_TEMPORAL_DENOISING
  3668. // Get some measure of the amount of noise, by measuring the (partial) mse
  3669. // between source and denoised buffer, for y channel. Partial refers to
  3670. // computing the sse for a sub-sample of the frame (i.e., skip x blocks along
  3671. // row/column),
  3672. // and only for blocks in that set that are consecutive ZEROMV_LAST mode.
  3673. // Do this every ~8 frames, to further reduce complexity.
  3674. // TODO(marpan): Keep this for now for the case cpi->oxcf.noise_sensitivity <
  3675. // 4,
  3676. // should be removed in favor of the process_denoiser_mode_change() function
  3677. // below.
  3678. if (cpi->oxcf.noise_sensitivity > 0 && cpi->oxcf.noise_sensitivity < 4 &&
  3679. !cpi->oxcf.screen_content_mode && cpi->frames_since_key % 8 == 0 &&
  3680. cm->frame_type != KEY_FRAME) {
  3681. cpi->mse_source_denoised = measure_square_diff_partial(
  3682. &cpi->denoiser.yv12_running_avg[INTRA_FRAME], cpi->Source, cpi);
  3683. }
  3684. // For the adaptive denoising mode (noise_sensitivity == 4), sample the mse
  3685. // of source diff (between current and previous frame), and determine if we
  3686. // should switch the denoiser mode. Sampling refers to computing the mse for
  3687. // a sub-sample of the frame (i.e., skip x blocks along row/column), and
  3688. // only for blocks in that set that have used ZEROMV LAST, along with some
  3689. // constraint on the sum diff between blocks. This process is called every
  3690. // ~8 frames, to further reduce complexity.
  3691. if (cpi->oxcf.noise_sensitivity == 4 && !cpi->oxcf.screen_content_mode &&
  3692. cpi->frames_since_key % 8 == 0 && cm->frame_type != KEY_FRAME) {
  3693. process_denoiser_mode_change(cpi);
  3694. }
  3695. #endif
  3696. #ifdef OUTPUT_YUV_SKINMAP
  3697. if (cpi->common.current_video_frame > 1) {
  3698. vp8_compute_skin_map(cpi, yuv_skinmap_file);
  3699. }
  3700. #endif
  3701. #if CONFIG_MULTITHREAD
  3702. if (vpx_atomic_load_acquire(&cpi->b_multi_threaded)) {
  3703. /* start loopfilter in separate thread */
  3704. sem_post(&cpi->h_event_start_lpf);
  3705. cpi->b_lpf_running = 1;
  3706. /* wait for the filter_level to be picked so that we can continue with
  3707. * stream packing */
  3708. sem_wait(&cpi->h_event_end_lpf);
  3709. } else
  3710. #endif
  3711. {
  3712. vp8_loopfilter_frame(cpi, cm);
  3713. }
  3714. update_reference_frames(cpi);
  3715. #ifdef OUTPUT_YUV_DENOISED
  3716. vpx_write_yuv_frame(yuv_denoised_file,
  3717. &cpi->denoiser.yv12_running_avg[INTRA_FRAME]);
  3718. #endif
  3719. #if !(CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
  3720. if (cpi->oxcf.error_resilient_mode) {
  3721. cm->refresh_entropy_probs = 0;
  3722. }
  3723. #endif
  3724. /* build the bitstream */
  3725. vp8_pack_bitstream(cpi, dest, dest_end, size);
  3726. /* Move storing frame_type out of the above loop since it is also
  3727. * needed in motion search besides loopfilter */
  3728. cm->last_frame_type = cm->frame_type;
  3729. /* Update rate control heuristics */
  3730. cpi->total_byte_count += (*size);
  3731. cpi->projected_frame_size = (int)(*size) << 3;
  3732. if (cpi->oxcf.number_of_layers > 1) {
  3733. unsigned int i;
  3734. for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
  3735. cpi->layer_context[i].total_byte_count += (*size);
  3736. }
  3737. }
  3738. if (!active_worst_qchanged) vp8_update_rate_correction_factors(cpi, 2);
  3739. cpi->last_q[cm->frame_type] = cm->base_qindex;
  3740. if (cm->frame_type == KEY_FRAME) {
  3741. vp8_adjust_key_frame_context(cpi);
  3742. }
  3743. /* Keep a record of ambient average Q. */
  3744. if (cm->frame_type != KEY_FRAME) {
  3745. cpi->avg_frame_qindex =
  3746. (2 + 3 * cpi->avg_frame_qindex + cm->base_qindex) >> 2;
  3747. }
  3748. /* Keep a record from which we can calculate the average Q excluding
  3749. * GF updates and key frames
  3750. */
  3751. if ((cm->frame_type != KEY_FRAME) &&
  3752. ((cpi->oxcf.number_of_layers > 1) ||
  3753. (!cm->refresh_golden_frame && !cm->refresh_alt_ref_frame))) {
  3754. cpi->ni_frames++;
  3755. /* Calculate the average Q for normal inter frames (not key or GFU
  3756. * frames).
  3757. */
  3758. if (cpi->pass == 2) {
  3759. cpi->ni_tot_qi += Q;
  3760. cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
  3761. } else {
  3762. /* Damp value for first few frames */
  3763. if (cpi->ni_frames > 150) {
  3764. cpi->ni_tot_qi += Q;
  3765. cpi->ni_av_qi = (cpi->ni_tot_qi / cpi->ni_frames);
  3766. }
  3767. /* For one pass, early in the clip ... average the current frame Q
  3768. * value with the worstq entered by the user as a dampening measure
  3769. */
  3770. else {
  3771. cpi->ni_tot_qi += Q;
  3772. cpi->ni_av_qi =
  3773. ((cpi->ni_tot_qi / cpi->ni_frames) + cpi->worst_quality + 1) / 2;
  3774. }
  3775. /* If the average Q is higher than what was used in the last
  3776. * frame (after going through the recode loop to keep the frame
  3777. * size within range) then use the last frame value - 1. The -1
  3778. * is designed to stop Q and hence the data rate, from
  3779. * progressively falling away during difficult sections, but at
  3780. * the same time reduce the number of itterations around the
  3781. * recode loop.
  3782. */
  3783. if (Q > cpi->ni_av_qi) cpi->ni_av_qi = Q - 1;
  3784. }
  3785. }
  3786. /* Update the buffer level variable. */
  3787. /* Non-viewable frames are a special case and are treated as pure overhead. */
  3788. if (!cm->show_frame) {
  3789. cpi->bits_off_target -= cpi->projected_frame_size;
  3790. } else {
  3791. cpi->bits_off_target +=
  3792. cpi->av_per_frame_bandwidth - cpi->projected_frame_size;
  3793. }
  3794. /* Clip the buffer level to the maximum specified buffer size */
  3795. if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size) {
  3796. cpi->bits_off_target = cpi->oxcf.maximum_buffer_size;
  3797. }
  3798. // If the frame dropper is not enabled, don't let the buffer level go below
  3799. // some threshold, given here by -|maximum_buffer_size|. For now we only do
  3800. // this for screen content input.
  3801. if (cpi->drop_frames_allowed == 0 && cpi->oxcf.screen_content_mode &&
  3802. cpi->bits_off_target < -cpi->oxcf.maximum_buffer_size) {
  3803. cpi->bits_off_target = -cpi->oxcf.maximum_buffer_size;
  3804. }
  3805. /* Rolling monitors of whether we are over or underspending used to
  3806. * help regulate min and Max Q in two pass.
  3807. */
  3808. cpi->rolling_target_bits =
  3809. ((cpi->rolling_target_bits * 3) + cpi->this_frame_target + 2) / 4;
  3810. cpi->rolling_actual_bits =
  3811. ((cpi->rolling_actual_bits * 3) + cpi->projected_frame_size + 2) / 4;
  3812. cpi->long_rolling_target_bits =
  3813. ((cpi->long_rolling_target_bits * 31) + cpi->this_frame_target + 16) / 32;
  3814. cpi->long_rolling_actual_bits =
  3815. ((cpi->long_rolling_actual_bits * 31) + cpi->projected_frame_size + 16) /
  3816. 32;
  3817. /* Actual bits spent */
  3818. cpi->total_actual_bits += cpi->projected_frame_size;
  3819. /* Debug stats */
  3820. cpi->total_target_vs_actual +=
  3821. (cpi->this_frame_target - cpi->projected_frame_size);
  3822. cpi->buffer_level = cpi->bits_off_target;
  3823. /* Propagate values to higher temporal layers */
  3824. if (cpi->oxcf.number_of_layers > 1) {
  3825. unsigned int i;
  3826. for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers; ++i) {
  3827. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  3828. int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
  3829. cpi->projected_frame_size);
  3830. lc->bits_off_target += bits_off_for_this_layer;
  3831. /* Clip buffer level to maximum buffer size for the layer */
  3832. if (lc->bits_off_target > lc->maximum_buffer_size) {
  3833. lc->bits_off_target = lc->maximum_buffer_size;
  3834. }
  3835. lc->total_actual_bits += cpi->projected_frame_size;
  3836. lc->total_target_vs_actual += bits_off_for_this_layer;
  3837. lc->buffer_level = lc->bits_off_target;
  3838. }
  3839. }
  3840. /* Update bits left to the kf and gf groups to account for overshoot
  3841. * or undershoot on these frames
  3842. */
  3843. if (cm->frame_type == KEY_FRAME) {
  3844. cpi->twopass.kf_group_bits +=
  3845. cpi->this_frame_target - cpi->projected_frame_size;
  3846. if (cpi->twopass.kf_group_bits < 0) cpi->twopass.kf_group_bits = 0;
  3847. } else if (cm->refresh_golden_frame || cm->refresh_alt_ref_frame) {
  3848. cpi->twopass.gf_group_bits +=
  3849. cpi->this_frame_target - cpi->projected_frame_size;
  3850. if (cpi->twopass.gf_group_bits < 0) cpi->twopass.gf_group_bits = 0;
  3851. }
  3852. if (cm->frame_type != KEY_FRAME) {
  3853. if (cpi->common.refresh_alt_ref_frame) {
  3854. cpi->last_skip_false_probs[2] = cpi->prob_skip_false;
  3855. cpi->last_skip_probs_q[2] = cm->base_qindex;
  3856. } else if (cpi->common.refresh_golden_frame) {
  3857. cpi->last_skip_false_probs[1] = cpi->prob_skip_false;
  3858. cpi->last_skip_probs_q[1] = cm->base_qindex;
  3859. } else {
  3860. cpi->last_skip_false_probs[0] = cpi->prob_skip_false;
  3861. cpi->last_skip_probs_q[0] = cm->base_qindex;
  3862. /* update the baseline */
  3863. cpi->base_skip_false_prob[cm->base_qindex] = cpi->prob_skip_false;
  3864. }
  3865. }
  3866. #if 0 && CONFIG_INTERNAL_STATS
  3867. {
  3868. FILE *f = fopen("tmp.stt", "a");
  3869. vpx_clear_system_state();
  3870. if (cpi->twopass.total_left_stats.coded_error != 0.0)
  3871. fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
  3872. "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
  3873. "%8.2lf %"PRId64" %10.3lf %10"PRId64" %8d\n",
  3874. cpi->common.current_video_frame, cpi->this_frame_target,
  3875. cpi->projected_frame_size,
  3876. (cpi->projected_frame_size - cpi->this_frame_target),
  3877. cpi->total_target_vs_actual,
  3878. cpi->buffer_level,
  3879. (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
  3880. cpi->total_actual_bits, cm->base_qindex,
  3881. cpi->active_best_quality, cpi->active_worst_quality,
  3882. cpi->ni_av_qi, cpi->cq_target_quality,
  3883. cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
  3884. cm->frame_type, cpi->gfu_boost,
  3885. cpi->twopass.est_max_qcorrection_factor,
  3886. cpi->twopass.bits_left,
  3887. cpi->twopass.total_left_stats.coded_error,
  3888. (double)cpi->twopass.bits_left /
  3889. cpi->twopass.total_left_stats.coded_error,
  3890. cpi->tot_recode_hits);
  3891. else
  3892. fprintf(f, "%10d %10d %10d %10d %10d %10"PRId64" %10"PRId64
  3893. "%10"PRId64" %10d %6d %6d %6d %6d %5d %5d %5d %8d "
  3894. "%8.2lf %"PRId64" %10.3lf %8d\n",
  3895. cpi->common.current_video_frame, cpi->this_frame_target,
  3896. cpi->projected_frame_size,
  3897. (cpi->projected_frame_size - cpi->this_frame_target),
  3898. cpi->total_target_vs_actual,
  3899. cpi->buffer_level,
  3900. (cpi->oxcf.starting_buffer_level-cpi->bits_off_target),
  3901. cpi->total_actual_bits, cm->base_qindex,
  3902. cpi->active_best_quality, cpi->active_worst_quality,
  3903. cpi->ni_av_qi, cpi->cq_target_quality,
  3904. cm->refresh_golden_frame, cm->refresh_alt_ref_frame,
  3905. cm->frame_type, cpi->gfu_boost,
  3906. cpi->twopass.est_max_qcorrection_factor,
  3907. cpi->twopass.bits_left,
  3908. cpi->twopass.total_left_stats.coded_error,
  3909. cpi->tot_recode_hits);
  3910. fclose(f);
  3911. {
  3912. FILE *fmodes = fopen("Modes.stt", "a");
  3913. fprintf(fmodes, "%6d:%1d:%1d:%1d ",
  3914. cpi->common.current_video_frame,
  3915. cm->frame_type, cm->refresh_golden_frame,
  3916. cm->refresh_alt_ref_frame);
  3917. fprintf(fmodes, "\n");
  3918. fclose(fmodes);
  3919. }
  3920. }
  3921. #endif
  3922. cpi->ext_refresh_frame_flags_pending = 0;
  3923. if (cm->refresh_golden_frame == 1) {
  3924. cm->frame_flags = cm->frame_flags | FRAMEFLAGS_GOLDEN;
  3925. } else {
  3926. cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_GOLDEN;
  3927. }
  3928. if (cm->refresh_alt_ref_frame == 1) {
  3929. cm->frame_flags = cm->frame_flags | FRAMEFLAGS_ALTREF;
  3930. } else {
  3931. cm->frame_flags = cm->frame_flags & ~FRAMEFLAGS_ALTREF;
  3932. }
  3933. if (cm->refresh_last_frame & cm->refresh_golden_frame) { /* both refreshed */
  3934. cpi->gold_is_last = 1;
  3935. } else if (cm->refresh_last_frame ^ cm->refresh_golden_frame) {
  3936. /* 1 refreshed but not the other */
  3937. cpi->gold_is_last = 0;
  3938. }
  3939. if (cm->refresh_last_frame & cm->refresh_alt_ref_frame) { /* both refreshed */
  3940. cpi->alt_is_last = 1;
  3941. } else if (cm->refresh_last_frame ^ cm->refresh_alt_ref_frame) {
  3942. /* 1 refreshed but not the other */
  3943. cpi->alt_is_last = 0;
  3944. }
  3945. if (cm->refresh_alt_ref_frame &
  3946. cm->refresh_golden_frame) { /* both refreshed */
  3947. cpi->gold_is_alt = 1;
  3948. } else if (cm->refresh_alt_ref_frame ^ cm->refresh_golden_frame) {
  3949. /* 1 refreshed but not the other */
  3950. cpi->gold_is_alt = 0;
  3951. }
  3952. cpi->ref_frame_flags = VP8_ALTR_FRAME | VP8_GOLD_FRAME | VP8_LAST_FRAME;
  3953. if (cpi->gold_is_last) cpi->ref_frame_flags &= ~VP8_GOLD_FRAME;
  3954. if (cpi->alt_is_last) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
  3955. if (cpi->gold_is_alt) cpi->ref_frame_flags &= ~VP8_ALTR_FRAME;
  3956. if (!cpi->oxcf.error_resilient_mode) {
  3957. if (cpi->oxcf.play_alternate && cm->refresh_alt_ref_frame &&
  3958. (cm->frame_type != KEY_FRAME)) {
  3959. /* Update the alternate reference frame stats as appropriate. */
  3960. update_alt_ref_frame_stats(cpi);
  3961. } else {
  3962. /* Update the Golden frame stats as appropriate. */
  3963. update_golden_frame_stats(cpi);
  3964. }
  3965. }
  3966. if (cm->frame_type == KEY_FRAME) {
  3967. /* Tell the caller that the frame was coded as a key frame */
  3968. *frame_flags = cm->frame_flags | FRAMEFLAGS_KEY;
  3969. /* As this frame is a key frame the next defaults to an inter frame. */
  3970. cm->frame_type = INTER_FRAME;
  3971. cpi->last_frame_percent_intra = 100;
  3972. } else {
  3973. *frame_flags = cm->frame_flags & ~FRAMEFLAGS_KEY;
  3974. cpi->last_frame_percent_intra = cpi->this_frame_percent_intra;
  3975. }
  3976. /* Clear the one shot update flags for segmentation map and mode/ref
  3977. * loop filter deltas.
  3978. */
  3979. cpi->mb.e_mbd.update_mb_segmentation_map = 0;
  3980. cpi->mb.e_mbd.update_mb_segmentation_data = 0;
  3981. cpi->mb.e_mbd.mode_ref_lf_delta_update = 0;
  3982. /* Dont increment frame counters if this was an altref buffer update
  3983. * not a real frame
  3984. */
  3985. if (cm->show_frame) {
  3986. cm->current_video_frame++;
  3987. cpi->frames_since_key++;
  3988. cpi->temporal_pattern_counter++;
  3989. }
  3990. #if 0
  3991. {
  3992. char filename[512];
  3993. FILE *recon_file;
  3994. sprintf(filename, "enc%04d.yuv", (int) cm->current_video_frame);
  3995. recon_file = fopen(filename, "wb");
  3996. fwrite(cm->yv12_fb[cm->lst_fb_idx].buffer_alloc,
  3997. cm->yv12_fb[cm->lst_fb_idx].frame_size, 1, recon_file);
  3998. fclose(recon_file);
  3999. }
  4000. #endif
  4001. /* DEBUG */
  4002. /* vpx_write_yuv_frame("encoder_recon.yuv", cm->frame_to_show); */
  4003. }
  4004. #if !CONFIG_REALTIME_ONLY
  4005. static void Pass2Encode(VP8_COMP *cpi, size_t *size, unsigned char *dest,
  4006. unsigned char *dest_end, unsigned int *frame_flags) {
  4007. if (!cpi->common.refresh_alt_ref_frame) vp8_second_pass(cpi);
  4008. encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
  4009. cpi->twopass.bits_left -= 8 * (int)(*size);
  4010. if (!cpi->common.refresh_alt_ref_frame) {
  4011. double two_pass_min_rate =
  4012. (double)(cpi->oxcf.target_bandwidth *
  4013. cpi->oxcf.two_pass_vbrmin_section / 100);
  4014. cpi->twopass.bits_left += (int64_t)(two_pass_min_rate / cpi->framerate);
  4015. }
  4016. }
  4017. #endif
  4018. int vp8_receive_raw_frame(VP8_COMP *cpi, unsigned int frame_flags,
  4019. YV12_BUFFER_CONFIG *sd, int64_t time_stamp,
  4020. int64_t end_time) {
  4021. struct vpx_usec_timer timer;
  4022. int res = 0;
  4023. vpx_usec_timer_start(&timer);
  4024. /* Reinit the lookahead buffer if the frame size changes */
  4025. if (sd->y_width != cpi->oxcf.Width || sd->y_height != cpi->oxcf.Height) {
  4026. assert(cpi->oxcf.lag_in_frames < 2);
  4027. dealloc_raw_frame_buffers(cpi);
  4028. alloc_raw_frame_buffers(cpi);
  4029. }
  4030. if (vp8_lookahead_push(cpi->lookahead, sd, time_stamp, end_time, frame_flags,
  4031. cpi->active_map_enabled ? cpi->active_map : NULL)) {
  4032. res = -1;
  4033. }
  4034. vpx_usec_timer_mark(&timer);
  4035. cpi->time_receive_data += vpx_usec_timer_elapsed(&timer);
  4036. return res;
  4037. }
  4038. static int frame_is_reference(const VP8_COMP *cpi) {
  4039. const VP8_COMMON *cm = &cpi->common;
  4040. const MACROBLOCKD *xd = &cpi->mb.e_mbd;
  4041. return cm->frame_type == KEY_FRAME || cm->refresh_last_frame ||
  4042. cm->refresh_golden_frame || cm->refresh_alt_ref_frame ||
  4043. cm->copy_buffer_to_gf || cm->copy_buffer_to_arf ||
  4044. cm->refresh_entropy_probs || xd->mode_ref_lf_delta_update ||
  4045. xd->update_mb_segmentation_map || xd->update_mb_segmentation_data;
  4046. }
  4047. int vp8_get_compressed_data(VP8_COMP *cpi, unsigned int *frame_flags,
  4048. size_t *size, unsigned char *dest,
  4049. unsigned char *dest_end, int64_t *time_stamp,
  4050. int64_t *time_end, int flush) {
  4051. VP8_COMMON *cm;
  4052. struct vpx_usec_timer tsctimer;
  4053. struct vpx_usec_timer ticktimer;
  4054. struct vpx_usec_timer cmptimer;
  4055. YV12_BUFFER_CONFIG *force_src_buffer = NULL;
  4056. if (!cpi) return -1;
  4057. cm = &cpi->common;
  4058. vpx_usec_timer_start(&cmptimer);
  4059. cpi->source = NULL;
  4060. #if !CONFIG_REALTIME_ONLY
  4061. /* Should we code an alternate reference frame */
  4062. if (cpi->oxcf.error_resilient_mode == 0 && cpi->oxcf.play_alternate &&
  4063. cpi->source_alt_ref_pending) {
  4064. if ((cpi->source = vp8_lookahead_peek(
  4065. cpi->lookahead, cpi->frames_till_gf_update_due, PEEK_FORWARD))) {
  4066. cpi->alt_ref_source = cpi->source;
  4067. if (cpi->oxcf.arnr_max_frames > 0) {
  4068. vp8_temporal_filter_prepare_c(cpi, cpi->frames_till_gf_update_due);
  4069. force_src_buffer = &cpi->alt_ref_buffer;
  4070. }
  4071. cpi->frames_till_alt_ref_frame = cpi->frames_till_gf_update_due;
  4072. cm->refresh_alt_ref_frame = 1;
  4073. cm->refresh_golden_frame = 0;
  4074. cm->refresh_last_frame = 0;
  4075. cm->show_frame = 0;
  4076. /* Clear Pending alt Ref flag. */
  4077. cpi->source_alt_ref_pending = 0;
  4078. cpi->is_src_frame_alt_ref = 0;
  4079. }
  4080. }
  4081. #endif
  4082. if (!cpi->source) {
  4083. /* Read last frame source if we are encoding first pass. */
  4084. if (cpi->pass == 1 && cm->current_video_frame > 0) {
  4085. if ((cpi->last_source =
  4086. vp8_lookahead_peek(cpi->lookahead, 1, PEEK_BACKWARD)) == NULL) {
  4087. return -1;
  4088. }
  4089. }
  4090. if ((cpi->source = vp8_lookahead_pop(cpi->lookahead, flush))) {
  4091. cm->show_frame = 1;
  4092. cpi->is_src_frame_alt_ref =
  4093. cpi->alt_ref_source && (cpi->source == cpi->alt_ref_source);
  4094. if (cpi->is_src_frame_alt_ref) cpi->alt_ref_source = NULL;
  4095. }
  4096. }
  4097. if (cpi->source) {
  4098. cpi->Source = force_src_buffer ? force_src_buffer : &cpi->source->img;
  4099. cpi->un_scaled_source = cpi->Source;
  4100. *time_stamp = cpi->source->ts_start;
  4101. *time_end = cpi->source->ts_end;
  4102. *frame_flags = cpi->source->flags;
  4103. if (cpi->pass == 1 && cm->current_video_frame > 0) {
  4104. cpi->last_frame_unscaled_source = &cpi->last_source->img;
  4105. }
  4106. } else {
  4107. *size = 0;
  4108. #if !CONFIG_REALTIME_ONLY
  4109. if (flush && cpi->pass == 1 && !cpi->twopass.first_pass_done) {
  4110. vp8_end_first_pass(cpi); /* get last stats packet */
  4111. cpi->twopass.first_pass_done = 1;
  4112. }
  4113. #endif
  4114. return -1;
  4115. }
  4116. if (cpi->source->ts_start < cpi->first_time_stamp_ever) {
  4117. cpi->first_time_stamp_ever = cpi->source->ts_start;
  4118. cpi->last_end_time_stamp_seen = cpi->source->ts_start;
  4119. }
  4120. /* adjust frame rates based on timestamps given */
  4121. if (cm->show_frame) {
  4122. int64_t this_duration;
  4123. int step = 0;
  4124. if (cpi->source->ts_start == cpi->first_time_stamp_ever) {
  4125. this_duration = cpi->source->ts_end - cpi->source->ts_start;
  4126. step = 1;
  4127. } else {
  4128. int64_t last_duration;
  4129. this_duration = cpi->source->ts_end - cpi->last_end_time_stamp_seen;
  4130. last_duration = cpi->last_end_time_stamp_seen - cpi->last_time_stamp_seen;
  4131. /* do a step update if the duration changes by 10% */
  4132. if (last_duration) {
  4133. step = (int)(((this_duration - last_duration) * 10 / last_duration));
  4134. }
  4135. }
  4136. if (this_duration) {
  4137. if (step) {
  4138. cpi->ref_framerate = 10000000.0 / this_duration;
  4139. } else {
  4140. double avg_duration, interval;
  4141. /* Average this frame's rate into the last second's average
  4142. * frame rate. If we haven't seen 1 second yet, then average
  4143. * over the whole interval seen.
  4144. */
  4145. interval = (double)(cpi->source->ts_end - cpi->first_time_stamp_ever);
  4146. if (interval > 10000000.0) interval = 10000000;
  4147. avg_duration = 10000000.0 / cpi->ref_framerate;
  4148. avg_duration *= (interval - avg_duration + this_duration);
  4149. avg_duration /= interval;
  4150. cpi->ref_framerate = 10000000.0 / avg_duration;
  4151. }
  4152. #if CONFIG_MULTI_RES_ENCODING
  4153. if (cpi->oxcf.mr_total_resolutions > 1) {
  4154. LOWER_RES_FRAME_INFO *low_res_frame_info =
  4155. (LOWER_RES_FRAME_INFO *)cpi->oxcf.mr_low_res_mode_info;
  4156. // Frame rate should be the same for all spatial layers in
  4157. // multi-res-encoding (simulcast), so we constrain the frame for
  4158. // higher layers to be that of lowest resolution. This is needed
  4159. // as he application may decide to skip encoding a high layer and
  4160. // then start again, in which case a big jump in time-stamps will
  4161. // be received for that high layer, which will yield an incorrect
  4162. // frame rate (from time-stamp adjustment in above calculation).
  4163. if (cpi->oxcf.mr_encoder_id) {
  4164. if (!low_res_frame_info->skip_encoding_base_stream)
  4165. cpi->ref_framerate = low_res_frame_info->low_res_framerate;
  4166. } else {
  4167. // Keep track of frame rate for lowest resolution.
  4168. low_res_frame_info->low_res_framerate = cpi->ref_framerate;
  4169. // The base stream is being encoded so set skip flag to 0.
  4170. low_res_frame_info->skip_encoding_base_stream = 0;
  4171. }
  4172. }
  4173. #endif
  4174. if (cpi->oxcf.number_of_layers > 1) {
  4175. unsigned int i;
  4176. /* Update frame rates for each layer */
  4177. assert(cpi->oxcf.number_of_layers <= VPX_TS_MAX_LAYERS);
  4178. for (i = 0; i < cpi->oxcf.number_of_layers && i < VPX_TS_MAX_LAYERS;
  4179. ++i) {
  4180. LAYER_CONTEXT *lc = &cpi->layer_context[i];
  4181. lc->framerate = cpi->ref_framerate / cpi->oxcf.rate_decimator[i];
  4182. }
  4183. } else {
  4184. vp8_new_framerate(cpi, cpi->ref_framerate);
  4185. }
  4186. }
  4187. cpi->last_time_stamp_seen = cpi->source->ts_start;
  4188. cpi->last_end_time_stamp_seen = cpi->source->ts_end;
  4189. }
  4190. if (cpi->oxcf.number_of_layers > 1) {
  4191. int layer;
  4192. update_layer_contexts(cpi);
  4193. /* Restore layer specific context & set frame rate */
  4194. if (cpi->temporal_layer_id >= 0) {
  4195. layer = cpi->temporal_layer_id;
  4196. } else {
  4197. layer =
  4198. cpi->oxcf
  4199. .layer_id[cpi->temporal_pattern_counter % cpi->oxcf.periodicity];
  4200. }
  4201. restore_layer_context(cpi, layer);
  4202. vp8_new_framerate(cpi, cpi->layer_context[layer].framerate);
  4203. }
  4204. if (cpi->compressor_speed == 2) {
  4205. vpx_usec_timer_start(&tsctimer);
  4206. vpx_usec_timer_start(&ticktimer);
  4207. }
  4208. cpi->lf_zeromv_pct = (cpi->zeromv_count * 100) / cm->MBs;
  4209. #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
  4210. {
  4211. int i;
  4212. const int num_part = (1 << cm->multi_token_partition);
  4213. /* the available bytes in dest */
  4214. const unsigned long dest_size = dest_end - dest;
  4215. const int tok_part_buff_size = (dest_size * 9) / (10 * num_part);
  4216. unsigned char *dp = dest;
  4217. cpi->partition_d[0] = dp;
  4218. dp += dest_size / 10; /* reserve 1/10 for control partition */
  4219. cpi->partition_d_end[0] = dp;
  4220. for (i = 0; i < num_part; ++i) {
  4221. cpi->partition_d[i + 1] = dp;
  4222. dp += tok_part_buff_size;
  4223. cpi->partition_d_end[i + 1] = dp;
  4224. }
  4225. }
  4226. #endif
  4227. /* start with a 0 size frame */
  4228. *size = 0;
  4229. /* Clear down mmx registers */
  4230. vpx_clear_system_state();
  4231. cm->frame_type = INTER_FRAME;
  4232. cm->frame_flags = *frame_flags;
  4233. #if 0
  4234. if (cm->refresh_alt_ref_frame)
  4235. {
  4236. cm->refresh_golden_frame = 0;
  4237. cm->refresh_last_frame = 0;
  4238. }
  4239. else
  4240. {
  4241. cm->refresh_golden_frame = 0;
  4242. cm->refresh_last_frame = 1;
  4243. }
  4244. #endif
  4245. /* find a free buffer for the new frame */
  4246. {
  4247. int i = 0;
  4248. for (; i < NUM_YV12_BUFFERS; ++i) {
  4249. if (!cm->yv12_fb[i].flags) {
  4250. cm->new_fb_idx = i;
  4251. break;
  4252. }
  4253. }
  4254. assert(i < NUM_YV12_BUFFERS);
  4255. }
  4256. switch (cpi->pass) {
  4257. #if !CONFIG_REALTIME_ONLY
  4258. case 1: Pass1Encode(cpi, size, dest, frame_flags); break;
  4259. case 2: Pass2Encode(cpi, size, dest, dest_end, frame_flags); break;
  4260. #endif // !CONFIG_REALTIME_ONLY
  4261. default:
  4262. encode_frame_to_data_rate(cpi, size, dest, dest_end, frame_flags);
  4263. break;
  4264. }
  4265. if (cpi->compressor_speed == 2) {
  4266. unsigned int duration, duration2;
  4267. vpx_usec_timer_mark(&tsctimer);
  4268. vpx_usec_timer_mark(&ticktimer);
  4269. duration = (int)(vpx_usec_timer_elapsed(&ticktimer));
  4270. duration2 = (unsigned int)((double)duration / 2);
  4271. if (cm->frame_type != KEY_FRAME) {
  4272. if (cpi->avg_encode_time == 0) {
  4273. cpi->avg_encode_time = duration;
  4274. } else {
  4275. cpi->avg_encode_time = (7 * cpi->avg_encode_time + duration) >> 3;
  4276. }
  4277. }
  4278. if (duration2) {
  4279. {
  4280. if (cpi->avg_pick_mode_time == 0) {
  4281. cpi->avg_pick_mode_time = duration2;
  4282. } else {
  4283. cpi->avg_pick_mode_time =
  4284. (7 * cpi->avg_pick_mode_time + duration2) >> 3;
  4285. }
  4286. }
  4287. }
  4288. }
  4289. if (cm->refresh_entropy_probs == 0) {
  4290. memcpy(&cm->fc, &cm->lfc, sizeof(cm->fc));
  4291. }
  4292. /* Save the contexts separately for alt ref, gold and last. */
  4293. /* (TODO jbb -> Optimize this with pointers to avoid extra copies. ) */
  4294. if (cm->refresh_alt_ref_frame) memcpy(&cpi->lfc_a, &cm->fc, sizeof(cm->fc));
  4295. if (cm->refresh_golden_frame) memcpy(&cpi->lfc_g, &cm->fc, sizeof(cm->fc));
  4296. if (cm->refresh_last_frame) memcpy(&cpi->lfc_n, &cm->fc, sizeof(cm->fc));
  4297. /* if its a dropped frame honor the requests on subsequent frames */
  4298. if (*size > 0) {
  4299. cpi->droppable = !frame_is_reference(cpi);
  4300. /* return to normal state */
  4301. cm->refresh_entropy_probs = 1;
  4302. cm->refresh_alt_ref_frame = 0;
  4303. cm->refresh_golden_frame = 0;
  4304. cm->refresh_last_frame = 1;
  4305. cm->frame_type = INTER_FRAME;
  4306. }
  4307. /* Save layer specific state */
  4308. if (cpi->oxcf.number_of_layers > 1) save_layer_context(cpi);
  4309. vpx_usec_timer_mark(&cmptimer);
  4310. cpi->time_compress_data += vpx_usec_timer_elapsed(&cmptimer);
  4311. if (cpi->b_calculate_psnr && cpi->pass != 1 && cm->show_frame) {
  4312. generate_psnr_packet(cpi);
  4313. }
  4314. #if CONFIG_INTERNAL_STATS
  4315. if (cpi->pass != 1) {
  4316. cpi->bytes += *size;
  4317. if (cm->show_frame) {
  4318. cpi->common.show_frame_mi = cpi->common.mi;
  4319. cpi->count++;
  4320. if (cpi->b_calculate_psnr) {
  4321. uint64_t ye, ue, ve;
  4322. double frame_psnr;
  4323. YV12_BUFFER_CONFIG *orig = cpi->Source;
  4324. YV12_BUFFER_CONFIG *recon = cpi->common.frame_to_show;
  4325. unsigned int y_width = cpi->common.Width;
  4326. unsigned int y_height = cpi->common.Height;
  4327. unsigned int uv_width = (y_width + 1) / 2;
  4328. unsigned int uv_height = (y_height + 1) / 2;
  4329. int y_samples = y_height * y_width;
  4330. int uv_samples = uv_height * uv_width;
  4331. int t_samples = y_samples + 2 * uv_samples;
  4332. double sq_error;
  4333. ye = calc_plane_error(orig->y_buffer, orig->y_stride, recon->y_buffer,
  4334. recon->y_stride, y_width, y_height);
  4335. ue = calc_plane_error(orig->u_buffer, orig->uv_stride, recon->u_buffer,
  4336. recon->uv_stride, uv_width, uv_height);
  4337. ve = calc_plane_error(orig->v_buffer, orig->uv_stride, recon->v_buffer,
  4338. recon->uv_stride, uv_width, uv_height);
  4339. sq_error = (double)(ye + ue + ve);
  4340. frame_psnr = vpx_sse_to_psnr(t_samples, 255.0, sq_error);
  4341. cpi->total_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
  4342. cpi->total_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
  4343. cpi->total_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
  4344. cpi->total_sq_error += sq_error;
  4345. cpi->total += frame_psnr;
  4346. #if CONFIG_POSTPROC
  4347. {
  4348. YV12_BUFFER_CONFIG *pp = &cm->post_proc_buffer;
  4349. double sq_error2;
  4350. double frame_psnr2, frame_ssim2 = 0;
  4351. double weight = 0;
  4352. vp8_deblock(cm, cm->frame_to_show, &cm->post_proc_buffer,
  4353. cm->filter_level * 10 / 6, 1, 0);
  4354. vpx_clear_system_state();
  4355. ye = calc_plane_error(orig->y_buffer, orig->y_stride, pp->y_buffer,
  4356. pp->y_stride, y_width, y_height);
  4357. ue = calc_plane_error(orig->u_buffer, orig->uv_stride, pp->u_buffer,
  4358. pp->uv_stride, uv_width, uv_height);
  4359. ve = calc_plane_error(orig->v_buffer, orig->uv_stride, pp->v_buffer,
  4360. pp->uv_stride, uv_width, uv_height);
  4361. sq_error2 = (double)(ye + ue + ve);
  4362. frame_psnr2 = vpx_sse_to_psnr(t_samples, 255.0, sq_error2);
  4363. cpi->totalp_y += vpx_sse_to_psnr(y_samples, 255.0, (double)ye);
  4364. cpi->totalp_u += vpx_sse_to_psnr(uv_samples, 255.0, (double)ue);
  4365. cpi->totalp_v += vpx_sse_to_psnr(uv_samples, 255.0, (double)ve);
  4366. cpi->total_sq_error2 += sq_error2;
  4367. cpi->totalp += frame_psnr2;
  4368. frame_ssim2 =
  4369. vpx_calc_ssim(cpi->Source, &cm->post_proc_buffer, &weight);
  4370. cpi->summed_quality += frame_ssim2 * weight;
  4371. cpi->summed_weights += weight;
  4372. if (cpi->oxcf.number_of_layers > 1) {
  4373. unsigned int i;
  4374. for (i = cpi->current_layer; i < cpi->oxcf.number_of_layers; ++i) {
  4375. cpi->frames_in_layer[i]++;
  4376. cpi->bytes_in_layer[i] += *size;
  4377. cpi->sum_psnr[i] += frame_psnr;
  4378. cpi->sum_psnr_p[i] += frame_psnr2;
  4379. cpi->total_error2[i] += sq_error;
  4380. cpi->total_error2_p[i] += sq_error2;
  4381. cpi->sum_ssim[i] += frame_ssim2 * weight;
  4382. cpi->sum_weights[i] += weight;
  4383. }
  4384. }
  4385. }
  4386. #endif
  4387. }
  4388. }
  4389. }
  4390. #if 0
  4391. if (cpi->common.frame_type != 0 && cpi->common.base_qindex == cpi->oxcf.worst_allowed_q)
  4392. {
  4393. skiptruecount += cpi->skip_true_count;
  4394. skipfalsecount += cpi->skip_false_count;
  4395. }
  4396. #endif
  4397. #if 0
  4398. if (cpi->pass != 1)
  4399. {
  4400. FILE *f = fopen("skip.stt", "a");
  4401. fprintf(f, "frame:%4d flags:%4x Q:%4d P:%4d Size:%5d\n", cpi->common.current_video_frame, *frame_flags, cpi->common.base_qindex, cpi->prob_skip_false, *size);
  4402. if (cpi->is_src_frame_alt_ref == 1)
  4403. fprintf(f, "skipcount: %4d framesize: %d\n", cpi->skip_true_count , *size);
  4404. fclose(f);
  4405. }
  4406. #endif
  4407. #endif
  4408. cpi->common.error.setjmp = 0;
  4409. #if CONFIG_MULTITHREAD
  4410. /* wait for the lpf thread done */
  4411. if (vpx_atomic_load_acquire(&cpi->b_multi_threaded) && cpi->b_lpf_running) {
  4412. sem_wait(&cpi->h_event_end_lpf);
  4413. cpi->b_lpf_running = 0;
  4414. }
  4415. #endif
  4416. return 0;
  4417. }
  4418. int vp8_get_preview_raw_frame(VP8_COMP *cpi, YV12_BUFFER_CONFIG *dest,
  4419. vp8_ppflags_t *flags) {
  4420. if (cpi->common.refresh_alt_ref_frame) {
  4421. return -1;
  4422. } else {
  4423. int ret;
  4424. #if CONFIG_POSTPROC
  4425. cpi->common.show_frame_mi = cpi->common.mi;
  4426. ret = vp8_post_proc_frame(&cpi->common, dest, flags);
  4427. #else
  4428. (void)flags;
  4429. if (cpi->common.frame_to_show) {
  4430. *dest = *cpi->common.frame_to_show;
  4431. dest->y_width = cpi->common.Width;
  4432. dest->y_height = cpi->common.Height;
  4433. dest->uv_height = cpi->common.Height / 2;
  4434. ret = 0;
  4435. } else {
  4436. ret = -1;
  4437. }
  4438. #endif
  4439. vpx_clear_system_state();
  4440. return ret;
  4441. }
  4442. }
  4443. int vp8_set_roimap(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
  4444. unsigned int cols, int delta_q[4], int delta_lf[4],
  4445. unsigned int threshold[4]) {
  4446. signed char feature_data[MB_LVL_MAX][MAX_MB_SEGMENTS];
  4447. int internal_delta_q[MAX_MB_SEGMENTS];
  4448. const int range = 63;
  4449. int i;
  4450. // Check number of rows and columns match
  4451. if (cpi->common.mb_rows != (int)rows || cpi->common.mb_cols != (int)cols) {
  4452. return -1;
  4453. }
  4454. // Range check the delta Q values and convert the external Q range values
  4455. // to internal ones.
  4456. if ((abs(delta_q[0]) > range) || (abs(delta_q[1]) > range) ||
  4457. (abs(delta_q[2]) > range) || (abs(delta_q[3]) > range)) {
  4458. return -1;
  4459. }
  4460. // Range check the delta lf values
  4461. if ((abs(delta_lf[0]) > range) || (abs(delta_lf[1]) > range) ||
  4462. (abs(delta_lf[2]) > range) || (abs(delta_lf[3]) > range)) {
  4463. return -1;
  4464. }
  4465. // Also disable segmentation if no deltas are specified.
  4466. if (!map || (delta_q[0] == 0 && delta_q[1] == 0 && delta_q[2] == 0 &&
  4467. delta_q[3] == 0 && delta_lf[0] == 0 && delta_lf[1] == 0 &&
  4468. delta_lf[2] == 0 && delta_lf[3] == 0 && threshold[0] == 0 &&
  4469. threshold[1] == 0 && threshold[2] == 0 && threshold[3] == 0)) {
  4470. disable_segmentation(cpi);
  4471. return 0;
  4472. }
  4473. // Translate the external delta q values to internal values.
  4474. for (i = 0; i < MAX_MB_SEGMENTS; ++i) {
  4475. internal_delta_q[i] =
  4476. (delta_q[i] >= 0) ? q_trans[delta_q[i]] : -q_trans[-delta_q[i]];
  4477. }
  4478. /* Set the segmentation Map */
  4479. set_segmentation_map(cpi, map);
  4480. /* Activate segmentation. */
  4481. enable_segmentation(cpi);
  4482. /* Set up the quant segment data */
  4483. feature_data[MB_LVL_ALT_Q][0] = internal_delta_q[0];
  4484. feature_data[MB_LVL_ALT_Q][1] = internal_delta_q[1];
  4485. feature_data[MB_LVL_ALT_Q][2] = internal_delta_q[2];
  4486. feature_data[MB_LVL_ALT_Q][3] = internal_delta_q[3];
  4487. /* Set up the loop segment data s */
  4488. feature_data[MB_LVL_ALT_LF][0] = delta_lf[0];
  4489. feature_data[MB_LVL_ALT_LF][1] = delta_lf[1];
  4490. feature_data[MB_LVL_ALT_LF][2] = delta_lf[2];
  4491. feature_data[MB_LVL_ALT_LF][3] = delta_lf[3];
  4492. cpi->segment_encode_breakout[0] = threshold[0];
  4493. cpi->segment_encode_breakout[1] = threshold[1];
  4494. cpi->segment_encode_breakout[2] = threshold[2];
  4495. cpi->segment_encode_breakout[3] = threshold[3];
  4496. /* Initialise the feature data structure */
  4497. set_segment_data(cpi, &feature_data[0][0], SEGMENT_DELTADATA);
  4498. if (threshold[0] != 0 || threshold[1] != 0 || threshold[2] != 0 ||
  4499. threshold[3] != 0)
  4500. cpi->use_roi_static_threshold = 1;
  4501. cpi->cyclic_refresh_mode_enabled = 0;
  4502. return 0;
  4503. }
  4504. int vp8_set_active_map(VP8_COMP *cpi, unsigned char *map, unsigned int rows,
  4505. unsigned int cols) {
  4506. if ((int)rows == cpi->common.mb_rows && (int)cols == cpi->common.mb_cols) {
  4507. if (map) {
  4508. memcpy(cpi->active_map, map, rows * cols);
  4509. cpi->active_map_enabled = 1;
  4510. } else {
  4511. cpi->active_map_enabled = 0;
  4512. }
  4513. return 0;
  4514. } else {
  4515. return -1;
  4516. }
  4517. }
  4518. int vp8_set_internal_size(VP8_COMP *cpi, VPX_SCALING horiz_mode,
  4519. VPX_SCALING vert_mode) {
  4520. if (horiz_mode <= ONETWO) {
  4521. cpi->common.horiz_scale = horiz_mode;
  4522. } else {
  4523. return -1;
  4524. }
  4525. if (vert_mode <= ONETWO) {
  4526. cpi->common.vert_scale = vert_mode;
  4527. } else {
  4528. return -1;
  4529. }
  4530. return 0;
  4531. }
  4532. int vp8_calc_ss_err(YV12_BUFFER_CONFIG *source, YV12_BUFFER_CONFIG *dest) {
  4533. int i, j;
  4534. int Total = 0;
  4535. unsigned char *src = source->y_buffer;
  4536. unsigned char *dst = dest->y_buffer;
  4537. /* Loop through the Y plane raw and reconstruction data summing
  4538. * (square differences)
  4539. */
  4540. for (i = 0; i < source->y_height; i += 16) {
  4541. for (j = 0; j < source->y_width; j += 16) {
  4542. unsigned int sse;
  4543. Total += vpx_mse16x16(src + j, source->y_stride, dst + j, dest->y_stride,
  4544. &sse);
  4545. }
  4546. src += 16 * source->y_stride;
  4547. dst += 16 * dest->y_stride;
  4548. }
  4549. return Total;
  4550. }
  4551. int vp8_get_quantizer(VP8_COMP *cpi) { return cpi->common.base_qindex; }