onyx_if.c 179 KB

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