encoder.c 175 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503
  1. /*****************************************************************************
  2. * encoder.c: top-level encoder functions
  3. *****************************************************************************
  4. * Copyright (C) 2003-2018 x264 project
  5. *
  6. * Authors: Laurent Aimar <fenrir@via.ecp.fr>
  7. * Loren Merritt <lorenm@u.washington.edu>
  8. * Fiona Glaser <fiona@x264.com>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
  23. *
  24. * This program is also available under a commercial proprietary license.
  25. * For more information, contact us at licensing@x264.com.
  26. *****************************************************************************/
  27. #include "common/common.h"
  28. #include "set.h"
  29. #include "analyse.h"
  30. #include "ratecontrol.h"
  31. #include "macroblock.h"
  32. #include "me.h"
  33. #if HAVE_INTEL_DISPATCHER
  34. #include "extras/intel_dispatcher.h"
  35. #endif
  36. //#define DEBUG_MB_TYPE
  37. #define bs_write_ue bs_write_ue_big
  38. // forward declaration needed for template usage
  39. void x264_nal_encode( x264_t *h, uint8_t *dst, x264_nal_t *nal );
  40. void x264_macroblock_cache_load_progressive( x264_t *h, int i_mb_x, int i_mb_y );
  41. static int encoder_frame_end( x264_t *h, x264_t *thread_current,
  42. x264_nal_t **pp_nal, int *pi_nal,
  43. x264_picture_t *pic_out );
  44. /****************************************************************************
  45. *
  46. ******************************* x264 libs **********************************
  47. *
  48. ****************************************************************************/
  49. static double calc_psnr( double sqe, double size )
  50. {
  51. double mse = sqe / (PIXEL_MAX*PIXEL_MAX * size);
  52. if( mse <= 0.0000000001 ) /* Max 100dB */
  53. return 100;
  54. return -10.0 * log10( mse );
  55. }
  56. static double calc_ssim_db( double ssim )
  57. {
  58. double inv_ssim = 1 - ssim;
  59. if( inv_ssim <= 0.0000000001 ) /* Max 100dB */
  60. return 100;
  61. return -10.0 * log10( inv_ssim );
  62. }
  63. static int threadpool_wait_all( x264_t *h )
  64. {
  65. for( int i = 0; i < h->param.i_threads; i++ )
  66. if( h->thread[i]->b_thread_active )
  67. {
  68. h->thread[i]->b_thread_active = 0;
  69. if( (intptr_t)x264_threadpool_wait( h->threadpool, h->thread[i] ) < 0 )
  70. return -1;
  71. }
  72. return 0;
  73. }
  74. static void frame_dump( x264_t *h )
  75. {
  76. FILE *f = x264_fopen( h->param.psz_dump_yuv, "r+b" );
  77. if( !f )
  78. return;
  79. /* Wait for the threads to finish deblocking */
  80. if( h->param.b_sliced_threads )
  81. threadpool_wait_all( h );
  82. /* Write the frame in display order */
  83. int frame_size = FRAME_SIZE( h->param.i_height * h->param.i_width * sizeof(pixel) );
  84. if( !fseek( f, (int64_t)h->fdec->i_frame * frame_size, SEEK_SET ) )
  85. {
  86. for( int p = 0; p < (CHROMA444 ? 3 : 1); p++ )
  87. for( int y = 0; y < h->param.i_height; y++ )
  88. fwrite( &h->fdec->plane[p][y*h->fdec->i_stride[p]], sizeof(pixel), h->param.i_width, f );
  89. if( CHROMA_FORMAT == CHROMA_420 || CHROMA_FORMAT == CHROMA_422 )
  90. {
  91. int cw = h->param.i_width>>1;
  92. int ch = h->param.i_height>>CHROMA_V_SHIFT;
  93. pixel *planeu = x264_malloc( 2 * (cw*ch*sizeof(pixel) + 32) );
  94. if( planeu )
  95. {
  96. pixel *planev = planeu + cw*ch + 32/sizeof(pixel);
  97. h->mc.plane_copy_deinterleave( planeu, cw, planev, cw, h->fdec->plane[1], h->fdec->i_stride[1], cw, ch );
  98. fwrite( planeu, 1, cw*ch*sizeof(pixel), f );
  99. fwrite( planev, 1, cw*ch*sizeof(pixel), f );
  100. x264_free( planeu );
  101. }
  102. }
  103. }
  104. fclose( f );
  105. }
  106. /* Fill "default" values */
  107. static void slice_header_init( x264_t *h, x264_slice_header_t *sh,
  108. x264_sps_t *sps, x264_pps_t *pps,
  109. int i_idr_pic_id, int i_frame, int i_qp )
  110. {
  111. x264_param_t *param = &h->param;
  112. /* First we fill all fields */
  113. sh->sps = sps;
  114. sh->pps = pps;
  115. sh->i_first_mb = 0;
  116. sh->i_last_mb = h->mb.i_mb_count - 1;
  117. sh->i_pps_id = pps->i_id;
  118. sh->i_frame_num = i_frame;
  119. sh->b_mbaff = PARAM_INTERLACED;
  120. sh->b_field_pic = 0; /* no field support for now */
  121. sh->b_bottom_field = 0; /* not yet used */
  122. sh->i_idr_pic_id = i_idr_pic_id;
  123. /* poc stuff, fixed later */
  124. sh->i_poc = 0;
  125. sh->i_delta_poc_bottom = 0;
  126. sh->i_delta_poc[0] = 0;
  127. sh->i_delta_poc[1] = 0;
  128. sh->i_redundant_pic_cnt = 0;
  129. h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  130. && h->param.i_bframe
  131. && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
  132. if( !h->mb.b_direct_auto_read && sh->i_type == SLICE_TYPE_B )
  133. {
  134. if( h->fref[1][0]->i_poc_l0ref0 == h->fref[0][0]->i_poc )
  135. {
  136. if( h->mb.b_direct_auto_write )
  137. sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
  138. else
  139. sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
  140. }
  141. else
  142. {
  143. h->mb.b_direct_auto_write = 0;
  144. sh->b_direct_spatial_mv_pred = 1;
  145. }
  146. }
  147. /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
  148. sh->b_num_ref_idx_override = 0;
  149. sh->i_num_ref_idx_l0_active = 1;
  150. sh->i_num_ref_idx_l1_active = 1;
  151. sh->b_ref_pic_list_reordering[0] = h->b_ref_reorder[0];
  152. sh->b_ref_pic_list_reordering[1] = h->b_ref_reorder[1];
  153. /* If the ref list isn't in the default order, construct reordering header */
  154. for( int list = 0; list < 2; list++ )
  155. {
  156. if( sh->b_ref_pic_list_reordering[list] )
  157. {
  158. int pred_frame_num = i_frame;
  159. for( int i = 0; i < h->i_ref[list]; i++ )
  160. {
  161. int diff = h->fref[list][i]->i_frame_num - pred_frame_num;
  162. sh->ref_pic_list_order[list][i].idc = ( diff > 0 );
  163. sh->ref_pic_list_order[list][i].arg = (abs(diff) - 1) & ((1 << sps->i_log2_max_frame_num) - 1);
  164. pred_frame_num = h->fref[list][i]->i_frame_num;
  165. }
  166. }
  167. }
  168. sh->i_cabac_init_idc = param->i_cabac_init_idc;
  169. sh->i_qp = SPEC_QP(i_qp);
  170. sh->i_qp_delta = sh->i_qp - pps->i_pic_init_qp;
  171. sh->b_sp_for_swidth = 0;
  172. sh->i_qs_delta = 0;
  173. int deblock_thresh = i_qp + 2 * X264_MIN(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta);
  174. /* If effective qp <= 15, deblocking would have no effect anyway */
  175. if( param->b_deblocking_filter && (h->mb.b_variable_qp || 15 < deblock_thresh ) )
  176. sh->i_disable_deblocking_filter_idc = param->b_sliced_threads ? 2 : 0;
  177. else
  178. sh->i_disable_deblocking_filter_idc = 1;
  179. sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
  180. sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
  181. }
  182. static void slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  183. {
  184. if( sh->b_mbaff )
  185. {
  186. int first_x = sh->i_first_mb % sh->sps->i_mb_width;
  187. int first_y = sh->i_first_mb / sh->sps->i_mb_width;
  188. assert( (first_y&1) == 0 );
  189. bs_write_ue( s, (2*first_x + sh->sps->i_mb_width*(first_y&~1) + (first_y&1)) >> 1 );
  190. }
  191. else
  192. bs_write_ue( s, sh->i_first_mb );
  193. bs_write_ue( s, sh->i_type + 5 ); /* same type things */
  194. bs_write_ue( s, sh->i_pps_id );
  195. bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num & ((1<<sh->sps->i_log2_max_frame_num)-1) );
  196. if( !sh->sps->b_frame_mbs_only )
  197. {
  198. bs_write1( s, sh->b_field_pic );
  199. if( sh->b_field_pic )
  200. bs_write1( s, sh->b_bottom_field );
  201. }
  202. if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
  203. bs_write_ue( s, sh->i_idr_pic_id );
  204. if( sh->sps->i_poc_type == 0 )
  205. {
  206. bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc & ((1<<sh->sps->i_log2_max_poc_lsb)-1) );
  207. if( sh->pps->b_pic_order && !sh->b_field_pic )
  208. bs_write_se( s, sh->i_delta_poc_bottom );
  209. }
  210. if( sh->pps->b_redundant_pic_cnt )
  211. bs_write_ue( s, sh->i_redundant_pic_cnt );
  212. if( sh->i_type == SLICE_TYPE_B )
  213. bs_write1( s, sh->b_direct_spatial_mv_pred );
  214. if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_B )
  215. {
  216. bs_write1( s, sh->b_num_ref_idx_override );
  217. if( sh->b_num_ref_idx_override )
  218. {
  219. bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
  220. if( sh->i_type == SLICE_TYPE_B )
  221. bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
  222. }
  223. }
  224. /* ref pic list reordering */
  225. if( sh->i_type != SLICE_TYPE_I )
  226. {
  227. bs_write1( s, sh->b_ref_pic_list_reordering[0] );
  228. if( sh->b_ref_pic_list_reordering[0] )
  229. {
  230. for( int i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  231. {
  232. bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
  233. bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
  234. }
  235. bs_write_ue( s, 3 );
  236. }
  237. }
  238. if( sh->i_type == SLICE_TYPE_B )
  239. {
  240. bs_write1( s, sh->b_ref_pic_list_reordering[1] );
  241. if( sh->b_ref_pic_list_reordering[1] )
  242. {
  243. for( int i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
  244. {
  245. bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
  246. bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
  247. }
  248. bs_write_ue( s, 3 );
  249. }
  250. }
  251. sh->b_weighted_pred = 0;
  252. if( sh->pps->b_weighted_pred && sh->i_type == SLICE_TYPE_P )
  253. {
  254. sh->b_weighted_pred = sh->weight[0][0].weightfn || sh->weight[0][1].weightfn || sh->weight[0][2].weightfn;
  255. /* pred_weight_table() */
  256. bs_write_ue( s, sh->weight[0][0].i_denom ); /* luma_log2_weight_denom */
  257. if( sh->sps->i_chroma_format_idc )
  258. bs_write_ue( s, sh->weight[0][1].i_denom ); /* chroma_log2_weight_denom */
  259. for( int i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  260. {
  261. int luma_weight_l0_flag = !!sh->weight[i][0].weightfn;
  262. bs_write1( s, luma_weight_l0_flag );
  263. if( luma_weight_l0_flag )
  264. {
  265. bs_write_se( s, sh->weight[i][0].i_scale );
  266. bs_write_se( s, sh->weight[i][0].i_offset );
  267. }
  268. if( sh->sps->i_chroma_format_idc )
  269. {
  270. int chroma_weight_l0_flag = sh->weight[i][1].weightfn || sh->weight[i][2].weightfn;
  271. bs_write1( s, chroma_weight_l0_flag );
  272. if( chroma_weight_l0_flag )
  273. {
  274. for( int j = 1; j < 3; j++ )
  275. {
  276. bs_write_se( s, sh->weight[i][j].i_scale );
  277. bs_write_se( s, sh->weight[i][j].i_offset );
  278. }
  279. }
  280. }
  281. }
  282. }
  283. else if( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B )
  284. {
  285. /* TODO */
  286. }
  287. if( i_nal_ref_idc != 0 )
  288. {
  289. if( sh->i_idr_pic_id >= 0 )
  290. {
  291. bs_write1( s, 0 ); /* no output of prior pics flag */
  292. bs_write1( s, 0 ); /* long term reference flag */
  293. }
  294. else
  295. {
  296. bs_write1( s, sh->i_mmco_command_count > 0 ); /* adaptive_ref_pic_marking_mode_flag */
  297. if( sh->i_mmco_command_count > 0 )
  298. {
  299. for( int i = 0; i < sh->i_mmco_command_count; i++ )
  300. {
  301. bs_write_ue( s, 1 ); /* mark short term ref as unused */
  302. bs_write_ue( s, sh->mmco[i].i_difference_of_pic_nums - 1 );
  303. }
  304. bs_write_ue( s, 0 ); /* end command list */
  305. }
  306. }
  307. }
  308. if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
  309. bs_write_ue( s, sh->i_cabac_init_idc );
  310. bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
  311. if( sh->pps->b_deblocking_filter_control )
  312. {
  313. bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
  314. if( sh->i_disable_deblocking_filter_idc != 1 )
  315. {
  316. bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
  317. bs_write_se( s, sh->i_beta_offset >> 1 );
  318. }
  319. }
  320. }
  321. /* If we are within a reasonable distance of the end of the memory allocated for the bitstream, */
  322. /* reallocate, adding an arbitrary amount of space. */
  323. static int bitstream_check_buffer_internal( x264_t *h, int size, int b_cabac, int i_nal )
  324. {
  325. if( (b_cabac && (h->cabac.p_end - h->cabac.p < size)) ||
  326. (h->out.bs.p_end - h->out.bs.p < size) )
  327. {
  328. int buf_size = h->out.i_bitstream + size;
  329. uint8_t *buf = x264_malloc( buf_size );
  330. if( !buf )
  331. return -1;
  332. int aligned_size = h->out.i_bitstream & ~15;
  333. h->mc.memcpy_aligned( buf, h->out.p_bitstream, aligned_size );
  334. memcpy( buf + aligned_size, h->out.p_bitstream + aligned_size, h->out.i_bitstream - aligned_size );
  335. intptr_t delta = buf - h->out.p_bitstream;
  336. h->out.bs.p_start += delta;
  337. h->out.bs.p += delta;
  338. h->out.bs.p_end = buf + buf_size;
  339. h->cabac.p_start += delta;
  340. h->cabac.p += delta;
  341. h->cabac.p_end = buf + buf_size;
  342. for( int i = 0; i <= i_nal; i++ )
  343. h->out.nal[i].p_payload += delta;
  344. x264_free( h->out.p_bitstream );
  345. h->out.p_bitstream = buf;
  346. h->out.i_bitstream = buf_size;
  347. }
  348. return 0;
  349. }
  350. static int bitstream_check_buffer( x264_t *h )
  351. {
  352. int max_row_size = (2500 << SLICE_MBAFF) * h->mb.i_mb_width;
  353. return bitstream_check_buffer_internal( h, max_row_size, h->param.b_cabac, h->out.i_nal );
  354. }
  355. static int bitstream_check_buffer_filler( x264_t *h, int filler )
  356. {
  357. filler += 32; // add padding for safety
  358. return bitstream_check_buffer_internal( h, filler, 0, -1 );
  359. }
  360. #if HAVE_THREAD
  361. static void encoder_thread_init( x264_t *h )
  362. {
  363. if( h->param.i_sync_lookahead )
  364. x264_lower_thread_priority( 10 );
  365. }
  366. #endif
  367. /****************************************************************************
  368. *
  369. ****************************************************************************
  370. ****************************** External API*********************************
  371. ****************************************************************************
  372. *
  373. ****************************************************************************/
  374. static int validate_parameters( x264_t *h, int b_open )
  375. {
  376. if( !h->param.pf_log )
  377. {
  378. x264_log_internal( X264_LOG_ERROR, "pf_log not set! did you forget to call x264_param_default?\n" );
  379. return -1;
  380. }
  381. #if HAVE_MMX
  382. if( b_open )
  383. {
  384. int cpuflags = x264_cpu_detect();
  385. int fail = 0;
  386. #ifdef __SSE__
  387. if( !(cpuflags & X264_CPU_SSE) )
  388. {
  389. x264_log( h, X264_LOG_ERROR, "your cpu does not support SSE1, but x264 was compiled with asm\n");
  390. fail = 1;
  391. }
  392. #else
  393. if( !(cpuflags & X264_CPU_MMX2) )
  394. {
  395. x264_log( h, X264_LOG_ERROR, "your cpu does not support MMXEXT, but x264 was compiled with asm\n");
  396. fail = 1;
  397. }
  398. #endif
  399. if( fail )
  400. {
  401. x264_log( h, X264_LOG_ERROR, "to run x264, recompile without asm (configure --disable-asm)\n");
  402. return -1;
  403. }
  404. }
  405. #endif
  406. #if HAVE_INTERLACED
  407. h->param.b_interlaced = !!PARAM_INTERLACED;
  408. #else
  409. if( h->param.b_interlaced )
  410. {
  411. x264_log( h, X264_LOG_ERROR, "not compiled with interlaced support\n" );
  412. return -1;
  413. }
  414. #endif
  415. if( h->param.i_width <= 0 || h->param.i_height <= 0 )
  416. {
  417. x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
  418. h->param.i_width, h->param.i_height );
  419. return -1;
  420. }
  421. int i_csp = h->param.i_csp & X264_CSP_MASK;
  422. #if X264_CHROMA_FORMAT
  423. if( CHROMA_FORMAT != CHROMA_400 && i_csp == X264_CSP_I400 )
  424. {
  425. x264_log( h, X264_LOG_ERROR, "not compiled with 4:0:0 support\n" );
  426. return -1;
  427. }
  428. else if( CHROMA_FORMAT != CHROMA_420 && i_csp >= X264_CSP_I420 && i_csp < X264_CSP_I422 )
  429. {
  430. x264_log( h, X264_LOG_ERROR, "not compiled with 4:2:0 support\n" );
  431. return -1;
  432. }
  433. else if( CHROMA_FORMAT != CHROMA_422 && i_csp >= X264_CSP_I422 && i_csp < X264_CSP_I444 )
  434. {
  435. x264_log( h, X264_LOG_ERROR, "not compiled with 4:2:2 support\n" );
  436. return -1;
  437. }
  438. else if( CHROMA_FORMAT != CHROMA_444 && i_csp >= X264_CSP_I444 && i_csp <= X264_CSP_RGB )
  439. {
  440. x264_log( h, X264_LOG_ERROR, "not compiled with 4:4:4 support\n" );
  441. return -1;
  442. }
  443. #endif
  444. if( i_csp <= X264_CSP_NONE || i_csp >= X264_CSP_MAX )
  445. {
  446. x264_log( h, X264_LOG_ERROR, "invalid CSP (only I400/I420/YV12/NV12/NV21/I422/YV16/NV16/YUYV/UYVY/"
  447. "I444/YV24/BGR/BGRA/RGB supported)\n" );
  448. return -1;
  449. }
  450. int w_mod = 1;
  451. int h_mod = 1 << (PARAM_INTERLACED || h->param.b_fake_interlaced);
  452. if( i_csp == X264_CSP_I400 )
  453. {
  454. h->param.analyse.i_chroma_qp_offset = 0;
  455. h->param.analyse.b_chroma_me = 0;
  456. h->param.vui.i_colmatrix = 2; /* undefined */
  457. }
  458. else if( i_csp < X264_CSP_I444 )
  459. {
  460. w_mod = 2;
  461. if( i_csp < X264_CSP_I422 )
  462. h_mod *= 2;
  463. }
  464. if( h->param.i_width % w_mod )
  465. {
  466. x264_log( h, X264_LOG_ERROR, "width not divisible by %d (%dx%d)\n",
  467. w_mod, h->param.i_width, h->param.i_height );
  468. return -1;
  469. }
  470. if( h->param.i_height % h_mod )
  471. {
  472. x264_log( h, X264_LOG_ERROR, "height not divisible by %d (%dx%d)\n",
  473. h_mod, h->param.i_width, h->param.i_height );
  474. return -1;
  475. }
  476. if( h->param.crop_rect.i_left >= h->param.i_width ||
  477. h->param.crop_rect.i_right >= h->param.i_width ||
  478. h->param.crop_rect.i_top >= h->param.i_height ||
  479. h->param.crop_rect.i_bottom >= h->param.i_height ||
  480. h->param.crop_rect.i_left + h->param.crop_rect.i_right >= h->param.i_width ||
  481. h->param.crop_rect.i_top + h->param.crop_rect.i_bottom >= h->param.i_height )
  482. {
  483. x264_log( h, X264_LOG_ERROR, "invalid crop-rect %u,%u,%u,%u\n", h->param.crop_rect.i_left,
  484. h->param.crop_rect.i_top, h->param.crop_rect.i_right, h->param.crop_rect.i_bottom );
  485. return -1;
  486. }
  487. if( h->param.crop_rect.i_left % w_mod || h->param.crop_rect.i_right % w_mod ||
  488. h->param.crop_rect.i_top % h_mod || h->param.crop_rect.i_bottom % h_mod )
  489. {
  490. x264_log( h, X264_LOG_ERROR, "crop-rect %u,%u,%u,%u not divisible by %dx%d\n", h->param.crop_rect.i_left,
  491. h->param.crop_rect.i_top, h->param.crop_rect.i_right, h->param.crop_rect.i_bottom, w_mod, h_mod );
  492. return -1;
  493. }
  494. if( h->param.vui.i_sar_width <= 0 || h->param.vui.i_sar_height <= 0 )
  495. {
  496. h->param.vui.i_sar_width = 0;
  497. h->param.vui.i_sar_height = 0;
  498. }
  499. if( h->param.i_threads == X264_THREADS_AUTO )
  500. {
  501. h->param.i_threads = x264_cpu_num_processors() * (h->param.b_sliced_threads?2:3)/2;
  502. /* Avoid too many threads as they don't improve performance and
  503. * complicate VBV. Capped at an arbitrary 2 rows per thread. */
  504. int max_threads = X264_MAX( 1, (h->param.i_height+15)/16 / 2 );
  505. h->param.i_threads = X264_MIN( h->param.i_threads, max_threads );
  506. }
  507. int max_sliced_threads = X264_MAX( 1, (h->param.i_height+15)/16 / 4 );
  508. if( h->param.i_threads > 1 )
  509. {
  510. #if !HAVE_THREAD
  511. x264_log( h, X264_LOG_WARNING, "not compiled with thread support!\n");
  512. h->param.i_threads = 1;
  513. #endif
  514. /* Avoid absurdly small thread slices as they can reduce performance
  515. * and VBV compliance. Capped at an arbitrary 4 rows per thread. */
  516. if( h->param.b_sliced_threads )
  517. h->param.i_threads = X264_MIN( h->param.i_threads, max_sliced_threads );
  518. }
  519. h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_THREAD_MAX );
  520. if( h->param.i_threads == 1 )
  521. {
  522. h->param.b_sliced_threads = 0;
  523. h->param.i_lookahead_threads = 1;
  524. }
  525. h->i_thread_frames = h->param.b_sliced_threads ? 1 : h->param.i_threads;
  526. if( h->i_thread_frames > 1 )
  527. h->param.nalu_process = NULL;
  528. if( h->param.b_opencl )
  529. {
  530. #if !HAVE_OPENCL
  531. x264_log( h, X264_LOG_WARNING, "OpenCL: not compiled with OpenCL support, disabling\n" );
  532. h->param.b_opencl = 0;
  533. #elif BIT_DEPTH > 8
  534. x264_log( h, X264_LOG_WARNING, "OpenCL lookahead does not support high bit depth, disabling opencl\n" );
  535. h->param.b_opencl = 0;
  536. #else
  537. if( h->param.i_width < 32 || h->param.i_height < 32 )
  538. {
  539. x264_log( h, X264_LOG_WARNING, "OpenCL: frame size is too small, disabling opencl\n" );
  540. h->param.b_opencl = 0;
  541. }
  542. #endif
  543. if( h->param.opencl_device_id && h->param.i_opencl_device )
  544. {
  545. x264_log( h, X264_LOG_WARNING, "OpenCL: device id and device skip count configured; dropping skip\n" );
  546. h->param.i_opencl_device = 0;
  547. }
  548. }
  549. h->param.i_keyint_max = x264_clip3( h->param.i_keyint_max, 1, X264_KEYINT_MAX_INFINITE );
  550. if( h->param.i_keyint_max == 1 )
  551. {
  552. h->param.b_intra_refresh = 0;
  553. h->param.analyse.i_weighted_pred = 0;
  554. h->param.i_frame_reference = 1;
  555. h->param.i_dpb_size = 1;
  556. }
  557. if( h->param.i_frame_packing < -1 || h->param.i_frame_packing > 7 )
  558. {
  559. x264_log( h, X264_LOG_WARNING, "ignoring unknown frame packing value\n" );
  560. h->param.i_frame_packing = -1;
  561. }
  562. if( h->param.i_frame_packing == 7 &&
  563. ((h->param.i_width - h->param.crop_rect.i_left - h->param.crop_rect.i_right) % 3 ||
  564. (h->param.i_height - h->param.crop_rect.i_top - h->param.crop_rect.i_bottom) % 3) )
  565. {
  566. x264_log( h, X264_LOG_ERROR, "cropped resolution %dx%d not compatible with tile format frame packing\n",
  567. h->param.i_width - h->param.crop_rect.i_left - h->param.crop_rect.i_right,
  568. h->param.i_height - h->param.crop_rect.i_top - h->param.crop_rect.i_bottom );
  569. return -1;
  570. }
  571. /* Detect default ffmpeg settings and terminate with an error. */
  572. if( b_open )
  573. {
  574. int score = 0;
  575. score += h->param.analyse.i_me_range == 0;
  576. score += h->param.rc.i_qp_step == 3;
  577. score += h->param.i_keyint_max == 12;
  578. score += h->param.rc.i_qp_min == 2;
  579. score += h->param.rc.i_qp_max == 31;
  580. score += h->param.rc.f_qcompress == 0.5;
  581. score += fabs(h->param.rc.f_ip_factor - 1.25) < 0.01;
  582. score += fabs(h->param.rc.f_pb_factor - 1.25) < 0.01;
  583. score += h->param.analyse.inter == 0 && h->param.analyse.i_subpel_refine == 8;
  584. if( score >= 5 )
  585. {
  586. x264_log( h, X264_LOG_ERROR, "broken ffmpeg default settings detected\n" );
  587. x264_log( h, X264_LOG_ERROR, "use an encoding preset (e.g. -vpre medium)\n" );
  588. x264_log( h, X264_LOG_ERROR, "preset usage: -vpre <speed> -vpre <profile>\n" );
  589. x264_log( h, X264_LOG_ERROR, "speed presets are listed in x264 --help\n" );
  590. x264_log( h, X264_LOG_ERROR, "profile is optional; x264 defaults to high\n" );
  591. return -1;
  592. }
  593. }
  594. if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
  595. {
  596. x264_log( h, X264_LOG_ERROR, "no ratecontrol method specified\n" );
  597. return -1;
  598. }
  599. if( PARAM_INTERLACED )
  600. h->param.b_pic_struct = 1;
  601. if( h->param.i_avcintra_class )
  602. {
  603. if( BIT_DEPTH != 10 )
  604. {
  605. x264_log( h, X264_LOG_ERROR, "%2d-bit AVC-Intra is not widely compatible\n", BIT_DEPTH );
  606. x264_log( h, X264_LOG_ERROR, "10-bit x264 is required to encode AVC-Intra\n" );
  607. return -1;
  608. }
  609. int type = h->param.i_avcintra_class == 200 ? 2 :
  610. h->param.i_avcintra_class == 100 ? 1 :
  611. h->param.i_avcintra_class == 50 ? 0 : -1;
  612. if( type < 0 )
  613. {
  614. x264_log( h, X264_LOG_ERROR, "Invalid AVC-Intra class\n" );
  615. return -1;
  616. }
  617. /* [50/100/200][res][fps] */
  618. static const struct
  619. {
  620. uint16_t fps_num;
  621. uint16_t fps_den;
  622. uint8_t interlaced;
  623. uint16_t frame_size;
  624. const uint8_t *cqm_4ic;
  625. const uint8_t *cqm_8iy;
  626. } avcintra_lut[3][2][7] =
  627. {
  628. {{{ 60000, 1001, 0, 912, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  629. { 50, 1, 0, 1100, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  630. { 30000, 1001, 0, 912, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  631. { 25, 1, 0, 1100, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  632. { 24000, 1001, 0, 912, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy }},
  633. {{ 30000, 1001, 1, 1820, x264_cqm_avci50_4ic, x264_cqm_avci50_1080i_8iy },
  634. { 25, 1, 1, 2196, x264_cqm_avci50_4ic, x264_cqm_avci50_1080i_8iy },
  635. { 60000, 1001, 0, 1820, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  636. { 30000, 1001, 0, 1820, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  637. { 50, 1, 0, 2196, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  638. { 25, 1, 0, 2196, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy },
  639. { 24000, 1001, 0, 1820, x264_cqm_avci50_4ic, x264_cqm_avci50_p_8iy }}},
  640. {{{ 60000, 1001, 0, 1848, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy },
  641. { 50, 1, 0, 2224, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy },
  642. { 30000, 1001, 0, 1848, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy },
  643. { 25, 1, 0, 2224, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy },
  644. { 24000, 1001, 0, 1848, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy }},
  645. {{ 30000, 1001, 1, 3692, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080i_8iy },
  646. { 25, 1, 1, 4444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080i_8iy },
  647. { 60000, 1001, 0, 3692, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  648. { 30000, 1001, 0, 3692, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  649. { 50, 1, 0, 4444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  650. { 25, 1, 0, 4444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  651. { 24000, 1001, 0, 3692, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy }}},
  652. {{{ 60000, 1001, 0, 3724, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy },
  653. { 50, 1, 0, 4472, x264_cqm_avci100_720p_4ic, x264_cqm_avci100_720p_8iy }},
  654. {{ 30000, 1001, 1, 7444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080i_8iy },
  655. { 25, 1, 1, 8940, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080i_8iy },
  656. { 60000, 1001, 0, 7444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  657. { 30000, 1001, 0, 7444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  658. { 50, 1, 0, 8940, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  659. { 25, 1, 0, 8940, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy },
  660. { 24000, 1001, 0, 7444, x264_cqm_avci100_1080_4ic, x264_cqm_avci100_1080p_8iy }}}
  661. };
  662. int res = -1;
  663. if( i_csp >= X264_CSP_I420 && i_csp < X264_CSP_I422 && !type )
  664. {
  665. if( h->param.i_width == 1440 && h->param.i_height == 1080 ) res = 1;
  666. else if( h->param.i_width == 960 && h->param.i_height == 720 ) res = 0;
  667. }
  668. else if( i_csp >= X264_CSP_I422 && i_csp < X264_CSP_I444 && type )
  669. {
  670. if( h->param.i_width == 1920 && h->param.i_height == 1080 ) res = 1;
  671. else if( h->param.i_width == 1280 && h->param.i_height == 720 ) res = 0;
  672. }
  673. else
  674. {
  675. x264_log( h, X264_LOG_ERROR, "Invalid colorspace for AVC-Intra %d\n", h->param.i_avcintra_class );
  676. return -1;
  677. }
  678. if( res < 0 )
  679. {
  680. x264_log( h, X264_LOG_ERROR, "Resolution %dx%d invalid for AVC-Intra %d\n",
  681. h->param.i_width, h->param.i_height, h->param.i_avcintra_class );
  682. return -1;
  683. }
  684. if( h->param.nalu_process )
  685. {
  686. x264_log( h, X264_LOG_ERROR, "nalu_process is not supported in AVC-Intra mode\n" );
  687. return -1;
  688. }
  689. if( !h->param.b_repeat_headers )
  690. {
  691. x264_log( h, X264_LOG_ERROR, "Separate headers not supported in AVC-Intra mode\n" );
  692. return -1;
  693. }
  694. int i;
  695. uint32_t fps_num = h->param.i_fps_num, fps_den = h->param.i_fps_den;
  696. x264_reduce_fraction( &fps_num, &fps_den );
  697. for( i = 0; i < 7; i++ )
  698. {
  699. if( avcintra_lut[type][res][i].fps_num == fps_num &&
  700. avcintra_lut[type][res][i].fps_den == fps_den &&
  701. avcintra_lut[type][res][i].interlaced == PARAM_INTERLACED )
  702. {
  703. break;
  704. }
  705. }
  706. if( i == 7 )
  707. {
  708. x264_log( h, X264_LOG_ERROR, "FPS %d/%d%c not compatible with AVC-Intra\n",
  709. h->param.i_fps_num, h->param.i_fps_den, PARAM_INTERLACED ? 'i' : 'p' );
  710. return -1;
  711. }
  712. h->param.i_keyint_max = 1;
  713. h->param.b_intra_refresh = 0;
  714. h->param.analyse.i_weighted_pred = 0;
  715. h->param.i_frame_reference = 1;
  716. h->param.i_dpb_size = 1;
  717. h->param.b_bluray_compat = 0;
  718. h->param.b_vfr_input = 0;
  719. h->param.b_aud = 1;
  720. h->param.vui.i_chroma_loc = 0;
  721. h->param.i_nal_hrd = X264_NAL_HRD_NONE;
  722. h->param.b_deblocking_filter = 0;
  723. h->param.b_stitchable = 1;
  724. h->param.b_pic_struct = 0;
  725. h->param.analyse.b_transform_8x8 = 1;
  726. h->param.analyse.intra = X264_ANALYSE_I8x8;
  727. h->param.analyse.i_chroma_qp_offset = res && type ? 3 : 4;
  728. h->param.b_cabac = !type;
  729. h->param.rc.i_vbv_buffer_size = avcintra_lut[type][res][i].frame_size;
  730. h->param.rc.i_vbv_max_bitrate =
  731. h->param.rc.i_bitrate = h->param.rc.i_vbv_buffer_size * fps_num / fps_den;
  732. h->param.rc.i_rc_method = X264_RC_ABR;
  733. h->param.rc.f_vbv_buffer_init = 1.0;
  734. h->param.rc.b_filler = 1;
  735. h->param.i_cqm_preset = X264_CQM_CUSTOM;
  736. memcpy( h->param.cqm_4iy, x264_cqm_jvt4i, sizeof(h->param.cqm_4iy) );
  737. memcpy( h->param.cqm_4ic, avcintra_lut[type][res][i].cqm_4ic, sizeof(h->param.cqm_4ic) );
  738. memcpy( h->param.cqm_8iy, avcintra_lut[type][res][i].cqm_8iy, sizeof(h->param.cqm_8iy) );
  739. /* Sony XAVC flavor much more simple */
  740. if( h->param.i_avcintra_flavor == X264_AVCINTRA_FLAVOR_SONY )
  741. {
  742. h->param.i_slice_count = 8;
  743. if( h->param.b_sliced_threads )
  744. h->param.i_threads = h->param.i_slice_count;
  745. /* Sony XAVC unlike AVC-Intra doesn't seem to have a QP floor */
  746. }
  747. else
  748. {
  749. /* Need exactly 10 slices of equal MB count... why? $deity knows... */
  750. h->param.i_slice_max_mbs = ((h->param.i_width + 15) / 16) * ((h->param.i_height + 15) / 16) / 10;
  751. h->param.i_slice_max_size = 0;
  752. /* The slice structure only allows a maximum of 2 threads for 1080i/p
  753. * and 1 or 5 threads for 720p */
  754. if( h->param.b_sliced_threads )
  755. {
  756. if( res )
  757. h->param.i_threads = X264_MIN( 2, h->param.i_threads );
  758. else
  759. {
  760. h->param.i_threads = X264_MIN( 5, h->param.i_threads );
  761. if( h->param.i_threads < 5 )
  762. h->param.i_threads = 1;
  763. }
  764. }
  765. /* Official encoder doesn't appear to go under 13
  766. * and Avid cannot handle negative QPs */
  767. h->param.rc.i_qp_min = X264_MAX( h->param.rc.i_qp_min, QP_BD_OFFSET + 1 );
  768. }
  769. if( type )
  770. h->param.vui.i_sar_width = h->param.vui.i_sar_height = 1;
  771. else
  772. {
  773. h->param.vui.i_sar_width = 4;
  774. h->param.vui.i_sar_height = 3;
  775. }
  776. }
  777. h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, -QP_BD_OFFSET, 51 );
  778. h->param.rc.f_rf_constant_max = x264_clip3f( h->param.rc.f_rf_constant_max, -QP_BD_OFFSET, 51 );
  779. h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, -1, QP_MAX );
  780. h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 0, 11 );
  781. h->param.rc.f_ip_factor = X264_MAX( h->param.rc.f_ip_factor, 0.01f );
  782. h->param.rc.f_pb_factor = X264_MAX( h->param.rc.f_pb_factor, 0.01f );
  783. if( h->param.rc.i_rc_method == X264_RC_CRF )
  784. {
  785. h->param.rc.i_qp_constant = h->param.rc.f_rf_constant + QP_BD_OFFSET;
  786. h->param.rc.i_bitrate = 0;
  787. }
  788. if( b_open && (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
  789. && h->param.rc.i_qp_constant == 0 )
  790. {
  791. h->mb.b_lossless = 1;
  792. h->param.i_cqm_preset = X264_CQM_FLAT;
  793. h->param.psz_cqm_file = NULL;
  794. h->param.rc.i_rc_method = X264_RC_CQP;
  795. h->param.rc.f_ip_factor = 1;
  796. h->param.rc.f_pb_factor = 1;
  797. h->param.analyse.b_psnr = 0;
  798. h->param.analyse.b_ssim = 0;
  799. h->param.analyse.i_chroma_qp_offset = 0;
  800. h->param.analyse.i_trellis = 0;
  801. h->param.analyse.b_fast_pskip = 0;
  802. h->param.analyse.i_noise_reduction = 0;
  803. h->param.analyse.b_psy = 0;
  804. h->param.i_bframe = 0;
  805. /* 8x8dct is not useful without RD in CAVLC lossless */
  806. if( !h->param.b_cabac && h->param.analyse.i_subpel_refine < 6 )
  807. h->param.analyse.b_transform_8x8 = 0;
  808. h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  809. h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  810. }
  811. if( i_csp >= X264_CSP_I444 && h->param.b_cabac )
  812. {
  813. /* Disable 8x8dct during 4:4:4+CABAC encoding for compatibility with libavcodec */
  814. h->param.analyse.b_transform_8x8 = 0;
  815. }
  816. if( h->param.rc.i_rc_method == X264_RC_CQP )
  817. {
  818. float qp_p = h->param.rc.i_qp_constant;
  819. float qp_i = qp_p - 6*log2f( h->param.rc.f_ip_factor );
  820. float qp_b = qp_p + 6*log2f( h->param.rc.f_pb_factor );
  821. if( qp_p < 0 )
  822. {
  823. x264_log( h, X264_LOG_ERROR, "qp not specified\n" );
  824. return -1;
  825. }
  826. h->param.rc.i_qp_min = x264_clip3( (int)(X264_MIN3( qp_p, qp_i, qp_b )), 0, QP_MAX );
  827. h->param.rc.i_qp_max = x264_clip3( (int)(X264_MAX3( qp_p, qp_i, qp_b ) + .999), 0, QP_MAX );
  828. h->param.rc.i_aq_mode = 0;
  829. h->param.rc.b_mb_tree = 0;
  830. h->param.rc.i_bitrate = 0;
  831. }
  832. h->param.rc.i_qp_max = x264_clip3( h->param.rc.i_qp_max, 0, QP_MAX );
  833. h->param.rc.i_qp_min = x264_clip3( h->param.rc.i_qp_min, 0, h->param.rc.i_qp_max );
  834. h->param.rc.i_qp_step = x264_clip3( h->param.rc.i_qp_step, 2, QP_MAX );
  835. h->param.rc.i_bitrate = x264_clip3( h->param.rc.i_bitrate, 0, 2000000 );
  836. if( h->param.rc.i_rc_method == X264_RC_ABR && !h->param.rc.i_bitrate )
  837. {
  838. x264_log( h, X264_LOG_ERROR, "bitrate not specified\n" );
  839. return -1;
  840. }
  841. h->param.rc.i_vbv_buffer_size = x264_clip3( h->param.rc.i_vbv_buffer_size, 0, 2000000 );
  842. h->param.rc.i_vbv_max_bitrate = x264_clip3( h->param.rc.i_vbv_max_bitrate, 0, 2000000 );
  843. h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init, 0, 2000000 );
  844. if( h->param.rc.i_vbv_buffer_size )
  845. {
  846. if( h->param.rc.i_rc_method == X264_RC_CQP )
  847. {
  848. x264_log( h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n" );
  849. h->param.rc.i_vbv_max_bitrate = 0;
  850. h->param.rc.i_vbv_buffer_size = 0;
  851. }
  852. else if( h->param.rc.i_vbv_max_bitrate == 0 )
  853. {
  854. if( h->param.rc.i_rc_method == X264_RC_ABR )
  855. {
  856. x264_log( h, X264_LOG_WARNING, "VBV maxrate unspecified, assuming CBR\n" );
  857. h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate;
  858. }
  859. else
  860. {
  861. x264_log( h, X264_LOG_WARNING, "VBV bufsize set but maxrate unspecified, ignored\n" );
  862. h->param.rc.i_vbv_buffer_size = 0;
  863. }
  864. }
  865. else if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate &&
  866. h->param.rc.i_rc_method == X264_RC_ABR )
  867. {
  868. x264_log( h, X264_LOG_WARNING, "max bitrate less than average bitrate, assuming CBR\n" );
  869. h->param.rc.i_bitrate = h->param.rc.i_vbv_max_bitrate;
  870. }
  871. }
  872. else if( h->param.rc.i_vbv_max_bitrate )
  873. {
  874. x264_log( h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize, ignored\n" );
  875. h->param.rc.i_vbv_max_bitrate = 0;
  876. }
  877. h->param.i_slice_max_size = X264_MAX( h->param.i_slice_max_size, 0 );
  878. h->param.i_slice_max_mbs = X264_MAX( h->param.i_slice_max_mbs, 0 );
  879. h->param.i_slice_min_mbs = X264_MAX( h->param.i_slice_min_mbs, 0 );
  880. if( h->param.i_slice_max_mbs )
  881. h->param.i_slice_min_mbs = X264_MIN( h->param.i_slice_min_mbs, h->param.i_slice_max_mbs/2 );
  882. else if( !h->param.i_slice_max_size )
  883. h->param.i_slice_min_mbs = 0;
  884. if( PARAM_INTERLACED && h->param.i_slice_min_mbs )
  885. {
  886. x264_log( h, X264_LOG_WARNING, "interlace + slice-min-mbs is not implemented\n" );
  887. h->param.i_slice_min_mbs = 0;
  888. }
  889. int mb_width = (h->param.i_width+15)/16;
  890. if( h->param.i_slice_min_mbs > mb_width )
  891. {
  892. x264_log( h, X264_LOG_WARNING, "slice-min-mbs > row mb size (%d) not implemented\n", mb_width );
  893. h->param.i_slice_min_mbs = mb_width;
  894. }
  895. int max_slices = (h->param.i_height+((16<<PARAM_INTERLACED)-1))/(16<<PARAM_INTERLACED);
  896. if( h->param.b_sliced_threads )
  897. h->param.i_slice_count = x264_clip3( h->param.i_threads, 0, max_slices );
  898. else
  899. {
  900. h->param.i_slice_count = x264_clip3( h->param.i_slice_count, 0, max_slices );
  901. if( h->param.i_slice_max_mbs || h->param.i_slice_max_size )
  902. h->param.i_slice_count = 0;
  903. }
  904. if( h->param.i_slice_count_max > 0 )
  905. h->param.i_slice_count_max = X264_MAX( h->param.i_slice_count, h->param.i_slice_count_max );
  906. if( h->param.b_bluray_compat )
  907. {
  908. h->param.i_bframe_pyramid = X264_MIN( X264_B_PYRAMID_STRICT, h->param.i_bframe_pyramid );
  909. h->param.i_bframe = X264_MIN( h->param.i_bframe, 3 );
  910. h->param.b_aud = 1;
  911. h->param.i_nal_hrd = X264_MAX( h->param.i_nal_hrd, X264_NAL_HRD_VBR );
  912. h->param.i_slice_max_size = 0;
  913. h->param.i_slice_max_mbs = 0;
  914. h->param.b_intra_refresh = 0;
  915. h->param.i_frame_reference = X264_MIN( h->param.i_frame_reference, 6 );
  916. h->param.i_dpb_size = X264_MIN( h->param.i_dpb_size, 6 );
  917. /* Don't use I-frames, because Blu-ray treats them the same as IDR. */
  918. h->param.i_keyint_min = 1;
  919. /* Due to the proliferation of broken players that don't handle dupes properly. */
  920. h->param.analyse.i_weighted_pred = X264_MIN( h->param.analyse.i_weighted_pred, X264_WEIGHTP_SIMPLE );
  921. if( h->param.b_fake_interlaced )
  922. h->param.b_pic_struct = 1;
  923. }
  924. h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, X264_REF_MAX );
  925. h->param.i_dpb_size = x264_clip3( h->param.i_dpb_size, 1, X264_REF_MAX );
  926. if( h->param.i_scenecut_threshold < 0 )
  927. h->param.i_scenecut_threshold = 0;
  928. h->param.analyse.i_direct_mv_pred = x264_clip3( h->param.analyse.i_direct_mv_pred, X264_DIRECT_PRED_NONE, X264_DIRECT_PRED_AUTO );
  929. if( !h->param.analyse.i_subpel_refine && h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
  930. {
  931. x264_log( h, X264_LOG_WARNING, "subme=0 + direct=temporal is not supported\n" );
  932. h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
  933. }
  934. h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_MIN( X264_BFRAME_MAX, h->param.i_keyint_max-1 ) );
  935. h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
  936. if( h->param.i_bframe <= 1 )
  937. h->param.i_bframe_pyramid = X264_B_PYRAMID_NONE;
  938. h->param.i_bframe_pyramid = x264_clip3( h->param.i_bframe_pyramid, X264_B_PYRAMID_NONE, X264_B_PYRAMID_NORMAL );
  939. h->param.i_bframe_adaptive = x264_clip3( h->param.i_bframe_adaptive, X264_B_ADAPT_NONE, X264_B_ADAPT_TRELLIS );
  940. if( !h->param.i_bframe )
  941. {
  942. h->param.i_bframe_adaptive = X264_B_ADAPT_NONE;
  943. h->param.analyse.i_direct_mv_pred = 0;
  944. h->param.analyse.b_weighted_bipred = 0;
  945. h->param.b_open_gop = 0;
  946. }
  947. if( h->param.b_intra_refresh && h->param.i_bframe_pyramid == X264_B_PYRAMID_NORMAL )
  948. {
  949. x264_log( h, X264_LOG_WARNING, "b-pyramid normal + intra-refresh is not supported\n" );
  950. h->param.i_bframe_pyramid = X264_B_PYRAMID_STRICT;
  951. }
  952. if( h->param.b_intra_refresh && (h->param.i_frame_reference > 1 || h->param.i_dpb_size > 1) )
  953. {
  954. x264_log( h, X264_LOG_WARNING, "ref > 1 + intra-refresh is not supported\n" );
  955. h->param.i_frame_reference = 1;
  956. h->param.i_dpb_size = 1;
  957. }
  958. if( h->param.b_intra_refresh && h->param.b_open_gop )
  959. {
  960. x264_log( h, X264_LOG_WARNING, "intra-refresh is not compatible with open-gop\n" );
  961. h->param.b_open_gop = 0;
  962. }
  963. if( !h->param.i_fps_num || !h->param.i_fps_den )
  964. {
  965. h->param.i_fps_num = 25;
  966. h->param.i_fps_den = 1;
  967. }
  968. float fps = (float)h->param.i_fps_num / h->param.i_fps_den;
  969. if( h->param.i_keyint_min == X264_KEYINT_MIN_AUTO )
  970. h->param.i_keyint_min = X264_MIN( h->param.i_keyint_max / 10, (int)fps );
  971. h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
  972. h->param.rc.i_lookahead = x264_clip3( h->param.rc.i_lookahead, 0, X264_LOOKAHEAD_MAX );
  973. {
  974. int maxrate = X264_MAX( h->param.rc.i_vbv_max_bitrate, h->param.rc.i_bitrate );
  975. float bufsize = maxrate ? (float)h->param.rc.i_vbv_buffer_size / maxrate : 0;
  976. h->param.rc.i_lookahead = X264_MIN( h->param.rc.i_lookahead, X264_MAX( h->param.i_keyint_max, bufsize*fps ) );
  977. }
  978. if( !h->param.i_timebase_num || !h->param.i_timebase_den || !(h->param.b_vfr_input || h->param.b_pulldown) )
  979. {
  980. h->param.i_timebase_num = h->param.i_fps_den;
  981. h->param.i_timebase_den = h->param.i_fps_num;
  982. }
  983. h->param.rc.f_qcompress = x264_clip3f( h->param.rc.f_qcompress, 0.0, 1.0 );
  984. if( h->param.i_keyint_max == 1 || h->param.rc.f_qcompress == 1 )
  985. h->param.rc.b_mb_tree = 0;
  986. if( (!h->param.b_intra_refresh && h->param.i_keyint_max != X264_KEYINT_MAX_INFINITE) &&
  987. !h->param.rc.i_lookahead && h->param.rc.b_mb_tree )
  988. {
  989. x264_log( h, X264_LOG_WARNING, "lookaheadless mb-tree requires intra refresh or infinite keyint\n" );
  990. h->param.rc.b_mb_tree = 0;
  991. }
  992. if( b_open && h->param.rc.b_stat_read )
  993. h->param.rc.i_lookahead = 0;
  994. #if HAVE_THREAD
  995. if( h->param.i_sync_lookahead < 0 )
  996. h->param.i_sync_lookahead = h->param.i_bframe + 1;
  997. h->param.i_sync_lookahead = X264_MIN( h->param.i_sync_lookahead, X264_LOOKAHEAD_MAX );
  998. if( h->param.rc.b_stat_read || h->i_thread_frames == 1 )
  999. h->param.i_sync_lookahead = 0;
  1000. #else
  1001. h->param.i_sync_lookahead = 0;
  1002. #endif
  1003. h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
  1004. h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
  1005. h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
  1006. h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
  1007. h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
  1008. if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
  1009. h->param.i_cqm_preset = X264_CQM_FLAT;
  1010. if( h->param.analyse.i_me_method < X264_ME_DIA ||
  1011. h->param.analyse.i_me_method > X264_ME_TESA )
  1012. h->param.analyse.i_me_method = X264_ME_HEX;
  1013. h->param.analyse.i_me_range = x264_clip3( h->param.analyse.i_me_range, 4, 1024 );
  1014. if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
  1015. h->param.analyse.i_me_range = 16;
  1016. if( h->param.analyse.i_me_method == X264_ME_TESA &&
  1017. (h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1) )
  1018. h->param.analyse.i_me_method = X264_ME_ESA;
  1019. h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
  1020. h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
  1021. X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  1022. h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  1023. if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
  1024. h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  1025. if( !h->param.analyse.b_transform_8x8 )
  1026. {
  1027. h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  1028. h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  1029. }
  1030. h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
  1031. h->param.rc.i_aq_mode = x264_clip3( h->param.rc.i_aq_mode, 0, 3 );
  1032. h->param.rc.f_aq_strength = x264_clip3f( h->param.rc.f_aq_strength, 0, 3 );
  1033. if( h->param.rc.f_aq_strength == 0 )
  1034. h->param.rc.i_aq_mode = 0;
  1035. if( h->param.i_log_level < X264_LOG_INFO )
  1036. {
  1037. h->param.analyse.b_psnr = 0;
  1038. h->param.analyse.b_ssim = 0;
  1039. }
  1040. /* Warn users trying to measure PSNR/SSIM with psy opts on. */
  1041. if( b_open && (h->param.analyse.b_psnr || h->param.analyse.b_ssim) )
  1042. {
  1043. char *s = NULL;
  1044. if( h->param.analyse.b_psy )
  1045. {
  1046. s = h->param.analyse.b_psnr ? "psnr" : "ssim";
  1047. x264_log( h, X264_LOG_WARNING, "--%s used with psy on: results will be invalid!\n", s );
  1048. }
  1049. else if( !h->param.rc.i_aq_mode && h->param.analyse.b_ssim )
  1050. {
  1051. x264_log( h, X264_LOG_WARNING, "--ssim used with AQ off: results will be invalid!\n" );
  1052. s = "ssim";
  1053. }
  1054. else if( h->param.rc.i_aq_mode && h->param.analyse.b_psnr )
  1055. {
  1056. x264_log( h, X264_LOG_WARNING, "--psnr used with AQ on: results will be invalid!\n" );
  1057. s = "psnr";
  1058. }
  1059. if( s )
  1060. x264_log( h, X264_LOG_WARNING, "--tune %s should be used if attempting to benchmark %s!\n", s, s );
  1061. }
  1062. if( !h->param.analyse.b_psy )
  1063. {
  1064. h->param.analyse.f_psy_rd = 0;
  1065. h->param.analyse.f_psy_trellis = 0;
  1066. }
  1067. h->param.analyse.f_psy_rd = x264_clip3f( h->param.analyse.f_psy_rd, 0, 10 );
  1068. h->param.analyse.f_psy_trellis = x264_clip3f( h->param.analyse.f_psy_trellis, 0, 10 );
  1069. h->mb.i_psy_rd = h->param.analyse.i_subpel_refine >= 6 ? FIX8( h->param.analyse.f_psy_rd ) : 0;
  1070. h->mb.i_psy_trellis = h->param.analyse.i_trellis ? FIX8( h->param.analyse.f_psy_trellis / 4 ) : 0;
  1071. h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -32, 32);
  1072. /* In 4:4:4 mode, chroma gets twice as much resolution, so we can halve its quality. */
  1073. if( b_open && i_csp >= X264_CSP_I444 && i_csp < X264_CSP_BGR && h->param.analyse.b_psy )
  1074. h->param.analyse.i_chroma_qp_offset += 6;
  1075. /* Psy RDO increases overall quantizers to improve the quality of luma--this indirectly hurts chroma quality */
  1076. /* so we lower the chroma QP offset to compensate */
  1077. if( b_open && h->mb.i_psy_rd && !h->param.i_avcintra_class )
  1078. h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_rd < 0.25 ? 1 : 2;
  1079. /* Psy trellis has a similar effect. */
  1080. if( b_open && h->mb.i_psy_trellis && !h->param.i_avcintra_class )
  1081. h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_trellis < 0.25 ? 1 : 2;
  1082. h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  1083. /* MB-tree requires AQ to be on, even if the strength is zero. */
  1084. if( !h->param.rc.i_aq_mode && h->param.rc.b_mb_tree )
  1085. {
  1086. h->param.rc.i_aq_mode = 1;
  1087. h->param.rc.f_aq_strength = 0;
  1088. }
  1089. h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
  1090. if( h->param.analyse.i_subpel_refine >= 10 && (h->param.analyse.i_trellis != 2 || !h->param.rc.i_aq_mode) )
  1091. h->param.analyse.i_subpel_refine = 9;
  1092. if( b_open )
  1093. {
  1094. const x264_level_t *l = x264_levels;
  1095. if( h->param.i_level_idc < 0 )
  1096. {
  1097. int maxrate_bak = h->param.rc.i_vbv_max_bitrate;
  1098. if( h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_buffer_size <= 0 )
  1099. h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate * 2;
  1100. x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  1101. do h->param.i_level_idc = l->level_idc;
  1102. while( l[1].level_idc && x264_validate_levels( h, 0 ) && l++ );
  1103. h->param.rc.i_vbv_max_bitrate = maxrate_bak;
  1104. }
  1105. else
  1106. {
  1107. while( l->level_idc && l->level_idc != h->param.i_level_idc )
  1108. l++;
  1109. if( l->level_idc == 0 )
  1110. {
  1111. x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
  1112. return -1;
  1113. }
  1114. }
  1115. if( h->param.analyse.i_mv_range <= 0 )
  1116. h->param.analyse.i_mv_range = l->mv_range >> PARAM_INTERLACED;
  1117. else
  1118. h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 8192 >> PARAM_INTERLACED);
  1119. }
  1120. h->param.analyse.i_weighted_pred = x264_clip3( h->param.analyse.i_weighted_pred, X264_WEIGHTP_NONE, X264_WEIGHTP_SMART );
  1121. if( h->param.i_lookahead_threads == X264_THREADS_AUTO )
  1122. {
  1123. if( h->param.b_sliced_threads )
  1124. h->param.i_lookahead_threads = h->param.i_threads;
  1125. else
  1126. {
  1127. /* If we're using much slower lookahead settings than encoding settings, it helps a lot to use
  1128. * more lookahead threads. This typically happens in the first pass of a two-pass encode, so
  1129. * try to guess at this sort of case.
  1130. *
  1131. * Tuned by a little bit of real encoding with the various presets. */
  1132. int badapt = h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS;
  1133. int subme = X264_MIN( h->param.analyse.i_subpel_refine / 3, 3 ) + (h->param.analyse.i_subpel_refine > 1);
  1134. int bframes = X264_MIN( (h->param.i_bframe - 1) / 3, 3 );
  1135. /* [b-adapt 0/1 vs 2][quantized subme][quantized bframes] */
  1136. static const uint8_t lookahead_thread_div[2][5][4] =
  1137. {{{6,6,6,6}, {3,3,3,3}, {4,4,4,4}, {6,6,6,6}, {12,12,12,12}},
  1138. {{3,2,1,1}, {2,1,1,1}, {4,3,2,1}, {6,4,3,2}, {12, 9, 6, 4}}};
  1139. h->param.i_lookahead_threads = h->param.i_threads / lookahead_thread_div[badapt][subme][bframes];
  1140. /* Since too many lookahead threads significantly degrades lookahead accuracy, limit auto
  1141. * lookahead threads to about 8 macroblock rows high each at worst. This number is chosen
  1142. * pretty much arbitrarily. */
  1143. h->param.i_lookahead_threads = X264_MIN( h->param.i_lookahead_threads, h->param.i_height / 128 );
  1144. }
  1145. }
  1146. h->param.i_lookahead_threads = x264_clip3( h->param.i_lookahead_threads, 1, X264_MIN( max_sliced_threads, X264_LOOKAHEAD_THREAD_MAX ) );
  1147. if( PARAM_INTERLACED )
  1148. {
  1149. if( h->param.analyse.i_me_method >= X264_ME_ESA )
  1150. {
  1151. x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implemented\n" );
  1152. h->param.analyse.i_me_method = X264_ME_UMH;
  1153. }
  1154. if( h->param.analyse.i_weighted_pred > 0 )
  1155. {
  1156. x264_log( h, X264_LOG_WARNING, "interlace + weightp is not implemented\n" );
  1157. h->param.analyse.i_weighted_pred = X264_WEIGHTP_NONE;
  1158. }
  1159. }
  1160. if( !h->param.analyse.i_weighted_pred && h->param.rc.b_mb_tree && h->param.analyse.b_psy )
  1161. h->param.analyse.i_weighted_pred = X264_WEIGHTP_FAKE;
  1162. if( h->i_thread_frames > 1 )
  1163. {
  1164. int r = h->param.analyse.i_mv_range_thread;
  1165. int r2;
  1166. if( r <= 0 )
  1167. {
  1168. // half of the available space is reserved and divided evenly among the threads,
  1169. // the rest is allocated to whichever thread is far enough ahead to use it.
  1170. // reserving more space increases quality for some videos, but costs more time
  1171. // in thread synchronization.
  1172. int max_range = (h->param.i_height + X264_THREAD_HEIGHT) / h->i_thread_frames - X264_THREAD_HEIGHT;
  1173. r = max_range / 2;
  1174. }
  1175. r = X264_MAX( r, h->param.analyse.i_me_range );
  1176. r = X264_MIN( r, h->param.analyse.i_mv_range );
  1177. // round up to use the whole mb row
  1178. r2 = (r & ~15) + ((-X264_THREAD_HEIGHT) & 15);
  1179. if( r2 < r )
  1180. r2 += 16;
  1181. x264_log( h, X264_LOG_DEBUG, "using mv_range_thread = %d\n", r2 );
  1182. h->param.analyse.i_mv_range_thread = r2;
  1183. }
  1184. if( h->param.rc.f_rate_tolerance < 0 )
  1185. h->param.rc.f_rate_tolerance = 0;
  1186. if( h->param.rc.f_qblur < 0 )
  1187. h->param.rc.f_qblur = 0;
  1188. if( h->param.rc.f_complexity_blur < 0 )
  1189. h->param.rc.f_complexity_blur = 0;
  1190. h->param.i_sps_id &= 31;
  1191. h->param.i_nal_hrd = x264_clip3( h->param.i_nal_hrd, X264_NAL_HRD_NONE, X264_NAL_HRD_CBR );
  1192. if( h->param.i_nal_hrd && !h->param.rc.i_vbv_buffer_size )
  1193. {
  1194. x264_log( h, X264_LOG_WARNING, "NAL HRD parameters require VBV parameters\n" );
  1195. h->param.i_nal_hrd = X264_NAL_HRD_NONE;
  1196. }
  1197. if( h->param.i_nal_hrd == X264_NAL_HRD_CBR &&
  1198. (h->param.rc.i_bitrate != h->param.rc.i_vbv_max_bitrate || !h->param.rc.i_vbv_max_bitrate) )
  1199. {
  1200. x264_log( h, X264_LOG_WARNING, "CBR HRD requires constant bitrate\n" );
  1201. h->param.i_nal_hrd = X264_NAL_HRD_VBR;
  1202. }
  1203. if( h->param.i_nal_hrd == X264_NAL_HRD_CBR )
  1204. h->param.rc.b_filler = 1;
  1205. /* ensure the booleans are 0 or 1 so they can be used in math */
  1206. #define BOOLIFY(x) h->param.x = !!h->param.x
  1207. BOOLIFY( b_cabac );
  1208. BOOLIFY( b_constrained_intra );
  1209. BOOLIFY( b_deblocking_filter );
  1210. BOOLIFY( b_deterministic );
  1211. BOOLIFY( b_sliced_threads );
  1212. BOOLIFY( b_interlaced );
  1213. BOOLIFY( b_intra_refresh );
  1214. BOOLIFY( b_aud );
  1215. BOOLIFY( b_repeat_headers );
  1216. BOOLIFY( b_annexb );
  1217. BOOLIFY( b_vfr_input );
  1218. BOOLIFY( b_pulldown );
  1219. BOOLIFY( b_tff );
  1220. BOOLIFY( b_pic_struct );
  1221. BOOLIFY( b_fake_interlaced );
  1222. BOOLIFY( b_open_gop );
  1223. BOOLIFY( b_bluray_compat );
  1224. BOOLIFY( b_stitchable );
  1225. BOOLIFY( b_full_recon );
  1226. BOOLIFY( b_opencl );
  1227. BOOLIFY( analyse.b_transform_8x8 );
  1228. BOOLIFY( analyse.b_weighted_bipred );
  1229. BOOLIFY( analyse.b_chroma_me );
  1230. BOOLIFY( analyse.b_mixed_references );
  1231. BOOLIFY( analyse.b_fast_pskip );
  1232. BOOLIFY( analyse.b_dct_decimate );
  1233. BOOLIFY( analyse.b_psy );
  1234. BOOLIFY( analyse.b_psnr );
  1235. BOOLIFY( analyse.b_ssim );
  1236. BOOLIFY( rc.b_stat_write );
  1237. BOOLIFY( rc.b_stat_read );
  1238. BOOLIFY( rc.b_mb_tree );
  1239. BOOLIFY( rc.b_filler );
  1240. #undef BOOLIFY
  1241. return 0;
  1242. }
  1243. static void mbcmp_init( x264_t *h )
  1244. {
  1245. int satd = !h->mb.b_lossless && h->param.analyse.i_subpel_refine > 1;
  1246. memcpy( h->pixf.mbcmp, satd ? h->pixf.satd : h->pixf.sad_aligned, sizeof(h->pixf.mbcmp) );
  1247. memcpy( h->pixf.mbcmp_unaligned, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.mbcmp_unaligned) );
  1248. h->pixf.intra_mbcmp_x3_16x16 = satd ? h->pixf.intra_satd_x3_16x16 : h->pixf.intra_sad_x3_16x16;
  1249. h->pixf.intra_mbcmp_x3_8x16c = satd ? h->pixf.intra_satd_x3_8x16c : h->pixf.intra_sad_x3_8x16c;
  1250. h->pixf.intra_mbcmp_x3_8x8c = satd ? h->pixf.intra_satd_x3_8x8c : h->pixf.intra_sad_x3_8x8c;
  1251. h->pixf.intra_mbcmp_x3_8x8 = satd ? h->pixf.intra_sa8d_x3_8x8 : h->pixf.intra_sad_x3_8x8;
  1252. h->pixf.intra_mbcmp_x3_4x4 = satd ? h->pixf.intra_satd_x3_4x4 : h->pixf.intra_sad_x3_4x4;
  1253. h->pixf.intra_mbcmp_x9_4x4 = h->param.b_cpu_independent || h->mb.b_lossless ? NULL
  1254. : satd ? h->pixf.intra_satd_x9_4x4 : h->pixf.intra_sad_x9_4x4;
  1255. h->pixf.intra_mbcmp_x9_8x8 = h->param.b_cpu_independent || h->mb.b_lossless ? NULL
  1256. : satd ? h->pixf.intra_sa8d_x9_8x8 : h->pixf.intra_sad_x9_8x8;
  1257. satd &= h->param.analyse.i_me_method == X264_ME_TESA;
  1258. memcpy( h->pixf.fpelcmp, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.fpelcmp) );
  1259. memcpy( h->pixf.fpelcmp_x3, satd ? h->pixf.satd_x3 : h->pixf.sad_x3, sizeof(h->pixf.fpelcmp_x3) );
  1260. memcpy( h->pixf.fpelcmp_x4, satd ? h->pixf.satd_x4 : h->pixf.sad_x4, sizeof(h->pixf.fpelcmp_x4) );
  1261. }
  1262. static void chroma_dsp_init( x264_t *h )
  1263. {
  1264. memcpy( h->luma2chroma_pixel, x264_luma2chroma_pixel[CHROMA_FORMAT], sizeof(h->luma2chroma_pixel) );
  1265. switch( CHROMA_FORMAT )
  1266. {
  1267. case CHROMA_400:
  1268. h->mc.prefetch_fenc = h->mc.prefetch_fenc_400;
  1269. break;
  1270. case CHROMA_420:
  1271. memcpy( h->predict_chroma, h->predict_8x8c, sizeof(h->predict_chroma) );
  1272. h->mc.prefetch_fenc = h->mc.prefetch_fenc_420;
  1273. h->loopf.deblock_chroma[0] = h->loopf.deblock_h_chroma_420;
  1274. h->loopf.deblock_chroma_intra[0] = h->loopf.deblock_h_chroma_420_intra;
  1275. h->loopf.deblock_chroma_mbaff = h->loopf.deblock_chroma_420_mbaff;
  1276. h->loopf.deblock_chroma_intra_mbaff = h->loopf.deblock_chroma_420_intra_mbaff;
  1277. h->pixf.intra_mbcmp_x3_chroma = h->pixf.intra_mbcmp_x3_8x8c;
  1278. h->quantf.coeff_last[DCT_CHROMA_DC] = h->quantf.coeff_last4;
  1279. h->quantf.coeff_level_run[DCT_CHROMA_DC] = h->quantf.coeff_level_run4;
  1280. break;
  1281. case CHROMA_422:
  1282. memcpy( h->predict_chroma, h->predict_8x16c, sizeof(h->predict_chroma) );
  1283. h->mc.prefetch_fenc = h->mc.prefetch_fenc_422;
  1284. h->loopf.deblock_chroma[0] = h->loopf.deblock_h_chroma_422;
  1285. h->loopf.deblock_chroma_intra[0] = h->loopf.deblock_h_chroma_422_intra;
  1286. h->loopf.deblock_chroma_mbaff = h->loopf.deblock_chroma_422_mbaff;
  1287. h->loopf.deblock_chroma_intra_mbaff = h->loopf.deblock_chroma_422_intra_mbaff;
  1288. h->pixf.intra_mbcmp_x3_chroma = h->pixf.intra_mbcmp_x3_8x16c;
  1289. h->quantf.coeff_last[DCT_CHROMA_DC] = h->quantf.coeff_last8;
  1290. h->quantf.coeff_level_run[DCT_CHROMA_DC] = h->quantf.coeff_level_run8;
  1291. break;
  1292. case CHROMA_444:
  1293. h->mc.prefetch_fenc = h->mc.prefetch_fenc_422; /* FIXME: doesn't cover V plane */
  1294. h->loopf.deblock_chroma_mbaff = h->loopf.deblock_luma_mbaff;
  1295. h->loopf.deblock_chroma_intra_mbaff = h->loopf.deblock_luma_intra_mbaff;
  1296. break;
  1297. }
  1298. }
  1299. static void set_aspect_ratio( x264_t *h, x264_param_t *param, int initial )
  1300. {
  1301. /* VUI */
  1302. if( param->vui.i_sar_width > 0 && param->vui.i_sar_height > 0 )
  1303. {
  1304. uint32_t i_w = param->vui.i_sar_width;
  1305. uint32_t i_h = param->vui.i_sar_height;
  1306. uint32_t old_w = h->param.vui.i_sar_width;
  1307. uint32_t old_h = h->param.vui.i_sar_height;
  1308. x264_reduce_fraction( &i_w, &i_h );
  1309. while( i_w > 65535 || i_h > 65535 )
  1310. {
  1311. i_w /= 2;
  1312. i_h /= 2;
  1313. }
  1314. x264_reduce_fraction( &i_w, &i_h );
  1315. if( i_w != old_w || i_h != old_h || initial )
  1316. {
  1317. h->param.vui.i_sar_width = 0;
  1318. h->param.vui.i_sar_height = 0;
  1319. if( i_w == 0 || i_h == 0 )
  1320. x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ratio\n" );
  1321. else
  1322. {
  1323. x264_log( h, initial?X264_LOG_INFO:X264_LOG_DEBUG, "using SAR=%d/%d\n", i_w, i_h );
  1324. h->param.vui.i_sar_width = i_w;
  1325. h->param.vui.i_sar_height = i_h;
  1326. }
  1327. }
  1328. }
  1329. }
  1330. /****************************************************************************
  1331. * x264_encoder_open:
  1332. ****************************************************************************/
  1333. x264_t *x264_encoder_open( x264_param_t *param )
  1334. {
  1335. x264_t *h;
  1336. char buf[1000], *p;
  1337. int i_slicetype_length;
  1338. CHECKED_MALLOCZERO( h, sizeof(x264_t) );
  1339. /* Create a copy of param */
  1340. memcpy( &h->param, param, sizeof(x264_param_t) );
  1341. if( param->param_free )
  1342. param->param_free( param );
  1343. #if HAVE_INTEL_DISPATCHER
  1344. x264_intel_dispatcher_override();
  1345. #endif
  1346. if( x264_threading_init() )
  1347. {
  1348. x264_log( h, X264_LOG_ERROR, "unable to initialize threading\n" );
  1349. goto fail;
  1350. }
  1351. if( validate_parameters( h, 1 ) < 0 )
  1352. goto fail;
  1353. if( h->param.psz_cqm_file )
  1354. if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
  1355. goto fail;
  1356. if( h->param.rc.psz_stat_out )
  1357. h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
  1358. if( h->param.rc.psz_stat_in )
  1359. h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
  1360. x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
  1361. x264_reduce_fraction( &h->param.i_timebase_num, &h->param.i_timebase_den );
  1362. /* Init x264_t */
  1363. h->i_frame = -1;
  1364. h->i_frame_num = 0;
  1365. if( h->param.i_avcintra_class )
  1366. h->i_idr_pic_id = 5;
  1367. else
  1368. h->i_idr_pic_id = 0;
  1369. if( (uint64_t)h->param.i_timebase_den * 2 > UINT32_MAX )
  1370. {
  1371. x264_log( h, X264_LOG_ERROR, "Effective timebase denominator %u exceeds H.264 maximum\n", h->param.i_timebase_den );
  1372. goto fail;
  1373. }
  1374. set_aspect_ratio( h, &h->param, 1 );
  1375. x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  1376. x264_sps_init_scaling_list( h->sps, &h->param );
  1377. x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps );
  1378. x264_validate_levels( h, 1 );
  1379. h->chroma_qp_table = i_chroma_qp_table + 12 + h->pps->i_chroma_qp_index_offset;
  1380. if( x264_cqm_init( h ) < 0 )
  1381. goto fail;
  1382. h->mb.i_mb_width = h->sps->i_mb_width;
  1383. h->mb.i_mb_height = h->sps->i_mb_height;
  1384. h->mb.i_mb_count = h->mb.i_mb_width * h->mb.i_mb_height;
  1385. h->mb.chroma_h_shift = CHROMA_FORMAT == CHROMA_420 || CHROMA_FORMAT == CHROMA_422;
  1386. h->mb.chroma_v_shift = CHROMA_FORMAT == CHROMA_420;
  1387. /* Adaptive MBAFF and subme 0 are not supported as we require halving motion
  1388. * vectors during prediction, resulting in hpel mvs.
  1389. * The chosen solution is to make MBAFF non-adaptive in this case. */
  1390. h->mb.b_adaptive_mbaff = PARAM_INTERLACED && h->param.analyse.i_subpel_refine;
  1391. /* Init frames. */
  1392. if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS && !h->param.rc.b_stat_read )
  1393. h->frames.i_delay = X264_MAX(h->param.i_bframe,3)*4;
  1394. else
  1395. h->frames.i_delay = h->param.i_bframe;
  1396. if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size )
  1397. h->frames.i_delay = X264_MAX( h->frames.i_delay, h->param.rc.i_lookahead );
  1398. i_slicetype_length = h->frames.i_delay;
  1399. h->frames.i_delay += h->i_thread_frames - 1;
  1400. h->frames.i_delay += h->param.i_sync_lookahead;
  1401. h->frames.i_delay += h->param.b_vfr_input;
  1402. h->frames.i_bframe_delay = h->param.i_bframe ? (h->param.i_bframe_pyramid ? 2 : 1) : 0;
  1403. h->frames.i_max_ref0 = h->param.i_frame_reference;
  1404. h->frames.i_max_ref1 = X264_MIN( h->sps->vui.i_num_reorder_frames, h->param.i_frame_reference );
  1405. h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering;
  1406. h->frames.b_have_lowres = !h->param.rc.b_stat_read
  1407. && ( h->param.rc.i_rc_method == X264_RC_ABR
  1408. || h->param.rc.i_rc_method == X264_RC_CRF
  1409. || h->param.i_bframe_adaptive
  1410. || h->param.i_scenecut_threshold
  1411. || h->param.rc.b_mb_tree
  1412. || h->param.analyse.i_weighted_pred );
  1413. h->frames.b_have_lowres |= h->param.rc.b_stat_read && h->param.rc.i_vbv_buffer_size > 0;
  1414. h->frames.b_have_sub8x8_esa = !!(h->param.analyse.inter & X264_ANALYSE_PSUB8x8);
  1415. h->frames.i_last_idr =
  1416. h->frames.i_last_keyframe = - h->param.i_keyint_max;
  1417. h->frames.i_input = 0;
  1418. h->frames.i_largest_pts = h->frames.i_second_largest_pts = -1;
  1419. h->frames.i_poc_last_open_gop = -1;
  1420. CHECKED_MALLOCZERO( h->cost_table, sizeof(*h->cost_table) );
  1421. CHECKED_MALLOCZERO( h->frames.unused[0], (h->frames.i_delay + 3) * sizeof(x264_frame_t *) );
  1422. /* Allocate room for max refs plus a few extra just in case. */
  1423. CHECKED_MALLOCZERO( h->frames.unused[1], (h->i_thread_frames + X264_REF_MAX + 4) * sizeof(x264_frame_t *) );
  1424. CHECKED_MALLOCZERO( h->frames.current, (h->param.i_sync_lookahead + h->param.i_bframe
  1425. + h->i_thread_frames + 3) * sizeof(x264_frame_t *) );
  1426. if( h->param.analyse.i_weighted_pred > 0 )
  1427. CHECKED_MALLOCZERO( h->frames.blank_unused, h->i_thread_frames * 4 * sizeof(x264_frame_t *) );
  1428. h->i_ref[0] = h->i_ref[1] = 0;
  1429. h->i_cpb_delay = h->i_coded_fields = h->i_disp_fields = 0;
  1430. h->i_prev_duration = ((uint64_t)h->param.i_fps_den * h->sps->vui.i_time_scale) / ((uint64_t)h->param.i_fps_num * h->sps->vui.i_num_units_in_tick);
  1431. h->i_disp_fields_last_frame = -1;
  1432. x264_rdo_init();
  1433. /* init CPU functions */
  1434. #if (ARCH_X86 || ARCH_X86_64) && HIGH_BIT_DEPTH
  1435. /* FIXME: Only 8-bit has been optimized for AVX-512 so far. The few AVX-512 functions
  1436. * enabled in high bit-depth are insignificant and just causes potential issues with
  1437. * unnecessary thermal throttling and whatnot, so keep it disabled for now. */
  1438. h->param.cpu &= ~X264_CPU_AVX512;
  1439. #endif
  1440. x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
  1441. x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
  1442. x264_predict_8x16c_init( h->param.cpu, h->predict_8x16c );
  1443. x264_predict_8x8_init( h->param.cpu, h->predict_8x8, &h->predict_8x8_filter );
  1444. x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
  1445. x264_pixel_init( h->param.cpu, &h->pixf );
  1446. x264_dct_init( h->param.cpu, &h->dctf );
  1447. x264_zigzag_init( h->param.cpu, &h->zigzagf_progressive, &h->zigzagf_interlaced );
  1448. memcpy( &h->zigzagf, PARAM_INTERLACED ? &h->zigzagf_interlaced : &h->zigzagf_progressive, sizeof(h->zigzagf) );
  1449. x264_mc_init( h->param.cpu, &h->mc, h->param.b_cpu_independent );
  1450. x264_quant_init( h, h->param.cpu, &h->quantf );
  1451. x264_deblock_init( h->param.cpu, &h->loopf, PARAM_INTERLACED );
  1452. x264_bitstream_init( h->param.cpu, &h->bsf );
  1453. if( h->param.b_cabac )
  1454. x264_cabac_init( h );
  1455. else
  1456. x264_cavlc_init( h );
  1457. mbcmp_init( h );
  1458. chroma_dsp_init( h );
  1459. p = buf + sprintf( buf, "using cpu capabilities:" );
  1460. for( int i = 0; x264_cpu_names[i].flags; i++ )
  1461. {
  1462. if( !strcmp(x264_cpu_names[i].name, "SSE")
  1463. && h->param.cpu & (X264_CPU_SSE2) )
  1464. continue;
  1465. if( !strcmp(x264_cpu_names[i].name, "SSE2")
  1466. && h->param.cpu & (X264_CPU_SSE2_IS_FAST|X264_CPU_SSE2_IS_SLOW) )
  1467. continue;
  1468. if( !strcmp(x264_cpu_names[i].name, "SSE3")
  1469. && (h->param.cpu & X264_CPU_SSSE3 || !(h->param.cpu & X264_CPU_CACHELINE_64)) )
  1470. continue;
  1471. if( !strcmp(x264_cpu_names[i].name, "SSE4.1")
  1472. && (h->param.cpu & X264_CPU_SSE42) )
  1473. continue;
  1474. if( !strcmp(x264_cpu_names[i].name, "LZCNT")
  1475. && (h->param.cpu & X264_CPU_BMI1) )
  1476. continue;
  1477. if( !strcmp(x264_cpu_names[i].name, "BMI1")
  1478. && (h->param.cpu & X264_CPU_BMI2) )
  1479. continue;
  1480. if( !strcmp(x264_cpu_names[i].name, "FMA4")
  1481. && (h->param.cpu & X264_CPU_FMA3) )
  1482. continue;
  1483. if( (h->param.cpu & x264_cpu_names[i].flags) == x264_cpu_names[i].flags
  1484. && (!i || x264_cpu_names[i].flags != x264_cpu_names[i-1].flags) )
  1485. p += sprintf( p, " %s", x264_cpu_names[i].name );
  1486. }
  1487. if( !h->param.cpu )
  1488. p += sprintf( p, " none!" );
  1489. x264_log( h, X264_LOG_INFO, "%s\n", buf );
  1490. if( x264_analyse_init_costs( h ) )
  1491. goto fail;
  1492. /* Must be volatile or else GCC will optimize it out. */
  1493. volatile int temp = 392;
  1494. if( x264_clz( temp ) != 23 )
  1495. {
  1496. x264_log( h, X264_LOG_ERROR, "CLZ test failed: x264 has been miscompiled!\n" );
  1497. #if ARCH_X86 || ARCH_X86_64
  1498. x264_log( h, X264_LOG_ERROR, "Are you attempting to run an SSE4a/LZCNT-targeted build on a CPU that\n" );
  1499. x264_log( h, X264_LOG_ERROR, "doesn't support it?\n" );
  1500. #endif
  1501. goto fail;
  1502. }
  1503. h->out.i_nal = 0;
  1504. h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 4
  1505. * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.95, h->param.rc.i_qp_min )
  1506. : pow( 0.95, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
  1507. h->nal_buffer_size = h->out.i_bitstream * 3/2 + 4 + 64; /* +4 for startcode, +64 for nal_escape assembly padding */
  1508. CHECKED_MALLOC( h->nal_buffer, h->nal_buffer_size );
  1509. CHECKED_MALLOC( h->reconfig_h, sizeof(x264_t) );
  1510. if( h->param.i_threads > 1 &&
  1511. x264_threadpool_init( &h->threadpool, h->param.i_threads, (void*)encoder_thread_init, h ) )
  1512. goto fail;
  1513. if( h->param.i_lookahead_threads > 1 &&
  1514. x264_threadpool_init( &h->lookaheadpool, h->param.i_lookahead_threads, NULL, NULL ) )
  1515. goto fail;
  1516. #if HAVE_OPENCL
  1517. if( h->param.b_opencl )
  1518. {
  1519. h->opencl.ocl = x264_opencl_load_library();
  1520. if( !h->opencl.ocl )
  1521. {
  1522. x264_log( h, X264_LOG_WARNING, "failed to load OpenCL\n" );
  1523. h->param.b_opencl = 0;
  1524. }
  1525. }
  1526. #endif
  1527. h->thread[0] = h;
  1528. for( int i = 1; i < h->param.i_threads + !!h->param.i_sync_lookahead; i++ )
  1529. CHECKED_MALLOC( h->thread[i], sizeof(x264_t) );
  1530. if( h->param.i_lookahead_threads > 1 )
  1531. for( int i = 0; i < h->param.i_lookahead_threads; i++ )
  1532. {
  1533. CHECKED_MALLOC( h->lookahead_thread[i], sizeof(x264_t) );
  1534. *h->lookahead_thread[i] = *h;
  1535. }
  1536. *h->reconfig_h = *h;
  1537. for( int i = 0; i < h->param.i_threads; i++ )
  1538. {
  1539. int init_nal_count = h->param.i_slice_count + 3;
  1540. int allocate_threadlocal_data = !h->param.b_sliced_threads || !i;
  1541. if( i > 0 )
  1542. *h->thread[i] = *h;
  1543. if( x264_pthread_mutex_init( &h->thread[i]->mutex, NULL ) )
  1544. goto fail;
  1545. if( x264_pthread_cond_init( &h->thread[i]->cv, NULL ) )
  1546. goto fail;
  1547. if( allocate_threadlocal_data )
  1548. {
  1549. h->thread[i]->fdec = x264_frame_pop_unused( h, 1 );
  1550. if( !h->thread[i]->fdec )
  1551. goto fail;
  1552. }
  1553. else
  1554. h->thread[i]->fdec = h->thread[0]->fdec;
  1555. CHECKED_MALLOC( h->thread[i]->out.p_bitstream, h->out.i_bitstream );
  1556. /* Start each thread with room for init_nal_count NAL units; it'll realloc later if needed. */
  1557. CHECKED_MALLOC( h->thread[i]->out.nal, init_nal_count*sizeof(x264_nal_t) );
  1558. h->thread[i]->out.i_nals_allocated = init_nal_count;
  1559. if( allocate_threadlocal_data && x264_macroblock_cache_allocate( h->thread[i] ) < 0 )
  1560. goto fail;
  1561. }
  1562. #if HAVE_OPENCL
  1563. if( h->param.b_opencl && x264_opencl_lookahead_init( h ) < 0 )
  1564. h->param.b_opencl = 0;
  1565. #endif
  1566. if( x264_lookahead_init( h, i_slicetype_length ) )
  1567. goto fail;
  1568. for( int i = 0; i < h->param.i_threads; i++ )
  1569. if( x264_macroblock_thread_allocate( h->thread[i], 0 ) < 0 )
  1570. goto fail;
  1571. if( x264_ratecontrol_new( h ) < 0 )
  1572. goto fail;
  1573. if( h->param.i_nal_hrd )
  1574. {
  1575. x264_log( h, X264_LOG_DEBUG, "HRD bitrate: %i bits/sec\n", h->sps->vui.hrd.i_bit_rate_unscaled );
  1576. x264_log( h, X264_LOG_DEBUG, "CPB size: %i bits\n", h->sps->vui.hrd.i_cpb_size_unscaled );
  1577. }
  1578. if( h->param.psz_dump_yuv )
  1579. {
  1580. /* create or truncate the reconstructed video file */
  1581. FILE *f = x264_fopen( h->param.psz_dump_yuv, "w" );
  1582. if( !f )
  1583. {
  1584. x264_log( h, X264_LOG_ERROR, "dump_yuv: can't write to %s\n", h->param.psz_dump_yuv );
  1585. goto fail;
  1586. }
  1587. else if( !x264_is_regular_file( f ) )
  1588. {
  1589. x264_log( h, X264_LOG_ERROR, "dump_yuv: incompatible with non-regular file %s\n", h->param.psz_dump_yuv );
  1590. fclose( f );
  1591. goto fail;
  1592. }
  1593. fclose( f );
  1594. }
  1595. const char *profile = h->sps->i_profile_idc == PROFILE_BASELINE ? "Constrained Baseline" :
  1596. h->sps->i_profile_idc == PROFILE_MAIN ? "Main" :
  1597. h->sps->i_profile_idc == PROFILE_HIGH ? "High" :
  1598. h->sps->i_profile_idc == PROFILE_HIGH10 ? (h->sps->b_constraint_set3 == 1 ? "High 10 Intra" : "High 10") :
  1599. h->sps->i_profile_idc == PROFILE_HIGH422 ? (h->sps->b_constraint_set3 == 1 ? "High 4:2:2 Intra" : "High 4:2:2") :
  1600. h->sps->b_constraint_set3 == 1 ? "High 4:4:4 Intra" : "High 4:4:4 Predictive";
  1601. char level[4];
  1602. snprintf( level, sizeof(level), "%d.%d", h->sps->i_level_idc/10, h->sps->i_level_idc%10 );
  1603. if( h->sps->i_level_idc == 9 || ( h->sps->i_level_idc == 11 && h->sps->b_constraint_set3 &&
  1604. (h->sps->i_profile_idc == PROFILE_BASELINE || h->sps->i_profile_idc == PROFILE_MAIN) ) )
  1605. strcpy( level, "1b" );
  1606. static const char * const subsampling[4] = { "4:0:0", "4:2:0", "4:2:2", "4:4:4" };
  1607. x264_log( h, X264_LOG_INFO, "profile %s, level %s, %s, %d-bit\n",
  1608. profile, level, subsampling[CHROMA_FORMAT], BIT_DEPTH );
  1609. return h;
  1610. fail:
  1611. x264_free( h );
  1612. return NULL;
  1613. }
  1614. /****************************************************************************/
  1615. static int encoder_try_reconfig( x264_t *h, x264_param_t *param, int *rc_reconfig )
  1616. {
  1617. *rc_reconfig = 0;
  1618. set_aspect_ratio( h, param, 0 );
  1619. #define COPY(var) h->param.var = param->var
  1620. COPY( i_frame_reference ); // but never uses more refs than initially specified
  1621. COPY( i_bframe_bias );
  1622. if( h->param.i_scenecut_threshold )
  1623. COPY( i_scenecut_threshold ); // can't turn it on or off, only vary the threshold
  1624. COPY( b_deblocking_filter );
  1625. COPY( i_deblocking_filter_alphac0 );
  1626. COPY( i_deblocking_filter_beta );
  1627. COPY( i_frame_packing );
  1628. COPY( analyse.inter );
  1629. COPY( analyse.intra );
  1630. COPY( analyse.i_direct_mv_pred );
  1631. /* Scratch buffer prevents me_range from being increased for esa/tesa */
  1632. if( h->param.analyse.i_me_method < X264_ME_ESA || param->analyse.i_me_range < h->param.analyse.i_me_range )
  1633. COPY( analyse.i_me_range );
  1634. COPY( analyse.i_noise_reduction );
  1635. /* We can't switch out of subme=0 during encoding. */
  1636. if( h->param.analyse.i_subpel_refine )
  1637. COPY( analyse.i_subpel_refine );
  1638. COPY( analyse.i_trellis );
  1639. COPY( analyse.b_chroma_me );
  1640. COPY( analyse.b_dct_decimate );
  1641. COPY( analyse.b_fast_pskip );
  1642. COPY( analyse.b_mixed_references );
  1643. COPY( analyse.f_psy_rd );
  1644. COPY( analyse.f_psy_trellis );
  1645. COPY( crop_rect );
  1646. // can only twiddle these if they were enabled to begin with:
  1647. if( h->param.analyse.i_me_method >= X264_ME_ESA || param->analyse.i_me_method < X264_ME_ESA )
  1648. COPY( analyse.i_me_method );
  1649. if( h->param.analyse.i_me_method >= X264_ME_ESA && !h->frames.b_have_sub8x8_esa )
  1650. h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  1651. if( h->pps->b_transform_8x8_mode )
  1652. COPY( analyse.b_transform_8x8 );
  1653. if( h->frames.i_max_ref1 > 1 )
  1654. COPY( i_bframe_pyramid );
  1655. COPY( i_slice_max_size );
  1656. COPY( i_slice_max_mbs );
  1657. COPY( i_slice_min_mbs );
  1658. COPY( i_slice_count );
  1659. COPY( i_slice_count_max );
  1660. COPY( b_tff );
  1661. /* VBV can't be turned on if it wasn't on to begin with */
  1662. if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 &&
  1663. param->rc.i_vbv_max_bitrate > 0 && param->rc.i_vbv_buffer_size > 0 )
  1664. {
  1665. *rc_reconfig |= h->param.rc.i_vbv_max_bitrate != param->rc.i_vbv_max_bitrate;
  1666. *rc_reconfig |= h->param.rc.i_vbv_buffer_size != param->rc.i_vbv_buffer_size;
  1667. *rc_reconfig |= h->param.rc.i_bitrate != param->rc.i_bitrate;
  1668. COPY( rc.i_vbv_max_bitrate );
  1669. COPY( rc.i_vbv_buffer_size );
  1670. COPY( rc.i_bitrate );
  1671. }
  1672. *rc_reconfig |= h->param.rc.f_rf_constant != param->rc.f_rf_constant;
  1673. *rc_reconfig |= h->param.rc.f_rf_constant_max != param->rc.f_rf_constant_max;
  1674. COPY( rc.f_rf_constant );
  1675. COPY( rc.f_rf_constant_max );
  1676. #undef COPY
  1677. return validate_parameters( h, 0 );
  1678. }
  1679. int x264_encoder_reconfig_apply( x264_t *h, x264_param_t *param )
  1680. {
  1681. int rc_reconfig;
  1682. int ret = encoder_try_reconfig( h, param, &rc_reconfig );
  1683. mbcmp_init( h );
  1684. if( !ret )
  1685. x264_sps_init_reconfigurable( h->sps, &h->param );
  1686. /* Supported reconfiguration options (1-pass only):
  1687. * vbv-maxrate
  1688. * vbv-bufsize
  1689. * crf
  1690. * bitrate (CBR only) */
  1691. if( !ret && rc_reconfig )
  1692. x264_ratecontrol_init_reconfigurable( h, 0 );
  1693. return ret;
  1694. }
  1695. /****************************************************************************
  1696. * x264_encoder_reconfig:
  1697. ****************************************************************************/
  1698. int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
  1699. {
  1700. h = h->thread[h->thread[0]->i_thread_phase];
  1701. x264_param_t param_save = h->reconfig_h->param;
  1702. h->reconfig_h->param = h->param;
  1703. int rc_reconfig;
  1704. int ret = encoder_try_reconfig( h->reconfig_h, param, &rc_reconfig );
  1705. if( !ret )
  1706. h->reconfig = 1;
  1707. else
  1708. h->reconfig_h->param = param_save;
  1709. return ret;
  1710. }
  1711. /****************************************************************************
  1712. * x264_encoder_parameters:
  1713. ****************************************************************************/
  1714. void x264_encoder_parameters( x264_t *h, x264_param_t *param )
  1715. {
  1716. memcpy( param, &h->thread[h->i_thread_phase]->param, sizeof(x264_param_t) );
  1717. }
  1718. /* internal usage */
  1719. static void nal_start( x264_t *h, int i_type, int i_ref_idc )
  1720. {
  1721. x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  1722. nal->i_ref_idc = i_ref_idc;
  1723. nal->i_type = i_type;
  1724. nal->b_long_startcode = 1;
  1725. nal->i_payload= 0;
  1726. nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8];
  1727. nal->i_padding= 0;
  1728. }
  1729. /* if number of allocated nals is not enough, re-allocate a larger one. */
  1730. static int nal_check_buffer( x264_t *h )
  1731. {
  1732. if( h->out.i_nal >= h->out.i_nals_allocated )
  1733. {
  1734. x264_nal_t *new_out = x264_malloc( sizeof(x264_nal_t) * (h->out.i_nals_allocated*2) );
  1735. if( !new_out )
  1736. return -1;
  1737. memcpy( new_out, h->out.nal, sizeof(x264_nal_t) * (h->out.i_nals_allocated) );
  1738. x264_free( h->out.nal );
  1739. h->out.nal = new_out;
  1740. h->out.i_nals_allocated *= 2;
  1741. }
  1742. return 0;
  1743. }
  1744. static int nal_end( x264_t *h )
  1745. {
  1746. x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  1747. uint8_t *end = &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8];
  1748. nal->i_payload = end - nal->p_payload;
  1749. /* Assembly implementation of nal_escape reads past the end of the input.
  1750. * While undefined padding wouldn't actually affect the output, it makes valgrind unhappy. */
  1751. memset( end, 0xff, 64 );
  1752. if( h->param.nalu_process )
  1753. h->param.nalu_process( h, nal, h->fenc->opaque );
  1754. h->out.i_nal++;
  1755. return nal_check_buffer( h );
  1756. }
  1757. static int check_encapsulated_buffer( x264_t *h, x264_t *h0, int start,
  1758. int previous_nal_size, int necessary_size )
  1759. {
  1760. if( h0->nal_buffer_size < necessary_size )
  1761. {
  1762. necessary_size *= 2;
  1763. uint8_t *buf = x264_malloc( necessary_size );
  1764. if( !buf )
  1765. return -1;
  1766. if( previous_nal_size )
  1767. memcpy( buf, h0->nal_buffer, previous_nal_size );
  1768. intptr_t delta = buf - h0->nal_buffer;
  1769. for( int i = 0; i < start; i++ )
  1770. h->out.nal[i].p_payload += delta;
  1771. x264_free( h0->nal_buffer );
  1772. h0->nal_buffer = buf;
  1773. h0->nal_buffer_size = necessary_size;
  1774. }
  1775. return 0;
  1776. }
  1777. static int encoder_encapsulate_nals( x264_t *h, int start )
  1778. {
  1779. x264_t *h0 = h->thread[0];
  1780. int nal_size = 0, previous_nal_size = 0;
  1781. if( h->param.nalu_process )
  1782. {
  1783. for( int i = start; i < h->out.i_nal; i++ )
  1784. nal_size += h->out.nal[i].i_payload;
  1785. return nal_size;
  1786. }
  1787. for( int i = 0; i < start; i++ )
  1788. previous_nal_size += h->out.nal[i].i_payload;
  1789. for( int i = start; i < h->out.i_nal; i++ )
  1790. nal_size += h->out.nal[i].i_payload;
  1791. /* Worst-case NAL unit escaping: reallocate the buffer if it's too small. */
  1792. int necessary_size = previous_nal_size + nal_size * 3/2 + h->out.i_nal * 4 + 4 + 64;
  1793. for( int i = start; i < h->out.i_nal; i++ )
  1794. necessary_size += h->out.nal[i].i_padding;
  1795. if( check_encapsulated_buffer( h, h0, start, previous_nal_size, necessary_size ) )
  1796. return -1;
  1797. uint8_t *nal_buffer = h0->nal_buffer + previous_nal_size;
  1798. for( int i = start; i < h->out.i_nal; i++ )
  1799. {
  1800. h->out.nal[i].b_long_startcode = !i || h->out.nal[i].i_type == NAL_SPS || h->out.nal[i].i_type == NAL_PPS ||
  1801. h->param.i_avcintra_class;
  1802. x264_nal_encode( h, nal_buffer, &h->out.nal[i] );
  1803. nal_buffer += h->out.nal[i].i_payload;
  1804. }
  1805. x264_emms();
  1806. return nal_buffer - (h0->nal_buffer + previous_nal_size);
  1807. }
  1808. /****************************************************************************
  1809. * x264_encoder_headers:
  1810. ****************************************************************************/
  1811. int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
  1812. {
  1813. int frame_size = 0;
  1814. /* init bitstream context */
  1815. h->out.i_nal = 0;
  1816. bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  1817. /* Write SEI, SPS and PPS. */
  1818. /* generate sequence parameters */
  1819. nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  1820. x264_sps_write( &h->out.bs, h->sps );
  1821. if( nal_end( h ) )
  1822. return -1;
  1823. /* generate picture parameters */
  1824. nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1825. x264_pps_write( &h->out.bs, h->sps, h->pps );
  1826. if( nal_end( h ) )
  1827. return -1;
  1828. /* identify ourselves */
  1829. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1830. if( x264_sei_version_write( h, &h->out.bs ) )
  1831. return -1;
  1832. if( nal_end( h ) )
  1833. return -1;
  1834. frame_size = encoder_encapsulate_nals( h, 0 );
  1835. if( frame_size < 0 )
  1836. return -1;
  1837. /* now set output*/
  1838. *pi_nal = h->out.i_nal;
  1839. *pp_nal = &h->out.nal[0];
  1840. h->out.i_nal = 0;
  1841. return frame_size;
  1842. }
  1843. /* Check to see whether we have chosen a reference list ordering different
  1844. * from the standard's default. */
  1845. static inline void reference_check_reorder( x264_t *h )
  1846. {
  1847. /* The reorder check doesn't check for missing frames, so just
  1848. * force a reorder if one of the reference list is corrupt. */
  1849. for( int i = 0; h->frames.reference[i]; i++ )
  1850. if( h->frames.reference[i]->b_corrupt )
  1851. {
  1852. h->b_ref_reorder[0] = 1;
  1853. return;
  1854. }
  1855. for( int list = 0; list <= (h->sh.i_type == SLICE_TYPE_B); list++ )
  1856. for( int i = 0; i < h->i_ref[list] - 1; i++ )
  1857. {
  1858. int framenum_diff = h->fref[list][i+1]->i_frame_num - h->fref[list][i]->i_frame_num;
  1859. int poc_diff = h->fref[list][i+1]->i_poc - h->fref[list][i]->i_poc;
  1860. /* P and B-frames use different default orders. */
  1861. if( h->sh.i_type == SLICE_TYPE_P ? framenum_diff > 0 : list == 1 ? poc_diff < 0 : poc_diff > 0 )
  1862. {
  1863. h->b_ref_reorder[list] = 1;
  1864. return;
  1865. }
  1866. }
  1867. }
  1868. /* return -1 on failure, else return the index of the new reference frame */
  1869. static int weighted_reference_duplicate( x264_t *h, int i_ref, const x264_weight_t *w )
  1870. {
  1871. int i = h->i_ref[0];
  1872. int j = 1;
  1873. x264_frame_t *newframe;
  1874. if( i <= 1 ) /* empty list, definitely can't duplicate frame */
  1875. return -1;
  1876. //Duplication is only used in X264_WEIGHTP_SMART
  1877. if( h->param.analyse.i_weighted_pred != X264_WEIGHTP_SMART )
  1878. return -1;
  1879. /* Duplication is a hack to compensate for crappy rounding in motion compensation.
  1880. * With high bit depth, it's not worth doing, so turn it off except in the case of
  1881. * unweighted dupes. */
  1882. if( BIT_DEPTH > 8 && w != x264_weight_none )
  1883. return -1;
  1884. newframe = x264_frame_pop_blank_unused( h );
  1885. if( !newframe )
  1886. return -1;
  1887. //FIXME: probably don't need to copy everything
  1888. *newframe = *h->fref[0][i_ref];
  1889. newframe->i_reference_count = 1;
  1890. newframe->orig = h->fref[0][i_ref];
  1891. newframe->b_duplicate = 1;
  1892. memcpy( h->fenc->weight[j], w, sizeof(h->fenc->weight[i]) );
  1893. /* shift the frames to make space for the dupe. */
  1894. h->b_ref_reorder[0] = 1;
  1895. if( h->i_ref[0] < X264_REF_MAX )
  1896. ++h->i_ref[0];
  1897. h->fref[0][X264_REF_MAX-1] = NULL;
  1898. x264_frame_unshift( &h->fref[0][j], newframe );
  1899. return j;
  1900. }
  1901. static void weighted_pred_init( x264_t *h )
  1902. {
  1903. /* for now no analysis and set all weights to nothing */
  1904. for( int i_ref = 0; i_ref < h->i_ref[0]; i_ref++ )
  1905. h->fenc->weighted[i_ref] = h->fref[0][i_ref]->filtered[0][0];
  1906. // FIXME: This only supports weighting of one reference frame
  1907. // and duplicates of that frame.
  1908. h->fenc->i_lines_weighted = 0;
  1909. for( int i_ref = 0; i_ref < (h->i_ref[0] << SLICE_MBAFF); i_ref++ )
  1910. for( int i = 0; i < 3; i++ )
  1911. h->sh.weight[i_ref][i].weightfn = NULL;
  1912. if( h->sh.i_type != SLICE_TYPE_P || h->param.analyse.i_weighted_pred <= 0 )
  1913. return;
  1914. int i_padv = PADV << PARAM_INTERLACED;
  1915. int denom = -1;
  1916. int weightplane[2] = { 0, 0 };
  1917. int buffer_next = 0;
  1918. for( int i = 0; i < 3; i++ )
  1919. {
  1920. for( int j = 0; j < h->i_ref[0]; j++ )
  1921. {
  1922. if( h->fenc->weight[j][i].weightfn )
  1923. {
  1924. h->sh.weight[j][i] = h->fenc->weight[j][i];
  1925. // if weight is useless, don't write it to stream
  1926. if( h->sh.weight[j][i].i_scale == 1<<h->sh.weight[j][i].i_denom && h->sh.weight[j][i].i_offset == 0 )
  1927. h->sh.weight[j][i].weightfn = NULL;
  1928. else
  1929. {
  1930. if( !weightplane[!!i] )
  1931. {
  1932. weightplane[!!i] = 1;
  1933. h->sh.weight[0][!!i].i_denom = denom = h->sh.weight[j][i].i_denom;
  1934. assert( x264_clip3( denom, 0, 7 ) == denom );
  1935. }
  1936. assert( h->sh.weight[j][i].i_denom == denom );
  1937. if( !i )
  1938. {
  1939. h->fenc->weighted[j] = h->mb.p_weight_buf[buffer_next++] + h->fenc->i_stride[0] * i_padv + PADH;
  1940. //scale full resolution frame
  1941. if( h->param.i_threads == 1 )
  1942. {
  1943. pixel *src = h->fref[0][j]->filtered[0][0] - h->fref[0][j]->i_stride[0]*i_padv - PADH;
  1944. pixel *dst = h->fenc->weighted[j] - h->fenc->i_stride[0]*i_padv - PADH;
  1945. int stride = h->fenc->i_stride[0];
  1946. int width = h->fenc->i_width[0] + PADH*2;
  1947. int height = h->fenc->i_lines[0] + i_padv*2;
  1948. x264_weight_scale_plane( h, dst, stride, src, stride, width, height, &h->sh.weight[j][0] );
  1949. h->fenc->i_lines_weighted = height;
  1950. }
  1951. }
  1952. }
  1953. }
  1954. }
  1955. }
  1956. if( weightplane[1] )
  1957. for( int i = 0; i < h->i_ref[0]; i++ )
  1958. {
  1959. if( h->sh.weight[i][1].weightfn && !h->sh.weight[i][2].weightfn )
  1960. {
  1961. h->sh.weight[i][2].i_scale = 1 << h->sh.weight[0][1].i_denom;
  1962. h->sh.weight[i][2].i_offset = 0;
  1963. }
  1964. else if( h->sh.weight[i][2].weightfn && !h->sh.weight[i][1].weightfn )
  1965. {
  1966. h->sh.weight[i][1].i_scale = 1 << h->sh.weight[0][1].i_denom;
  1967. h->sh.weight[i][1].i_offset = 0;
  1968. }
  1969. }
  1970. if( !weightplane[0] )
  1971. h->sh.weight[0][0].i_denom = 0;
  1972. if( !weightplane[1] )
  1973. h->sh.weight[0][1].i_denom = 0;
  1974. h->sh.weight[0][2].i_denom = h->sh.weight[0][1].i_denom;
  1975. }
  1976. static inline int reference_distance( x264_t *h, x264_frame_t *frame )
  1977. {
  1978. if( h->param.i_frame_packing == 5 )
  1979. return abs((h->fenc->i_frame&~1) - (frame->i_frame&~1)) +
  1980. ((h->fenc->i_frame&1) != (frame->i_frame&1));
  1981. else
  1982. return abs(h->fenc->i_frame - frame->i_frame);
  1983. }
  1984. static inline void reference_build_list( x264_t *h, int i_poc )
  1985. {
  1986. int b_ok;
  1987. /* build ref list 0/1 */
  1988. h->mb.pic.i_fref[0] = h->i_ref[0] = 0;
  1989. h->mb.pic.i_fref[1] = h->i_ref[1] = 0;
  1990. if( h->sh.i_type == SLICE_TYPE_I )
  1991. return;
  1992. for( int i = 0; h->frames.reference[i]; i++ )
  1993. {
  1994. if( h->frames.reference[i]->b_corrupt )
  1995. continue;
  1996. if( h->frames.reference[i]->i_poc < i_poc )
  1997. h->fref[0][h->i_ref[0]++] = h->frames.reference[i];
  1998. else if( h->frames.reference[i]->i_poc > i_poc )
  1999. h->fref[1][h->i_ref[1]++] = h->frames.reference[i];
  2000. }
  2001. if( h->sh.i_mmco_remove_from_end )
  2002. {
  2003. /* Order ref0 for MMCO remove */
  2004. do
  2005. {
  2006. b_ok = 1;
  2007. for( int i = 0; i < h->i_ref[0] - 1; i++ )
  2008. {
  2009. if( h->fref[0][i]->i_frame < h->fref[0][i+1]->i_frame )
  2010. {
  2011. XCHG( x264_frame_t*, h->fref[0][i], h->fref[0][i+1] );
  2012. b_ok = 0;
  2013. break;
  2014. }
  2015. }
  2016. } while( !b_ok );
  2017. for( int i = h->i_ref[0]-1; i >= h->i_ref[0] - h->sh.i_mmco_remove_from_end; i-- )
  2018. {
  2019. int diff = h->i_frame_num - h->fref[0][i]->i_frame_num;
  2020. h->sh.mmco[h->sh.i_mmco_command_count].i_poc = h->fref[0][i]->i_poc;
  2021. h->sh.mmco[h->sh.i_mmco_command_count++].i_difference_of_pic_nums = diff;
  2022. }
  2023. }
  2024. /* Order reference lists by distance from the current frame. */
  2025. for( int list = 0; list < 2; list++ )
  2026. {
  2027. h->fref_nearest[list] = h->fref[list][0];
  2028. do
  2029. {
  2030. b_ok = 1;
  2031. for( int i = 0; i < h->i_ref[list] - 1; i++ )
  2032. {
  2033. if( list ? h->fref[list][i+1]->i_poc < h->fref_nearest[list]->i_poc
  2034. : h->fref[list][i+1]->i_poc > h->fref_nearest[list]->i_poc )
  2035. h->fref_nearest[list] = h->fref[list][i+1];
  2036. if( reference_distance( h, h->fref[list][i] ) > reference_distance( h, h->fref[list][i+1] ) )
  2037. {
  2038. XCHG( x264_frame_t*, h->fref[list][i], h->fref[list][i+1] );
  2039. b_ok = 0;
  2040. break;
  2041. }
  2042. }
  2043. } while( !b_ok );
  2044. }
  2045. reference_check_reorder( h );
  2046. h->i_ref[1] = X264_MIN( h->i_ref[1], h->frames.i_max_ref1 );
  2047. h->i_ref[0] = X264_MIN( h->i_ref[0], h->frames.i_max_ref0 );
  2048. h->i_ref[0] = X264_MIN( h->i_ref[0], h->param.i_frame_reference ); // if reconfig() has lowered the limit
  2049. /* For Blu-ray compliance, don't reference frames outside of the minigop. */
  2050. if( IS_X264_TYPE_B( h->fenc->i_type ) && h->param.b_bluray_compat )
  2051. h->i_ref[0] = X264_MIN( h->i_ref[0], IS_X264_TYPE_B( h->fref[0][0]->i_type ) + 1 );
  2052. /* add duplicates */
  2053. if( h->fenc->i_type == X264_TYPE_P )
  2054. {
  2055. int idx = -1;
  2056. if( h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
  2057. {
  2058. x264_weight_t w[3];
  2059. w[1].weightfn = w[2].weightfn = NULL;
  2060. if( h->param.rc.b_stat_read )
  2061. x264_ratecontrol_set_weights( h, h->fenc );
  2062. if( !h->fenc->weight[0][0].weightfn )
  2063. {
  2064. h->fenc->weight[0][0].i_denom = 0;
  2065. SET_WEIGHT( w[0], 1, 1, 0, -1 );
  2066. idx = weighted_reference_duplicate( h, 0, w );
  2067. }
  2068. else
  2069. {
  2070. if( h->fenc->weight[0][0].i_scale == 1<<h->fenc->weight[0][0].i_denom )
  2071. {
  2072. SET_WEIGHT( h->fenc->weight[0][0], 1, 1, 0, h->fenc->weight[0][0].i_offset );
  2073. }
  2074. weighted_reference_duplicate( h, 0, x264_weight_none );
  2075. if( h->fenc->weight[0][0].i_offset > -128 )
  2076. {
  2077. w[0] = h->fenc->weight[0][0];
  2078. w[0].i_offset--;
  2079. h->mc.weight_cache( h, &w[0] );
  2080. idx = weighted_reference_duplicate( h, 0, w );
  2081. }
  2082. }
  2083. }
  2084. h->mb.ref_blind_dupe = idx;
  2085. }
  2086. assert( h->i_ref[0] + h->i_ref[1] <= X264_REF_MAX );
  2087. h->mb.pic.i_fref[0] = h->i_ref[0];
  2088. h->mb.pic.i_fref[1] = h->i_ref[1];
  2089. }
  2090. static void fdec_filter_row( x264_t *h, int mb_y, int pass )
  2091. {
  2092. /* mb_y is the mb to be encoded next, not the mb to be filtered here */
  2093. int b_hpel = h->fdec->b_kept_as_ref;
  2094. int b_deblock = h->sh.i_disable_deblocking_filter_idc != 1;
  2095. int b_end = mb_y == h->i_threadslice_end;
  2096. int b_measure_quality = 1;
  2097. int min_y = mb_y - (1 << SLICE_MBAFF);
  2098. int b_start = min_y == h->i_threadslice_start;
  2099. /* Even in interlaced mode, deblocking never modifies more than 4 pixels
  2100. * above each MB, as bS=4 doesn't happen for the top of interlaced mbpairs. */
  2101. int minpix_y = min_y*16 - 4 * !b_start;
  2102. int maxpix_y = mb_y*16 - 4 * !b_end;
  2103. b_deblock &= b_hpel || h->param.b_full_recon || h->param.psz_dump_yuv;
  2104. if( h->param.b_sliced_threads )
  2105. {
  2106. switch( pass )
  2107. {
  2108. /* During encode: only do deblock if asked for */
  2109. default:
  2110. case 0:
  2111. b_deblock &= h->param.b_full_recon;
  2112. b_hpel = 0;
  2113. break;
  2114. /* During post-encode pass: do deblock if not done yet, do hpel for all
  2115. * rows except those between slices. */
  2116. case 1:
  2117. b_deblock &= !h->param.b_full_recon;
  2118. b_hpel &= !(b_start && min_y > 0);
  2119. b_measure_quality = 0;
  2120. break;
  2121. /* Final pass: do the rows between slices in sequence. */
  2122. case 2:
  2123. b_deblock = 0;
  2124. b_measure_quality = 0;
  2125. break;
  2126. }
  2127. }
  2128. if( mb_y & SLICE_MBAFF )
  2129. return;
  2130. if( min_y < h->i_threadslice_start )
  2131. return;
  2132. if( b_deblock )
  2133. for( int y = min_y; y < mb_y; y += (1 << SLICE_MBAFF) )
  2134. x264_frame_deblock_row( h, y );
  2135. /* FIXME: Prediction requires different borders for interlaced/progressive mc,
  2136. * but the actual image data is equivalent. For now, maintain this
  2137. * consistency by copying deblocked pixels between planes. */
  2138. if( PARAM_INTERLACED && (!h->param.b_sliced_threads || pass == 1) )
  2139. for( int p = 0; p < h->fdec->i_plane; p++ )
  2140. for( int i = minpix_y>>(CHROMA_V_SHIFT && p); i < maxpix_y>>(CHROMA_V_SHIFT && p); i++ )
  2141. memcpy( h->fdec->plane_fld[p] + i*h->fdec->i_stride[p],
  2142. h->fdec->plane[p] + i*h->fdec->i_stride[p],
  2143. h->mb.i_mb_width*16*sizeof(pixel) );
  2144. if( h->fdec->b_kept_as_ref && (!h->param.b_sliced_threads || pass == 1) )
  2145. x264_frame_expand_border( h, h->fdec, min_y );
  2146. if( b_hpel )
  2147. {
  2148. int end = mb_y == h->mb.i_mb_height;
  2149. /* Can't do hpel until the previous slice is done encoding. */
  2150. if( h->param.analyse.i_subpel_refine )
  2151. {
  2152. x264_frame_filter( h, h->fdec, min_y, end );
  2153. x264_frame_expand_border_filtered( h, h->fdec, min_y, end );
  2154. }
  2155. }
  2156. if( SLICE_MBAFF && pass == 0 )
  2157. for( int i = 0; i < 3; i++ )
  2158. {
  2159. XCHG( pixel *, h->intra_border_backup[0][i], h->intra_border_backup[3][i] );
  2160. XCHG( pixel *, h->intra_border_backup[1][i], h->intra_border_backup[4][i] );
  2161. }
  2162. if( h->i_thread_frames > 1 && h->fdec->b_kept_as_ref )
  2163. x264_frame_cond_broadcast( h->fdec, mb_y*16 + (b_end ? 10000 : -(X264_THREAD_HEIGHT << SLICE_MBAFF)) );
  2164. if( b_measure_quality )
  2165. {
  2166. maxpix_y = X264_MIN( maxpix_y, h->param.i_height );
  2167. if( h->param.analyse.b_psnr )
  2168. {
  2169. for( int p = 0; p < (CHROMA444 ? 3 : 1); p++ )
  2170. h->stat.frame.i_ssd[p] += x264_pixel_ssd_wxh( &h->pixf,
  2171. h->fdec->plane[p] + minpix_y * h->fdec->i_stride[p], h->fdec->i_stride[p],
  2172. h->fenc->plane[p] + minpix_y * h->fenc->i_stride[p], h->fenc->i_stride[p],
  2173. h->param.i_width, maxpix_y-minpix_y );
  2174. if( !CHROMA444 )
  2175. {
  2176. uint64_t ssd_u, ssd_v;
  2177. int v_shift = CHROMA_V_SHIFT;
  2178. x264_pixel_ssd_nv12( &h->pixf,
  2179. h->fdec->plane[1] + (minpix_y>>v_shift) * h->fdec->i_stride[1], h->fdec->i_stride[1],
  2180. h->fenc->plane[1] + (minpix_y>>v_shift) * h->fenc->i_stride[1], h->fenc->i_stride[1],
  2181. h->param.i_width>>1, (maxpix_y-minpix_y)>>v_shift, &ssd_u, &ssd_v );
  2182. h->stat.frame.i_ssd[1] += ssd_u;
  2183. h->stat.frame.i_ssd[2] += ssd_v;
  2184. }
  2185. }
  2186. if( h->param.analyse.b_ssim )
  2187. {
  2188. int ssim_cnt;
  2189. x264_emms();
  2190. /* offset by 2 pixels to avoid alignment of ssim blocks with dct blocks,
  2191. * and overlap by 4 */
  2192. minpix_y += b_start ? 2 : -6;
  2193. h->stat.frame.f_ssim +=
  2194. x264_pixel_ssim_wxh( &h->pixf,
  2195. h->fdec->plane[0] + 2+minpix_y*h->fdec->i_stride[0], h->fdec->i_stride[0],
  2196. h->fenc->plane[0] + 2+minpix_y*h->fenc->i_stride[0], h->fenc->i_stride[0],
  2197. h->param.i_width-2, maxpix_y-minpix_y, h->scratch_buffer, &ssim_cnt );
  2198. h->stat.frame.i_ssim_cnt += ssim_cnt;
  2199. }
  2200. }
  2201. }
  2202. static inline int reference_update( x264_t *h )
  2203. {
  2204. if( !h->fdec->b_kept_as_ref )
  2205. {
  2206. if( h->i_thread_frames > 1 )
  2207. {
  2208. x264_frame_push_unused( h, h->fdec );
  2209. h->fdec = x264_frame_pop_unused( h, 1 );
  2210. if( !h->fdec )
  2211. return -1;
  2212. }
  2213. return 0;
  2214. }
  2215. /* apply mmco from previous frame. */
  2216. for( int i = 0; i < h->sh.i_mmco_command_count; i++ )
  2217. for( int j = 0; h->frames.reference[j]; j++ )
  2218. if( h->frames.reference[j]->i_poc == h->sh.mmco[i].i_poc )
  2219. x264_frame_push_unused( h, x264_frame_shift( &h->frames.reference[j] ) );
  2220. /* move frame in the buffer */
  2221. x264_frame_push( h->frames.reference, h->fdec );
  2222. if( h->frames.reference[h->sps->i_num_ref_frames] )
  2223. x264_frame_push_unused( h, x264_frame_shift( h->frames.reference ) );
  2224. h->fdec = x264_frame_pop_unused( h, 1 );
  2225. if( !h->fdec )
  2226. return -1;
  2227. return 0;
  2228. }
  2229. static inline void reference_reset( x264_t *h )
  2230. {
  2231. while( h->frames.reference[0] )
  2232. x264_frame_push_unused( h, x264_frame_pop( h->frames.reference ) );
  2233. h->fdec->i_poc =
  2234. h->fenc->i_poc = 0;
  2235. }
  2236. static inline void reference_hierarchy_reset( x264_t *h )
  2237. {
  2238. int ref;
  2239. int b_hasdelayframe = 0;
  2240. /* look for delay frames -- chain must only contain frames that are disposable */
  2241. for( int i = 0; h->frames.current[i] && IS_DISPOSABLE( h->frames.current[i]->i_type ); i++ )
  2242. b_hasdelayframe |= h->frames.current[i]->i_coded
  2243. != h->frames.current[i]->i_frame + h->sps->vui.i_num_reorder_frames;
  2244. /* This function must handle b-pyramid and clear frames for open-gop */
  2245. if( h->param.i_bframe_pyramid != X264_B_PYRAMID_STRICT && !b_hasdelayframe && h->frames.i_poc_last_open_gop == -1 )
  2246. return;
  2247. /* Remove last BREF. There will never be old BREFs in the
  2248. * dpb during a BREF decode when pyramid == STRICT */
  2249. for( ref = 0; h->frames.reference[ref]; ref++ )
  2250. {
  2251. if( ( h->param.i_bframe_pyramid == X264_B_PYRAMID_STRICT
  2252. && h->frames.reference[ref]->i_type == X264_TYPE_BREF )
  2253. || ( h->frames.reference[ref]->i_poc < h->frames.i_poc_last_open_gop
  2254. && h->sh.i_type != SLICE_TYPE_B ) )
  2255. {
  2256. int diff = h->i_frame_num - h->frames.reference[ref]->i_frame_num;
  2257. h->sh.mmco[h->sh.i_mmco_command_count].i_difference_of_pic_nums = diff;
  2258. h->sh.mmco[h->sh.i_mmco_command_count++].i_poc = h->frames.reference[ref]->i_poc;
  2259. x264_frame_push_unused( h, x264_frame_shift( &h->frames.reference[ref] ) );
  2260. h->b_ref_reorder[0] = 1;
  2261. ref--;
  2262. }
  2263. }
  2264. /* Prepare room in the dpb for the delayed display time of the later b-frame's */
  2265. if( h->param.i_bframe_pyramid )
  2266. h->sh.i_mmco_remove_from_end = X264_MAX( ref + 2 - h->frames.i_max_dpb, 0 );
  2267. }
  2268. static inline void slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  2269. {
  2270. /* ------------------------ Create slice header ----------------------- */
  2271. if( i_nal_type == NAL_SLICE_IDR )
  2272. {
  2273. slice_header_init( h, &h->sh, h->sps, h->pps, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
  2274. /* alternate id */
  2275. if( h->param.i_avcintra_class )
  2276. {
  2277. switch( h->i_idr_pic_id )
  2278. {
  2279. case 5:
  2280. h->i_idr_pic_id = 3;
  2281. break;
  2282. case 3:
  2283. h->i_idr_pic_id = 4;
  2284. break;
  2285. case 4:
  2286. default:
  2287. h->i_idr_pic_id = 5;
  2288. break;
  2289. }
  2290. }
  2291. else
  2292. h->i_idr_pic_id ^= 1;
  2293. }
  2294. else
  2295. {
  2296. slice_header_init( h, &h->sh, h->sps, h->pps, -1, h->i_frame_num, i_global_qp );
  2297. h->sh.i_num_ref_idx_l0_active = h->i_ref[0] <= 0 ? 1 : h->i_ref[0];
  2298. h->sh.i_num_ref_idx_l1_active = h->i_ref[1] <= 0 ? 1 : h->i_ref[1];
  2299. if( h->sh.i_num_ref_idx_l0_active != h->pps->i_num_ref_idx_l0_default_active ||
  2300. (h->sh.i_type == SLICE_TYPE_B && h->sh.i_num_ref_idx_l1_active != h->pps->i_num_ref_idx_l1_default_active) )
  2301. {
  2302. h->sh.b_num_ref_idx_override = 1;
  2303. }
  2304. }
  2305. if( h->fenc->i_type == X264_TYPE_BREF && h->param.b_bluray_compat && h->sh.i_mmco_command_count )
  2306. {
  2307. h->b_sh_backup = 1;
  2308. h->sh_backup = h->sh;
  2309. }
  2310. h->fdec->i_frame_num = h->sh.i_frame_num;
  2311. if( h->sps->i_poc_type == 0 )
  2312. {
  2313. h->sh.i_poc = h->fdec->i_poc;
  2314. if( PARAM_INTERLACED )
  2315. {
  2316. h->sh.i_delta_poc_bottom = h->param.b_tff ? 1 : -1;
  2317. h->sh.i_poc += h->sh.i_delta_poc_bottom == -1;
  2318. }
  2319. else
  2320. h->sh.i_delta_poc_bottom = 0;
  2321. h->fdec->i_delta_poc[0] = h->sh.i_delta_poc_bottom == -1;
  2322. h->fdec->i_delta_poc[1] = h->sh.i_delta_poc_bottom == 1;
  2323. }
  2324. else
  2325. {
  2326. /* Nothing to do ? */
  2327. }
  2328. x264_macroblock_slice_init( h );
  2329. }
  2330. typedef struct
  2331. {
  2332. int skip;
  2333. uint8_t cabac_prevbyte;
  2334. bs_t bs;
  2335. x264_cabac_t cabac;
  2336. x264_frame_stat_t stat;
  2337. int last_qp;
  2338. int last_dqp;
  2339. int field_decoding_flag;
  2340. } x264_bs_bak_t;
  2341. static ALWAYS_INLINE void bitstream_backup( x264_t *h, x264_bs_bak_t *bak, int i_skip, int full )
  2342. {
  2343. if( full )
  2344. {
  2345. bak->stat = h->stat.frame;
  2346. bak->last_qp = h->mb.i_last_qp;
  2347. bak->last_dqp = h->mb.i_last_dqp;
  2348. bak->field_decoding_flag = h->mb.field_decoding_flag;
  2349. }
  2350. else
  2351. {
  2352. bak->stat.i_mv_bits = h->stat.frame.i_mv_bits;
  2353. bak->stat.i_tex_bits = h->stat.frame.i_tex_bits;
  2354. }
  2355. /* In the per-MB backup, we don't need the contexts because flushing the CABAC
  2356. * encoder has no context dependency and in this case, a slice is ended (and
  2357. * thus the content of all contexts are thrown away). */
  2358. if( h->param.b_cabac )
  2359. {
  2360. if( full )
  2361. memcpy( &bak->cabac, &h->cabac, sizeof(x264_cabac_t) );
  2362. else
  2363. memcpy( &bak->cabac, &h->cabac, offsetof(x264_cabac_t, f8_bits_encoded) );
  2364. /* x264's CABAC writer modifies the previous byte during carry, so it has to be
  2365. * backed up. */
  2366. bak->cabac_prevbyte = h->cabac.p[-1];
  2367. }
  2368. else
  2369. {
  2370. bak->bs = h->out.bs;
  2371. bak->skip = i_skip;
  2372. }
  2373. }
  2374. static ALWAYS_INLINE void bitstream_restore( x264_t *h, x264_bs_bak_t *bak, int *skip, int full )
  2375. {
  2376. if( full )
  2377. {
  2378. h->stat.frame = bak->stat;
  2379. h->mb.i_last_qp = bak->last_qp;
  2380. h->mb.i_last_dqp = bak->last_dqp;
  2381. h->mb.field_decoding_flag = bak->field_decoding_flag;
  2382. }
  2383. else
  2384. {
  2385. h->stat.frame.i_mv_bits = bak->stat.i_mv_bits;
  2386. h->stat.frame.i_tex_bits = bak->stat.i_tex_bits;
  2387. }
  2388. if( h->param.b_cabac )
  2389. {
  2390. if( full )
  2391. memcpy( &h->cabac, &bak->cabac, sizeof(x264_cabac_t) );
  2392. else
  2393. memcpy( &h->cabac, &bak->cabac, offsetof(x264_cabac_t, f8_bits_encoded) );
  2394. h->cabac.p[-1] = bak->cabac_prevbyte;
  2395. }
  2396. else
  2397. {
  2398. h->out.bs = bak->bs;
  2399. *skip = bak->skip;
  2400. }
  2401. }
  2402. static intptr_t slice_write( x264_t *h )
  2403. {
  2404. int i_skip;
  2405. int mb_xy, i_mb_x, i_mb_y;
  2406. /* NALUs other than the first use a 3-byte startcode.
  2407. * Add one extra byte for the rbsp, and one more for the final CABAC putbyte.
  2408. * Then add an extra 5 bytes just in case, to account for random NAL escapes and
  2409. * other inaccuracies. */
  2410. int overhead_guess = (NALU_OVERHEAD - (h->param.b_annexb && h->out.i_nal)) + 1 + h->param.b_cabac + 5;
  2411. int slice_max_size = h->param.i_slice_max_size > 0 ? (h->param.i_slice_max_size-overhead_guess)*8 : 0;
  2412. int back_up_bitstream_cavlc = !h->param.b_cabac && h->sps->i_profile_idc < PROFILE_HIGH;
  2413. int back_up_bitstream = slice_max_size || back_up_bitstream_cavlc;
  2414. int starting_bits = bs_pos(&h->out.bs);
  2415. int b_deblock = h->sh.i_disable_deblocking_filter_idc != 1;
  2416. int b_hpel = h->fdec->b_kept_as_ref;
  2417. int orig_last_mb = h->sh.i_last_mb;
  2418. int thread_last_mb = h->i_threadslice_end * h->mb.i_mb_width - 1;
  2419. uint8_t *last_emu_check;
  2420. #define BS_BAK_SLICE_MAX_SIZE 0
  2421. #define BS_BAK_CAVLC_OVERFLOW 1
  2422. #define BS_BAK_SLICE_MIN_MBS 2
  2423. #define BS_BAK_ROW_VBV 3
  2424. x264_bs_bak_t bs_bak[4];
  2425. b_deblock &= b_hpel || h->param.b_full_recon || h->param.psz_dump_yuv;
  2426. bs_realign( &h->out.bs );
  2427. /* Slice */
  2428. nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  2429. h->out.nal[h->out.i_nal].i_first_mb = h->sh.i_first_mb;
  2430. /* Slice header */
  2431. x264_macroblock_thread_init( h );
  2432. /* Set the QP equal to the first QP in the slice for more accurate CABAC initialization. */
  2433. h->mb.i_mb_xy = h->sh.i_first_mb;
  2434. h->sh.i_qp = x264_ratecontrol_mb_qp( h );
  2435. h->sh.i_qp = SPEC_QP( h->sh.i_qp );
  2436. h->sh.i_qp_delta = h->sh.i_qp - h->pps->i_pic_init_qp;
  2437. slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
  2438. if( h->param.b_cabac )
  2439. {
  2440. /* alignment needed */
  2441. bs_align_1( &h->out.bs );
  2442. /* init cabac */
  2443. x264_cabac_context_init( h, &h->cabac, h->sh.i_type, x264_clip3( h->sh.i_qp-QP_BD_OFFSET, 0, 51 ), h->sh.i_cabac_init_idc );
  2444. x264_cabac_encode_init ( &h->cabac, h->out.bs.p, h->out.bs.p_end );
  2445. last_emu_check = h->cabac.p;
  2446. }
  2447. else
  2448. last_emu_check = h->out.bs.p;
  2449. h->mb.i_last_qp = h->sh.i_qp;
  2450. h->mb.i_last_dqp = 0;
  2451. h->mb.field_decoding_flag = 0;
  2452. i_mb_y = h->sh.i_first_mb / h->mb.i_mb_width;
  2453. i_mb_x = h->sh.i_first_mb % h->mb.i_mb_width;
  2454. i_skip = 0;
  2455. while( 1 )
  2456. {
  2457. mb_xy = i_mb_x + i_mb_y * h->mb.i_mb_width;
  2458. int mb_spos = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
  2459. if( i_mb_x == 0 )
  2460. {
  2461. if( bitstream_check_buffer( h ) )
  2462. return -1;
  2463. if( !(i_mb_y & SLICE_MBAFF) && h->param.rc.i_vbv_buffer_size )
  2464. bitstream_backup( h, &bs_bak[BS_BAK_ROW_VBV], i_skip, 1 );
  2465. if( !h->mb.b_reencode_mb )
  2466. fdec_filter_row( h, i_mb_y, 0 );
  2467. }
  2468. if( back_up_bitstream )
  2469. {
  2470. if( back_up_bitstream_cavlc )
  2471. bitstream_backup( h, &bs_bak[BS_BAK_CAVLC_OVERFLOW], i_skip, 0 );
  2472. if( slice_max_size && !(i_mb_y & SLICE_MBAFF) )
  2473. {
  2474. bitstream_backup( h, &bs_bak[BS_BAK_SLICE_MAX_SIZE], i_skip, 0 );
  2475. if( (thread_last_mb+1-mb_xy) == h->param.i_slice_min_mbs )
  2476. bitstream_backup( h, &bs_bak[BS_BAK_SLICE_MIN_MBS], i_skip, 0 );
  2477. }
  2478. }
  2479. if( PARAM_INTERLACED )
  2480. {
  2481. if( h->mb.b_adaptive_mbaff )
  2482. {
  2483. if( !(i_mb_y&1) )
  2484. {
  2485. /* FIXME: VSAD is fast but fairly poor at choosing the best interlace type. */
  2486. h->mb.b_interlaced = x264_field_vsad( h, i_mb_x, i_mb_y );
  2487. memcpy( &h->zigzagf, MB_INTERLACED ? &h->zigzagf_interlaced : &h->zigzagf_progressive, sizeof(h->zigzagf) );
  2488. if( !MB_INTERLACED && (i_mb_y+2) == h->mb.i_mb_height )
  2489. x264_expand_border_mbpair( h, i_mb_x, i_mb_y );
  2490. }
  2491. }
  2492. h->mb.field[mb_xy] = MB_INTERLACED;
  2493. }
  2494. /* load cache */
  2495. if( SLICE_MBAFF )
  2496. x264_macroblock_cache_load_interlaced( h, i_mb_x, i_mb_y );
  2497. else
  2498. x264_macroblock_cache_load_progressive( h, i_mb_x, i_mb_y );
  2499. x264_macroblock_analyse( h );
  2500. /* encode this macroblock -> be careful it can change the mb type to P_SKIP if needed */
  2501. reencode:
  2502. x264_macroblock_encode( h );
  2503. if( h->param.b_cabac )
  2504. {
  2505. if( mb_xy > h->sh.i_first_mb && !(SLICE_MBAFF && (i_mb_y&1)) )
  2506. x264_cabac_encode_terminal( &h->cabac );
  2507. if( IS_SKIP( h->mb.i_type ) )
  2508. x264_cabac_mb_skip( h, 1 );
  2509. else
  2510. {
  2511. if( h->sh.i_type != SLICE_TYPE_I )
  2512. x264_cabac_mb_skip( h, 0 );
  2513. x264_macroblock_write_cabac( h, &h->cabac );
  2514. }
  2515. }
  2516. else
  2517. {
  2518. if( IS_SKIP( h->mb.i_type ) )
  2519. i_skip++;
  2520. else
  2521. {
  2522. if( h->sh.i_type != SLICE_TYPE_I )
  2523. {
  2524. bs_write_ue( &h->out.bs, i_skip ); /* skip run */
  2525. i_skip = 0;
  2526. }
  2527. x264_macroblock_write_cavlc( h );
  2528. /* If there was a CAVLC level code overflow, try again at a higher QP. */
  2529. if( h->mb.b_overflow )
  2530. {
  2531. h->mb.i_chroma_qp = h->chroma_qp_table[++h->mb.i_qp];
  2532. h->mb.i_skip_intra = 0;
  2533. h->mb.b_skip_mc = 0;
  2534. h->mb.b_overflow = 0;
  2535. bitstream_restore( h, &bs_bak[BS_BAK_CAVLC_OVERFLOW], &i_skip, 0 );
  2536. goto reencode;
  2537. }
  2538. }
  2539. }
  2540. int total_bits = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
  2541. int mb_size = total_bits - mb_spos;
  2542. if( slice_max_size && (!SLICE_MBAFF || (i_mb_y&1)) )
  2543. {
  2544. /* Count the skip run, just in case. */
  2545. if( !h->param.b_cabac )
  2546. total_bits += bs_size_ue_big( i_skip );
  2547. /* Check for escape bytes. */
  2548. uint8_t *end = h->param.b_cabac ? h->cabac.p : h->out.bs.p;
  2549. for( ; last_emu_check < end - 2; last_emu_check++ )
  2550. if( last_emu_check[0] == 0 && last_emu_check[1] == 0 && last_emu_check[2] <= 3 )
  2551. {
  2552. slice_max_size -= 8;
  2553. last_emu_check++;
  2554. }
  2555. /* We'll just re-encode this last macroblock if we go over the max slice size. */
  2556. if( total_bits - starting_bits > slice_max_size && !h->mb.b_reencode_mb )
  2557. {
  2558. if( !x264_frame_new_slice( h, h->fdec ) )
  2559. {
  2560. /* Handle the most obnoxious slice-min-mbs edge case: we need to end the slice
  2561. * because it's gone over the maximum size, but doing so would violate slice-min-mbs.
  2562. * If possible, roll back to the last checkpoint and try again.
  2563. * We could try raising QP, but that would break in the case where a slice spans multiple
  2564. * rows, which the re-encoding infrastructure can't currently handle. */
  2565. if( mb_xy <= thread_last_mb && (thread_last_mb+1-mb_xy) < h->param.i_slice_min_mbs )
  2566. {
  2567. if( thread_last_mb-h->param.i_slice_min_mbs < h->sh.i_first_mb+h->param.i_slice_min_mbs )
  2568. {
  2569. x264_log( h, X264_LOG_WARNING, "slice-max-size violated (frame %d, cause: slice-min-mbs)\n", h->i_frame );
  2570. slice_max_size = 0;
  2571. goto cont;
  2572. }
  2573. bitstream_restore( h, &bs_bak[BS_BAK_SLICE_MIN_MBS], &i_skip, 0 );
  2574. h->mb.b_reencode_mb = 1;
  2575. h->sh.i_last_mb = thread_last_mb-h->param.i_slice_min_mbs;
  2576. break;
  2577. }
  2578. if( mb_xy-SLICE_MBAFF*h->mb.i_mb_stride != h->sh.i_first_mb )
  2579. {
  2580. bitstream_restore( h, &bs_bak[BS_BAK_SLICE_MAX_SIZE], &i_skip, 0 );
  2581. h->mb.b_reencode_mb = 1;
  2582. if( SLICE_MBAFF )
  2583. {
  2584. // set to bottom of previous mbpair
  2585. if( i_mb_x )
  2586. h->sh.i_last_mb = mb_xy-1+h->mb.i_mb_stride*(!(i_mb_y&1));
  2587. else
  2588. h->sh.i_last_mb = (i_mb_y-2+!(i_mb_y&1))*h->mb.i_mb_stride + h->mb.i_mb_width - 1;
  2589. }
  2590. else
  2591. h->sh.i_last_mb = mb_xy-1;
  2592. break;
  2593. }
  2594. else
  2595. h->sh.i_last_mb = mb_xy;
  2596. }
  2597. else
  2598. slice_max_size = 0;
  2599. }
  2600. }
  2601. cont:
  2602. h->mb.b_reencode_mb = 0;
  2603. /* save cache */
  2604. x264_macroblock_cache_save( h );
  2605. if( x264_ratecontrol_mb( h, mb_size ) < 0 )
  2606. {
  2607. bitstream_restore( h, &bs_bak[BS_BAK_ROW_VBV], &i_skip, 1 );
  2608. h->mb.b_reencode_mb = 1;
  2609. i_mb_x = 0;
  2610. i_mb_y = i_mb_y - SLICE_MBAFF;
  2611. h->mb.i_mb_prev_xy = i_mb_y * h->mb.i_mb_stride - 1;
  2612. h->sh.i_last_mb = orig_last_mb;
  2613. continue;
  2614. }
  2615. /* accumulate mb stats */
  2616. h->stat.frame.i_mb_count[h->mb.i_type]++;
  2617. int b_intra = IS_INTRA( h->mb.i_type );
  2618. int b_skip = IS_SKIP( h->mb.i_type );
  2619. if( h->param.i_log_level >= X264_LOG_INFO || h->param.rc.b_stat_write )
  2620. {
  2621. if( !b_intra && !b_skip && !IS_DIRECT( h->mb.i_type ) )
  2622. {
  2623. if( h->mb.i_partition != D_8x8 )
  2624. h->stat.frame.i_mb_partition[h->mb.i_partition] += 4;
  2625. else
  2626. for( int i = 0; i < 4; i++ )
  2627. h->stat.frame.i_mb_partition[h->mb.i_sub_partition[i]] ++;
  2628. if( h->param.i_frame_reference > 1 )
  2629. for( int i_list = 0; i_list <= (h->sh.i_type == SLICE_TYPE_B); i_list++ )
  2630. for( int i = 0; i < 4; i++ )
  2631. {
  2632. int i_ref = h->mb.cache.ref[i_list][ x264_scan8[4*i] ];
  2633. if( i_ref >= 0 )
  2634. h->stat.frame.i_mb_count_ref[i_list][i_ref] ++;
  2635. }
  2636. }
  2637. }
  2638. if( h->param.i_log_level >= X264_LOG_INFO )
  2639. {
  2640. if( h->mb.i_cbp_luma | h->mb.i_cbp_chroma )
  2641. {
  2642. if( CHROMA444 )
  2643. {
  2644. for( int i = 0; i < 4; i++ )
  2645. if( h->mb.i_cbp_luma & (1 << i) )
  2646. for( int p = 0; p < 3; p++ )
  2647. {
  2648. int s8 = i*4+p*16;
  2649. int nnz8x8 = M16( &h->mb.cache.non_zero_count[x264_scan8[s8]+0] )
  2650. | M16( &h->mb.cache.non_zero_count[x264_scan8[s8]+8] );
  2651. h->stat.frame.i_mb_cbp[!b_intra + p*2] += !!nnz8x8;
  2652. }
  2653. }
  2654. else
  2655. {
  2656. int cbpsum = (h->mb.i_cbp_luma&1) + ((h->mb.i_cbp_luma>>1)&1)
  2657. + ((h->mb.i_cbp_luma>>2)&1) + (h->mb.i_cbp_luma>>3);
  2658. h->stat.frame.i_mb_cbp[!b_intra + 0] += cbpsum;
  2659. h->stat.frame.i_mb_cbp[!b_intra + 2] += !!h->mb.i_cbp_chroma;
  2660. h->stat.frame.i_mb_cbp[!b_intra + 4] += h->mb.i_cbp_chroma >> 1;
  2661. }
  2662. }
  2663. if( h->mb.i_cbp_luma && !b_intra )
  2664. {
  2665. h->stat.frame.i_mb_count_8x8dct[0] ++;
  2666. h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
  2667. }
  2668. if( b_intra && h->mb.i_type != I_PCM )
  2669. {
  2670. if( h->mb.i_type == I_16x16 )
  2671. h->stat.frame.i_mb_pred_mode[0][h->mb.i_intra16x16_pred_mode]++;
  2672. else if( h->mb.i_type == I_8x8 )
  2673. for( int i = 0; i < 16; i += 4 )
  2674. h->stat.frame.i_mb_pred_mode[1][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
  2675. else //if( h->mb.i_type == I_4x4 )
  2676. for( int i = 0; i < 16; i++ )
  2677. h->stat.frame.i_mb_pred_mode[2][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
  2678. h->stat.frame.i_mb_pred_mode[3][x264_mb_chroma_pred_mode_fix[h->mb.i_chroma_pred_mode]]++;
  2679. }
  2680. h->stat.frame.i_mb_field[b_intra?0:b_skip?2:1] += MB_INTERLACED;
  2681. }
  2682. /* calculate deblock strength values (actual deblocking is done per-row along with hpel) */
  2683. if( b_deblock )
  2684. x264_macroblock_deblock_strength( h );
  2685. if( mb_xy == h->sh.i_last_mb )
  2686. break;
  2687. if( SLICE_MBAFF )
  2688. {
  2689. i_mb_x += i_mb_y & 1;
  2690. i_mb_y ^= i_mb_x < h->mb.i_mb_width;
  2691. }
  2692. else
  2693. i_mb_x++;
  2694. if( i_mb_x == h->mb.i_mb_width )
  2695. {
  2696. i_mb_y++;
  2697. i_mb_x = 0;
  2698. }
  2699. }
  2700. if( h->sh.i_last_mb < h->sh.i_first_mb )
  2701. return 0;
  2702. h->out.nal[h->out.i_nal].i_last_mb = h->sh.i_last_mb;
  2703. if( h->param.b_cabac )
  2704. {
  2705. x264_cabac_encode_flush( h, &h->cabac );
  2706. h->out.bs.p = h->cabac.p;
  2707. }
  2708. else
  2709. {
  2710. if( i_skip > 0 )
  2711. bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
  2712. /* rbsp_slice_trailing_bits */
  2713. bs_rbsp_trailing( &h->out.bs );
  2714. bs_flush( &h->out.bs );
  2715. }
  2716. if( nal_end( h ) )
  2717. return -1;
  2718. if( h->sh.i_last_mb == (h->i_threadslice_end * h->mb.i_mb_width - 1) )
  2719. {
  2720. h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
  2721. + (h->out.i_nal*NALU_OVERHEAD * 8)
  2722. - h->stat.frame.i_tex_bits
  2723. - h->stat.frame.i_mv_bits;
  2724. fdec_filter_row( h, h->i_threadslice_end, 0 );
  2725. if( h->param.b_sliced_threads )
  2726. {
  2727. /* Tell the main thread we're done. */
  2728. x264_threadslice_cond_broadcast( h, 1 );
  2729. /* Do hpel now */
  2730. for( int mb_y = h->i_threadslice_start; mb_y <= h->i_threadslice_end; mb_y++ )
  2731. fdec_filter_row( h, mb_y, 1 );
  2732. x264_threadslice_cond_broadcast( h, 2 );
  2733. /* Do the first row of hpel, now that the previous slice is done */
  2734. if( h->i_thread_idx > 0 )
  2735. {
  2736. x264_threadslice_cond_wait( h->thread[h->i_thread_idx-1], 2 );
  2737. fdec_filter_row( h, h->i_threadslice_start + (1 << SLICE_MBAFF), 2 );
  2738. }
  2739. }
  2740. /* Free mb info after the last thread's done using it */
  2741. if( h->fdec->mb_info_free && (!h->param.b_sliced_threads || h->i_thread_idx == (h->param.i_threads-1)) )
  2742. {
  2743. h->fdec->mb_info_free( h->fdec->mb_info );
  2744. h->fdec->mb_info = NULL;
  2745. h->fdec->mb_info_free = NULL;
  2746. }
  2747. }
  2748. return 0;
  2749. }
  2750. static void thread_sync_context( x264_t *dst, x264_t *src )
  2751. {
  2752. if( dst == src )
  2753. return;
  2754. // reference counting
  2755. for( x264_frame_t **f = src->frames.reference; *f; f++ )
  2756. (*f)->i_reference_count++;
  2757. for( x264_frame_t **f = dst->frames.reference; *f; f++ )
  2758. x264_frame_push_unused( src, *f );
  2759. src->fdec->i_reference_count++;
  2760. x264_frame_push_unused( src, dst->fdec );
  2761. // copy everything except the per-thread pointers and the constants.
  2762. memcpy( &dst->i_frame, &src->i_frame, offsetof(x264_t, mb.base) - offsetof(x264_t, i_frame) );
  2763. dst->param = src->param;
  2764. dst->stat = src->stat;
  2765. dst->pixf = src->pixf;
  2766. dst->reconfig = src->reconfig;
  2767. }
  2768. static void thread_sync_stat( x264_t *dst, x264_t *src )
  2769. {
  2770. if( dst != src )
  2771. memcpy( &dst->stat, &src->stat, offsetof(x264_t, stat.frame) - offsetof(x264_t, stat) );
  2772. }
  2773. static void *slices_write( x264_t *h )
  2774. {
  2775. int i_slice_num = 0;
  2776. int last_thread_mb = h->sh.i_last_mb;
  2777. int round_bias = h->param.i_avcintra_class ? 0 : h->param.i_slice_count/2;
  2778. /* init stats */
  2779. memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
  2780. h->mb.b_reencode_mb = 0;
  2781. while( h->sh.i_first_mb + SLICE_MBAFF*h->mb.i_mb_stride <= last_thread_mb )
  2782. {
  2783. h->sh.i_last_mb = last_thread_mb;
  2784. if( !i_slice_num || !x264_frame_new_slice( h, h->fdec ) )
  2785. {
  2786. if( h->param.i_slice_max_mbs )
  2787. {
  2788. if( SLICE_MBAFF )
  2789. {
  2790. // convert first to mbaff form, add slice-max-mbs, then convert back to normal form
  2791. int last_mbaff = 2*(h->sh.i_first_mb % h->mb.i_mb_width)
  2792. + h->mb.i_mb_width*(h->sh.i_first_mb / h->mb.i_mb_width)
  2793. + h->param.i_slice_max_mbs - 1;
  2794. int last_x = (last_mbaff % (2*h->mb.i_mb_width))/2;
  2795. int last_y = (last_mbaff / (2*h->mb.i_mb_width))*2 + 1;
  2796. h->sh.i_last_mb = last_x + h->mb.i_mb_stride*last_y;
  2797. }
  2798. else
  2799. {
  2800. h->sh.i_last_mb = h->sh.i_first_mb + h->param.i_slice_max_mbs - 1;
  2801. if( h->sh.i_last_mb < last_thread_mb && last_thread_mb - h->sh.i_last_mb < h->param.i_slice_min_mbs )
  2802. h->sh.i_last_mb = last_thread_mb - h->param.i_slice_min_mbs;
  2803. }
  2804. i_slice_num++;
  2805. }
  2806. else if( h->param.i_slice_count && !h->param.b_sliced_threads )
  2807. {
  2808. int height = h->mb.i_mb_height >> PARAM_INTERLACED;
  2809. int width = h->mb.i_mb_width << PARAM_INTERLACED;
  2810. i_slice_num++;
  2811. h->sh.i_last_mb = (height * i_slice_num + round_bias) / h->param.i_slice_count * width - 1;
  2812. }
  2813. }
  2814. h->sh.i_last_mb = X264_MIN( h->sh.i_last_mb, last_thread_mb );
  2815. if( slice_write( h ) )
  2816. goto fail;
  2817. h->sh.i_first_mb = h->sh.i_last_mb + 1;
  2818. // if i_first_mb is not the last mb in a row then go to the next mb in MBAFF order
  2819. if( SLICE_MBAFF && h->sh.i_first_mb % h->mb.i_mb_width )
  2820. h->sh.i_first_mb -= h->mb.i_mb_stride;
  2821. }
  2822. return (void *)0;
  2823. fail:
  2824. /* Tell other threads we're done, so they wouldn't wait for it */
  2825. if( h->param.b_sliced_threads )
  2826. x264_threadslice_cond_broadcast( h, 2 );
  2827. return (void *)-1;
  2828. }
  2829. static int threaded_slices_write( x264_t *h )
  2830. {
  2831. int round_bias = h->param.i_avcintra_class ? 0 : h->param.i_slice_count/2;
  2832. /* set first/last mb and sync contexts */
  2833. for( int i = 0; i < h->param.i_threads; i++ )
  2834. {
  2835. x264_t *t = h->thread[i];
  2836. if( i )
  2837. {
  2838. t->param = h->param;
  2839. memcpy( &t->i_frame, &h->i_frame, offsetof(x264_t, rc) - offsetof(x264_t, i_frame) );
  2840. }
  2841. int height = h->mb.i_mb_height >> PARAM_INTERLACED;
  2842. t->i_threadslice_start = ((height * i + round_bias) / h->param.i_threads) << PARAM_INTERLACED;
  2843. t->i_threadslice_end = ((height * (i+1) + round_bias) / h->param.i_threads) << PARAM_INTERLACED;
  2844. t->sh.i_first_mb = t->i_threadslice_start * h->mb.i_mb_width;
  2845. t->sh.i_last_mb = t->i_threadslice_end * h->mb.i_mb_width - 1;
  2846. }
  2847. x264_analyse_weight_frame( h, h->mb.i_mb_height*16 + 16 );
  2848. x264_threads_distribute_ratecontrol( h );
  2849. /* setup */
  2850. for( int i = 0; i < h->param.i_threads; i++ )
  2851. {
  2852. h->thread[i]->i_thread_idx = i;
  2853. h->thread[i]->b_thread_active = 1;
  2854. x264_threadslice_cond_broadcast( h->thread[i], 0 );
  2855. }
  2856. /* dispatch */
  2857. for( int i = 0; i < h->param.i_threads; i++ )
  2858. x264_threadpool_run( h->threadpool, (void*)slices_write, h->thread[i] );
  2859. /* wait */
  2860. for( int i = 0; i < h->param.i_threads; i++ )
  2861. x264_threadslice_cond_wait( h->thread[i], 1 );
  2862. x264_threads_merge_ratecontrol( h );
  2863. for( int i = 1; i < h->param.i_threads; i++ )
  2864. {
  2865. x264_t *t = h->thread[i];
  2866. for( int j = 0; j < t->out.i_nal; j++ )
  2867. {
  2868. h->out.nal[h->out.i_nal] = t->out.nal[j];
  2869. h->out.i_nal++;
  2870. nal_check_buffer( h );
  2871. }
  2872. /* All entries in stat.frame are ints except for ssd/ssim. */
  2873. for( int j = 0; j < (offsetof(x264_t,stat.frame.i_ssd) - offsetof(x264_t,stat.frame.i_mv_bits)) / sizeof(int); j++ )
  2874. ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
  2875. for( int j = 0; j < 3; j++ )
  2876. h->stat.frame.i_ssd[j] += t->stat.frame.i_ssd[j];
  2877. h->stat.frame.f_ssim += t->stat.frame.f_ssim;
  2878. h->stat.frame.i_ssim_cnt += t->stat.frame.i_ssim_cnt;
  2879. }
  2880. return 0;
  2881. }
  2882. void x264_encoder_intra_refresh( x264_t *h )
  2883. {
  2884. h = h->thread[h->i_thread_phase];
  2885. h->b_queued_intra_refresh = 1;
  2886. }
  2887. int x264_encoder_invalidate_reference( x264_t *h, int64_t pts )
  2888. {
  2889. if( h->param.i_bframe )
  2890. {
  2891. x264_log( h, X264_LOG_ERROR, "x264_encoder_invalidate_reference is not supported with B-frames enabled\n" );
  2892. return -1;
  2893. }
  2894. if( h->param.b_intra_refresh )
  2895. {
  2896. x264_log( h, X264_LOG_ERROR, "x264_encoder_invalidate_reference is not supported with intra refresh enabled\n" );
  2897. return -1;
  2898. }
  2899. h = h->thread[h->i_thread_phase];
  2900. if( pts >= h->i_last_idr_pts )
  2901. {
  2902. for( int i = 0; h->frames.reference[i]; i++ )
  2903. if( pts <= h->frames.reference[i]->i_pts )
  2904. h->frames.reference[i]->b_corrupt = 1;
  2905. if( pts <= h->fdec->i_pts )
  2906. h->fdec->b_corrupt = 1;
  2907. }
  2908. return 0;
  2909. }
  2910. /****************************************************************************
  2911. * x264_encoder_encode:
  2912. * XXX: i_poc : is the poc of the current given picture
  2913. * i_frame : is the number of the frame being coded
  2914. * ex: type frame poc
  2915. * I 0 2*0
  2916. * P 1 2*3
  2917. * B 2 2*1
  2918. * B 3 2*2
  2919. * P 4 2*6
  2920. * B 5 2*4
  2921. * B 6 2*5
  2922. ****************************************************************************/
  2923. int x264_encoder_encode( x264_t *h,
  2924. x264_nal_t **pp_nal, int *pi_nal,
  2925. x264_picture_t *pic_in,
  2926. x264_picture_t *pic_out )
  2927. {
  2928. x264_t *thread_current, *thread_prev, *thread_oldest;
  2929. int i_nal_type, i_nal_ref_idc, i_global_qp;
  2930. int overhead = NALU_OVERHEAD;
  2931. #if HAVE_OPENCL
  2932. if( h->opencl.b_fatal_error )
  2933. return -1;
  2934. #endif
  2935. if( h->i_thread_frames > 1 )
  2936. {
  2937. thread_prev = h->thread[ h->i_thread_phase ];
  2938. h->i_thread_phase = (h->i_thread_phase + 1) % h->i_thread_frames;
  2939. thread_current = h->thread[ h->i_thread_phase ];
  2940. thread_oldest = h->thread[ (h->i_thread_phase + 1) % h->i_thread_frames ];
  2941. thread_sync_context( thread_current, thread_prev );
  2942. x264_thread_sync_ratecontrol( thread_current, thread_prev, thread_oldest );
  2943. h = thread_current;
  2944. }
  2945. else
  2946. {
  2947. thread_current =
  2948. thread_oldest = h;
  2949. }
  2950. h->i_cpb_delay_pir_offset = h->i_cpb_delay_pir_offset_next;
  2951. /* no data out */
  2952. *pi_nal = 0;
  2953. *pp_nal = NULL;
  2954. /* ------------------- Setup new frame from picture -------------------- */
  2955. if( pic_in != NULL )
  2956. {
  2957. if( h->lookahead->b_exit_thread )
  2958. {
  2959. x264_log( h, X264_LOG_ERROR, "lookahead thread is already stopped\n" );
  2960. return -1;
  2961. }
  2962. /* 1: Copy the picture to a frame and move it to a buffer */
  2963. x264_frame_t *fenc = x264_frame_pop_unused( h, 0 );
  2964. if( !fenc )
  2965. return -1;
  2966. if( x264_frame_copy_picture( h, fenc, pic_in ) < 0 )
  2967. return -1;
  2968. if( h->param.i_width != 16 * h->mb.i_mb_width ||
  2969. h->param.i_height != 16 * h->mb.i_mb_height )
  2970. x264_frame_expand_border_mod16( h, fenc );
  2971. fenc->i_frame = h->frames.i_input++;
  2972. if( fenc->i_frame == 0 )
  2973. h->frames.i_first_pts = fenc->i_pts;
  2974. if( h->frames.i_bframe_delay && fenc->i_frame == h->frames.i_bframe_delay )
  2975. h->frames.i_bframe_delay_time = fenc->i_pts - h->frames.i_first_pts;
  2976. if( h->param.b_vfr_input && fenc->i_pts <= h->frames.i_largest_pts )
  2977. x264_log( h, X264_LOG_WARNING, "non-strictly-monotonic PTS\n" );
  2978. h->frames.i_second_largest_pts = h->frames.i_largest_pts;
  2979. h->frames.i_largest_pts = fenc->i_pts;
  2980. if( (fenc->i_pic_struct < PIC_STRUCT_AUTO) || (fenc->i_pic_struct > PIC_STRUCT_TRIPLE) )
  2981. fenc->i_pic_struct = PIC_STRUCT_AUTO;
  2982. if( fenc->i_pic_struct == PIC_STRUCT_AUTO )
  2983. {
  2984. #if HAVE_INTERLACED
  2985. int b_interlaced = fenc->param ? fenc->param->b_interlaced : h->param.b_interlaced;
  2986. #else
  2987. int b_interlaced = 0;
  2988. #endif
  2989. if( b_interlaced )
  2990. {
  2991. int b_tff = fenc->param ? fenc->param->b_tff : h->param.b_tff;
  2992. fenc->i_pic_struct = b_tff ? PIC_STRUCT_TOP_BOTTOM : PIC_STRUCT_BOTTOM_TOP;
  2993. }
  2994. else
  2995. fenc->i_pic_struct = PIC_STRUCT_PROGRESSIVE;
  2996. }
  2997. if( h->param.rc.b_mb_tree && h->param.rc.b_stat_read )
  2998. {
  2999. if( x264_macroblock_tree_read( h, fenc, pic_in->prop.quant_offsets ) )
  3000. return -1;
  3001. }
  3002. else
  3003. x264_adaptive_quant_frame( h, fenc, pic_in->prop.quant_offsets );
  3004. if( pic_in->prop.quant_offsets_free )
  3005. pic_in->prop.quant_offsets_free( pic_in->prop.quant_offsets );
  3006. if( h->frames.b_have_lowres )
  3007. x264_frame_init_lowres( h, fenc );
  3008. /* 2: Place the frame into the queue for its slice type decision */
  3009. x264_lookahead_put_frame( h, fenc );
  3010. if( h->frames.i_input <= h->frames.i_delay + 1 - h->i_thread_frames )
  3011. {
  3012. /* Nothing yet to encode, waiting for filling of buffers */
  3013. pic_out->i_type = X264_TYPE_AUTO;
  3014. return 0;
  3015. }
  3016. }
  3017. else
  3018. {
  3019. /* signal kills for lookahead thread */
  3020. x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  3021. h->lookahead->b_exit_thread = 1;
  3022. x264_pthread_cond_broadcast( &h->lookahead->ifbuf.cv_fill );
  3023. x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  3024. }
  3025. h->i_frame++;
  3026. /* 3: The picture is analyzed in the lookahead */
  3027. if( !h->frames.current[0] )
  3028. x264_lookahead_get_frames( h );
  3029. if( !h->frames.current[0] && x264_lookahead_is_empty( h ) )
  3030. return encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  3031. /* ------------------- Get frame to be encoded ------------------------- */
  3032. /* 4: get picture to encode */
  3033. h->fenc = x264_frame_shift( h->frames.current );
  3034. /* If applicable, wait for previous frame reconstruction to finish */
  3035. if( h->param.b_sliced_threads )
  3036. if( threadpool_wait_all( h ) < 0 )
  3037. return -1;
  3038. if( h->i_frame == 0 )
  3039. h->i_reordered_pts_delay = h->fenc->i_reordered_pts;
  3040. if( h->reconfig )
  3041. {
  3042. x264_encoder_reconfig_apply( h, &h->reconfig_h->param );
  3043. h->reconfig = 0;
  3044. }
  3045. if( h->fenc->param )
  3046. {
  3047. x264_encoder_reconfig_apply( h, h->fenc->param );
  3048. if( h->fenc->param->param_free )
  3049. {
  3050. h->fenc->param->param_free( h->fenc->param );
  3051. h->fenc->param = NULL;
  3052. }
  3053. }
  3054. x264_ratecontrol_zone_init( h );
  3055. // ok to call this before encoding any frames, since the initial values of fdec have b_kept_as_ref=0
  3056. if( reference_update( h ) )
  3057. return -1;
  3058. h->fdec->i_lines_completed = -1;
  3059. if( !IS_X264_TYPE_I( h->fenc->i_type ) )
  3060. {
  3061. int valid_refs_left = 0;
  3062. for( int i = 0; h->frames.reference[i]; i++ )
  3063. if( !h->frames.reference[i]->b_corrupt )
  3064. valid_refs_left++;
  3065. /* No valid reference frames left: force an IDR. */
  3066. if( !valid_refs_left )
  3067. {
  3068. h->fenc->b_keyframe = 1;
  3069. h->fenc->i_type = X264_TYPE_IDR;
  3070. }
  3071. }
  3072. if( h->fenc->b_keyframe )
  3073. {
  3074. h->frames.i_last_keyframe = h->fenc->i_frame;
  3075. if( h->fenc->i_type == X264_TYPE_IDR )
  3076. {
  3077. h->i_frame_num = 0;
  3078. h->frames.i_last_idr = h->fenc->i_frame;
  3079. }
  3080. }
  3081. h->sh.i_mmco_command_count =
  3082. h->sh.i_mmco_remove_from_end = 0;
  3083. h->b_ref_reorder[0] =
  3084. h->b_ref_reorder[1] = 0;
  3085. h->fdec->i_poc =
  3086. h->fenc->i_poc = 2 * ( h->fenc->i_frame - X264_MAX( h->frames.i_last_idr, 0 ) );
  3087. /* ------------------- Setup frame context ----------------------------- */
  3088. /* 5: Init data dependent of frame type */
  3089. if( h->fenc->i_type == X264_TYPE_IDR )
  3090. {
  3091. /* reset ref pictures */
  3092. i_nal_type = NAL_SLICE_IDR;
  3093. i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  3094. h->sh.i_type = SLICE_TYPE_I;
  3095. reference_reset( h );
  3096. h->frames.i_poc_last_open_gop = -1;
  3097. }
  3098. else if( h->fenc->i_type == X264_TYPE_I )
  3099. {
  3100. i_nal_type = NAL_SLICE;
  3101. i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  3102. h->sh.i_type = SLICE_TYPE_I;
  3103. reference_hierarchy_reset( h );
  3104. if( h->param.b_open_gop )
  3105. h->frames.i_poc_last_open_gop = h->fenc->b_keyframe ? h->fenc->i_poc : -1;
  3106. }
  3107. else if( h->fenc->i_type == X264_TYPE_P )
  3108. {
  3109. i_nal_type = NAL_SLICE;
  3110. i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  3111. h->sh.i_type = SLICE_TYPE_P;
  3112. reference_hierarchy_reset( h );
  3113. h->frames.i_poc_last_open_gop = -1;
  3114. }
  3115. else if( h->fenc->i_type == X264_TYPE_BREF )
  3116. {
  3117. i_nal_type = NAL_SLICE;
  3118. i_nal_ref_idc = h->param.i_bframe_pyramid == X264_B_PYRAMID_STRICT ? NAL_PRIORITY_LOW : NAL_PRIORITY_HIGH;
  3119. h->sh.i_type = SLICE_TYPE_B;
  3120. reference_hierarchy_reset( h );
  3121. }
  3122. else /* B frame */
  3123. {
  3124. i_nal_type = NAL_SLICE;
  3125. i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
  3126. h->sh.i_type = SLICE_TYPE_B;
  3127. }
  3128. h->fdec->i_type = h->fenc->i_type;
  3129. h->fdec->i_frame = h->fenc->i_frame;
  3130. h->fenc->b_kept_as_ref =
  3131. h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1;
  3132. h->fdec->mb_info = h->fenc->mb_info;
  3133. h->fdec->mb_info_free = h->fenc->mb_info_free;
  3134. h->fenc->mb_info = NULL;
  3135. h->fenc->mb_info_free = NULL;
  3136. h->fdec->i_pts = h->fenc->i_pts;
  3137. if( h->frames.i_bframe_delay )
  3138. {
  3139. int64_t *prev_reordered_pts = thread_current->frames.i_prev_reordered_pts;
  3140. h->fdec->i_dts = h->i_frame > h->frames.i_bframe_delay
  3141. ? prev_reordered_pts[ (h->i_frame - h->frames.i_bframe_delay) % h->frames.i_bframe_delay ]
  3142. : h->fenc->i_reordered_pts - h->frames.i_bframe_delay_time;
  3143. prev_reordered_pts[ h->i_frame % h->frames.i_bframe_delay ] = h->fenc->i_reordered_pts;
  3144. }
  3145. else
  3146. h->fdec->i_dts = h->fenc->i_reordered_pts;
  3147. if( h->fenc->i_type == X264_TYPE_IDR )
  3148. h->i_last_idr_pts = h->fdec->i_pts;
  3149. /* ------------------- Init ----------------------------- */
  3150. /* build ref list 0/1 */
  3151. reference_build_list( h, h->fdec->i_poc );
  3152. /* ---------------------- Write the bitstream -------------------------- */
  3153. /* Init bitstream context */
  3154. if( h->param.b_sliced_threads )
  3155. {
  3156. for( int i = 0; i < h->param.i_threads; i++ )
  3157. {
  3158. bs_init( &h->thread[i]->out.bs, h->thread[i]->out.p_bitstream, h->thread[i]->out.i_bitstream );
  3159. h->thread[i]->out.i_nal = 0;
  3160. }
  3161. }
  3162. else
  3163. {
  3164. bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  3165. h->out.i_nal = 0;
  3166. }
  3167. if( h->param.b_aud )
  3168. {
  3169. int pic_type;
  3170. if( h->sh.i_type == SLICE_TYPE_I )
  3171. pic_type = 0;
  3172. else if( h->sh.i_type == SLICE_TYPE_P )
  3173. pic_type = 1;
  3174. else if( h->sh.i_type == SLICE_TYPE_B )
  3175. pic_type = 2;
  3176. else
  3177. pic_type = 7;
  3178. nal_start( h, NAL_AUD, NAL_PRIORITY_DISPOSABLE );
  3179. bs_write( &h->out.bs, 3, pic_type );
  3180. bs_rbsp_trailing( &h->out.bs );
  3181. bs_flush( &h->out.bs );
  3182. if( nal_end( h ) )
  3183. return -1;
  3184. overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  3185. }
  3186. h->i_nal_type = i_nal_type;
  3187. h->i_nal_ref_idc = i_nal_ref_idc;
  3188. if( h->param.b_intra_refresh )
  3189. {
  3190. if( IS_X264_TYPE_I( h->fenc->i_type ) )
  3191. {
  3192. h->fdec->i_frames_since_pir = 0;
  3193. h->b_queued_intra_refresh = 0;
  3194. /* PIR is currently only supported with ref == 1, so any intra frame effectively refreshes
  3195. * the whole frame and counts as an intra refresh. */
  3196. h->fdec->f_pir_position = h->mb.i_mb_width;
  3197. }
  3198. else if( h->fenc->i_type == X264_TYPE_P )
  3199. {
  3200. int pocdiff = (h->fdec->i_poc - h->fref[0][0]->i_poc)/2;
  3201. float increment = X264_MAX( ((float)h->mb.i_mb_width-1) / h->param.i_keyint_max, 1 );
  3202. h->fdec->f_pir_position = h->fref[0][0]->f_pir_position;
  3203. h->fdec->i_frames_since_pir = h->fref[0][0]->i_frames_since_pir + pocdiff;
  3204. if( h->fdec->i_frames_since_pir >= h->param.i_keyint_max ||
  3205. (h->b_queued_intra_refresh && h->fdec->f_pir_position + 0.5 >= h->mb.i_mb_width) )
  3206. {
  3207. h->fdec->f_pir_position = 0;
  3208. h->fdec->i_frames_since_pir = 0;
  3209. h->b_queued_intra_refresh = 0;
  3210. h->fenc->b_keyframe = 1;
  3211. }
  3212. h->fdec->i_pir_start_col = h->fdec->f_pir_position+0.5;
  3213. h->fdec->f_pir_position += increment * pocdiff;
  3214. h->fdec->i_pir_end_col = h->fdec->f_pir_position+0.5;
  3215. /* If our intra refresh has reached the right side of the frame, we're done. */
  3216. if( h->fdec->i_pir_end_col >= h->mb.i_mb_width - 1 )
  3217. {
  3218. h->fdec->f_pir_position = h->mb.i_mb_width;
  3219. h->fdec->i_pir_end_col = h->mb.i_mb_width - 1;
  3220. }
  3221. }
  3222. }
  3223. if( h->fenc->b_keyframe )
  3224. {
  3225. /* Write SPS and PPS */
  3226. if( h->param.b_repeat_headers )
  3227. {
  3228. /* generate sequence parameters */
  3229. nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  3230. x264_sps_write( &h->out.bs, h->sps );
  3231. if( nal_end( h ) )
  3232. return -1;
  3233. /* Pad AUD/SPS to 256 bytes like Panasonic */
  3234. if( h->param.i_avcintra_class )
  3235. h->out.nal[h->out.i_nal-1].i_padding = 256 - bs_pos( &h->out.bs ) / 8 - 2*NALU_OVERHEAD;
  3236. overhead += h->out.nal[h->out.i_nal-1].i_payload + h->out.nal[h->out.i_nal-1].i_padding + NALU_OVERHEAD;
  3237. /* generate picture parameters */
  3238. nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  3239. x264_pps_write( &h->out.bs, h->sps, h->pps );
  3240. if( nal_end( h ) )
  3241. return -1;
  3242. if( h->param.i_avcintra_class )
  3243. {
  3244. int total_len = 256;
  3245. /* Sony XAVC uses an oversized PPS instead of SEI padding */
  3246. if( h->param.i_avcintra_flavor == X264_AVCINTRA_FLAVOR_SONY )
  3247. total_len += h->param.i_height == 1080 ? 18*512 : 10*512;
  3248. h->out.nal[h->out.i_nal-1].i_padding = total_len - h->out.nal[h->out.i_nal-1].i_payload - NALU_OVERHEAD;
  3249. }
  3250. overhead += h->out.nal[h->out.i_nal-1].i_payload + h->out.nal[h->out.i_nal-1].i_padding + NALU_OVERHEAD;
  3251. }
  3252. /* when frame threading is used, buffering period sei is written in encoder_frame_end */
  3253. if( h->i_thread_frames == 1 && h->sps->vui.b_nal_hrd_parameters_present )
  3254. {
  3255. x264_hrd_fullness( h );
  3256. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3257. x264_sei_buffering_period_write( h, &h->out.bs );
  3258. if( nal_end( h ) )
  3259. return -1;
  3260. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3261. }
  3262. }
  3263. /* write extra sei */
  3264. for( int i = 0; i < h->fenc->extra_sei.num_payloads; i++ )
  3265. {
  3266. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3267. x264_sei_write( &h->out.bs, h->fenc->extra_sei.payloads[i].payload, h->fenc->extra_sei.payloads[i].payload_size,
  3268. h->fenc->extra_sei.payloads[i].payload_type );
  3269. if( nal_end( h ) )
  3270. return -1;
  3271. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3272. if( h->fenc->extra_sei.sei_free )
  3273. {
  3274. h->fenc->extra_sei.sei_free( h->fenc->extra_sei.payloads[i].payload );
  3275. h->fenc->extra_sei.payloads[i].payload = NULL;
  3276. }
  3277. }
  3278. if( h->fenc->extra_sei.sei_free )
  3279. {
  3280. h->fenc->extra_sei.sei_free( h->fenc->extra_sei.payloads );
  3281. h->fenc->extra_sei.payloads = NULL;
  3282. h->fenc->extra_sei.sei_free = NULL;
  3283. }
  3284. if( h->fenc->b_keyframe )
  3285. {
  3286. /* Avid's decoder strictly wants two SEIs for AVC-Intra so we can't insert the x264 SEI */
  3287. if( h->param.b_repeat_headers && h->fenc->i_frame == 0 && !h->param.i_avcintra_class )
  3288. {
  3289. /* identify ourself */
  3290. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3291. if( x264_sei_version_write( h, &h->out.bs ) )
  3292. return -1;
  3293. if( nal_end( h ) )
  3294. return -1;
  3295. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3296. }
  3297. if( h->fenc->i_type != X264_TYPE_IDR )
  3298. {
  3299. int time_to_recovery = h->param.b_open_gop ? 0 : X264_MIN( h->mb.i_mb_width - 1, h->param.i_keyint_max ) + h->param.i_bframe - 1;
  3300. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3301. x264_sei_recovery_point_write( h, &h->out.bs, time_to_recovery );
  3302. if( nal_end( h ) )
  3303. return -1;
  3304. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3305. }
  3306. }
  3307. if( h->param.i_frame_packing >= 0 && (h->fenc->b_keyframe || h->param.i_frame_packing == 5) )
  3308. {
  3309. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3310. x264_sei_frame_packing_write( h, &h->out.bs );
  3311. if( nal_end( h ) )
  3312. return -1;
  3313. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3314. }
  3315. if( h->param.i_alternative_transfer != 2 )
  3316. {
  3317. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3318. x264_sei_alternative_transfer_write( h, &h->out.bs );
  3319. if( nal_end( h ) )
  3320. return -1;
  3321. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3322. }
  3323. /* generate sei pic timing */
  3324. if( h->sps->vui.b_pic_struct_present || h->sps->vui.b_nal_hrd_parameters_present )
  3325. {
  3326. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3327. x264_sei_pic_timing_write( h, &h->out.bs );
  3328. if( nal_end( h ) )
  3329. return -1;
  3330. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3331. }
  3332. /* As required by Blu-ray. */
  3333. if( !IS_X264_TYPE_B( h->fenc->i_type ) && h->b_sh_backup )
  3334. {
  3335. h->b_sh_backup = 0;
  3336. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3337. x264_sei_dec_ref_pic_marking_write( h, &h->out.bs );
  3338. if( nal_end( h ) )
  3339. return -1;
  3340. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3341. }
  3342. if( h->fenc->b_keyframe && h->param.b_intra_refresh )
  3343. h->i_cpb_delay_pir_offset_next = h->fenc->i_cpb_delay;
  3344. /* Filler space: 10 or 18 SEIs' worth of space, depending on resolution */
  3345. if( h->param.i_avcintra_class && h->param.i_avcintra_flavor != X264_AVCINTRA_FLAVOR_SONY )
  3346. {
  3347. /* Write an empty filler NAL to mimic the AUD in the P2 format*/
  3348. nal_start( h, NAL_FILLER, NAL_PRIORITY_DISPOSABLE );
  3349. x264_filler_write( h, &h->out.bs, 0 );
  3350. if( nal_end( h ) )
  3351. return -1;
  3352. overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  3353. /* All lengths are magic lengths that decoders expect to see */
  3354. /* "UMID" SEI */
  3355. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3356. if( x264_sei_avcintra_umid_write( h, &h->out.bs ) < 0 )
  3357. return -1;
  3358. if( nal_end( h ) )
  3359. return -1;
  3360. overhead += h->out.nal[h->out.i_nal-1].i_payload + SEI_OVERHEAD;
  3361. int unpadded_len;
  3362. int total_len;
  3363. if( h->param.i_height == 1080 )
  3364. {
  3365. unpadded_len = 5780;
  3366. total_len = 17*512;
  3367. }
  3368. else
  3369. {
  3370. unpadded_len = 2900;
  3371. total_len = 9*512;
  3372. }
  3373. /* "VANC" SEI */
  3374. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3375. if( x264_sei_avcintra_vanc_write( h, &h->out.bs, unpadded_len ) < 0 )
  3376. return -1;
  3377. if( nal_end( h ) )
  3378. return -1;
  3379. h->out.nal[h->out.i_nal-1].i_padding = total_len - h->out.nal[h->out.i_nal-1].i_payload - SEI_OVERHEAD;
  3380. overhead += h->out.nal[h->out.i_nal-1].i_payload + h->out.nal[h->out.i_nal-1].i_padding + SEI_OVERHEAD;
  3381. }
  3382. /* Init the rate control */
  3383. /* FIXME: Include slice header bit cost. */
  3384. x264_ratecontrol_start( h, h->fenc->i_qpplus1, overhead*8 );
  3385. i_global_qp = x264_ratecontrol_qp( h );
  3386. pic_out->i_qpplus1 =
  3387. h->fdec->i_qpplus1 = i_global_qp + 1;
  3388. if( h->param.rc.b_stat_read && h->sh.i_type != SLICE_TYPE_I )
  3389. {
  3390. x264_reference_build_list_optimal( h );
  3391. reference_check_reorder( h );
  3392. }
  3393. if( h->i_ref[0] )
  3394. h->fdec->i_poc_l0ref0 = h->fref[0][0]->i_poc;
  3395. /* ------------------------ Create slice header ----------------------- */
  3396. slice_init( h, i_nal_type, i_global_qp );
  3397. /*------------------------- Weights -------------------------------------*/
  3398. if( h->sh.i_type == SLICE_TYPE_B )
  3399. x264_macroblock_bipred_init( h );
  3400. weighted_pred_init( h );
  3401. if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
  3402. h->i_frame_num++;
  3403. /* Write frame */
  3404. h->i_threadslice_start = 0;
  3405. h->i_threadslice_end = h->mb.i_mb_height;
  3406. if( h->i_thread_frames > 1 )
  3407. {
  3408. x264_threadpool_run( h->threadpool, (void*)slices_write, h );
  3409. h->b_thread_active = 1;
  3410. }
  3411. else if( h->param.b_sliced_threads )
  3412. {
  3413. if( threaded_slices_write( h ) )
  3414. return -1;
  3415. }
  3416. else
  3417. if( (intptr_t)slices_write( h ) )
  3418. return -1;
  3419. return encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  3420. }
  3421. static int encoder_frame_end( x264_t *h, x264_t *thread_current,
  3422. x264_nal_t **pp_nal, int *pi_nal,
  3423. x264_picture_t *pic_out )
  3424. {
  3425. char psz_message[80];
  3426. if( !h->param.b_sliced_threads && h->b_thread_active )
  3427. {
  3428. h->b_thread_active = 0;
  3429. if( (intptr_t)x264_threadpool_wait( h->threadpool, h ) )
  3430. return -1;
  3431. }
  3432. if( !h->out.i_nal )
  3433. {
  3434. pic_out->i_type = X264_TYPE_AUTO;
  3435. return 0;
  3436. }
  3437. x264_emms();
  3438. /* generate buffering period sei and insert it into place */
  3439. if( h->i_thread_frames > 1 && h->fenc->b_keyframe && h->sps->vui.b_nal_hrd_parameters_present )
  3440. {
  3441. x264_hrd_fullness( h );
  3442. nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  3443. x264_sei_buffering_period_write( h, &h->out.bs );
  3444. if( nal_end( h ) )
  3445. return -1;
  3446. /* buffering period sei must follow AUD, SPS and PPS and precede all other SEIs */
  3447. int idx = 0;
  3448. while( h->out.nal[idx].i_type == NAL_AUD ||
  3449. h->out.nal[idx].i_type == NAL_SPS ||
  3450. h->out.nal[idx].i_type == NAL_PPS )
  3451. idx++;
  3452. x264_nal_t nal_tmp = h->out.nal[h->out.i_nal-1];
  3453. memmove( &h->out.nal[idx+1], &h->out.nal[idx], (h->out.i_nal-idx-1)*sizeof(x264_nal_t) );
  3454. h->out.nal[idx] = nal_tmp;
  3455. }
  3456. int frame_size = encoder_encapsulate_nals( h, 0 );
  3457. if( frame_size < 0 )
  3458. return -1;
  3459. /* Set output picture properties */
  3460. pic_out->i_type = h->fenc->i_type;
  3461. pic_out->b_keyframe = h->fenc->b_keyframe;
  3462. pic_out->i_pic_struct = h->fenc->i_pic_struct;
  3463. pic_out->i_pts = h->fdec->i_pts;
  3464. pic_out->i_dts = h->fdec->i_dts;
  3465. if( pic_out->i_pts < pic_out->i_dts )
  3466. x264_log( h, X264_LOG_WARNING, "invalid DTS: PTS is less than DTS\n" );
  3467. pic_out->opaque = h->fenc->opaque;
  3468. pic_out->img.i_csp = h->fdec->i_csp;
  3469. #if HIGH_BIT_DEPTH
  3470. pic_out->img.i_csp |= X264_CSP_HIGH_DEPTH;
  3471. #endif
  3472. pic_out->img.i_plane = h->fdec->i_plane;
  3473. for( int i = 0; i < pic_out->img.i_plane; i++ )
  3474. {
  3475. pic_out->img.i_stride[i] = h->fdec->i_stride[i] * sizeof(pixel);
  3476. pic_out->img.plane[i] = (uint8_t*)h->fdec->plane[i];
  3477. }
  3478. x264_frame_push_unused( thread_current, h->fenc );
  3479. /* ---------------------- Update encoder state ------------------------- */
  3480. /* update rc */
  3481. int filler = 0;
  3482. if( x264_ratecontrol_end( h, frame_size * 8, &filler ) < 0 )
  3483. return -1;
  3484. pic_out->hrd_timing = h->fenc->hrd_timing;
  3485. pic_out->prop.f_crf_avg = h->fdec->f_crf_avg;
  3486. /* Filler in AVC-Intra mode is written as zero bytes to the last slice
  3487. * We don't know the size of the last slice until encapsulation so we add filler to the encapsulated NAL */
  3488. if( h->param.i_avcintra_class )
  3489. {
  3490. if( check_encapsulated_buffer( h, h->thread[0], h->out.i_nal, frame_size, frame_size + filler ) < 0 )
  3491. return -1;
  3492. x264_nal_t *nal = &h->out.nal[h->out.i_nal-1];
  3493. memset( nal->p_payload + nal->i_payload, 0, filler );
  3494. nal->i_payload += filler;
  3495. nal->i_padding = filler;
  3496. frame_size += filler;
  3497. /* Fix up the size header for mp4/etc */
  3498. if( !h->param.b_annexb )
  3499. {
  3500. /* Size doesn't include the size of the header we're writing now. */
  3501. uint8_t *nal_data = nal->p_payload;
  3502. int chunk_size = nal->i_payload - 4;
  3503. nal_data[0] = chunk_size >> 24;
  3504. nal_data[1] = chunk_size >> 16;
  3505. nal_data[2] = chunk_size >> 8;
  3506. nal_data[3] = chunk_size >> 0;
  3507. }
  3508. }
  3509. else
  3510. {
  3511. while( filler > 0 )
  3512. {
  3513. int f, overhead = FILLER_OVERHEAD - h->param.b_annexb;
  3514. if( h->param.i_slice_max_size && filler > h->param.i_slice_max_size )
  3515. {
  3516. int next_size = filler - h->param.i_slice_max_size;
  3517. int overflow = X264_MAX( overhead - next_size, 0 );
  3518. f = h->param.i_slice_max_size - overhead - overflow;
  3519. }
  3520. else
  3521. f = X264_MAX( 0, filler - overhead );
  3522. if( bitstream_check_buffer_filler( h, f ) )
  3523. return -1;
  3524. nal_start( h, NAL_FILLER, NAL_PRIORITY_DISPOSABLE );
  3525. x264_filler_write( h, &h->out.bs, f );
  3526. if( nal_end( h ) )
  3527. return -1;
  3528. int total_size = encoder_encapsulate_nals( h, h->out.i_nal-1 );
  3529. if( total_size < 0 )
  3530. return -1;
  3531. frame_size += total_size;
  3532. filler -= total_size;
  3533. }
  3534. }
  3535. /* End bitstream, set output */
  3536. *pi_nal = h->out.i_nal;
  3537. *pp_nal = h->out.nal;
  3538. h->out.i_nal = 0;
  3539. x264_noise_reduction_update( h );
  3540. /* ---------------------- Compute/Print statistics --------------------- */
  3541. thread_sync_stat( h, h->thread[0] );
  3542. /* Slice stat */
  3543. h->stat.i_frame_count[h->sh.i_type]++;
  3544. h->stat.i_frame_size[h->sh.i_type] += frame_size;
  3545. h->stat.f_frame_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  3546. for( int i = 0; i < X264_MBTYPE_MAX; i++ )
  3547. h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
  3548. for( int i = 0; i < X264_PARTTYPE_MAX; i++ )
  3549. h->stat.i_mb_partition[h->sh.i_type][i] += h->stat.frame.i_mb_partition[i];
  3550. for( int i = 0; i < 2; i++ )
  3551. h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
  3552. for( int i = 0; i < 6; i++ )
  3553. h->stat.i_mb_cbp[i] += h->stat.frame.i_mb_cbp[i];
  3554. for( int i = 0; i < 4; i++ )
  3555. for( int j = 0; j < 13; j++ )
  3556. h->stat.i_mb_pred_mode[i][j] += h->stat.frame.i_mb_pred_mode[i][j];
  3557. if( h->sh.i_type != SLICE_TYPE_I )
  3558. for( int i_list = 0; i_list < 2; i_list++ )
  3559. for( int i = 0; i < X264_REF_MAX*2; i++ )
  3560. h->stat.i_mb_count_ref[h->sh.i_type][i_list][i] += h->stat.frame.i_mb_count_ref[i_list][i];
  3561. for( int i = 0; i < 3; i++ )
  3562. h->stat.i_mb_field[i] += h->stat.frame.i_mb_field[i];
  3563. if( h->sh.i_type == SLICE_TYPE_P && h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE )
  3564. {
  3565. h->stat.i_wpred[0] += !!h->sh.weight[0][0].weightfn;
  3566. h->stat.i_wpred[1] += !!h->sh.weight[0][1].weightfn || !!h->sh.weight[0][2].weightfn;
  3567. }
  3568. if( h->sh.i_type == SLICE_TYPE_B )
  3569. {
  3570. h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
  3571. if( h->mb.b_direct_auto_write )
  3572. {
  3573. //FIXME somewhat arbitrary time constants
  3574. if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
  3575. for( int i = 0; i < 2; i++ )
  3576. h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
  3577. for( int i = 0; i < 2; i++ )
  3578. h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
  3579. }
  3580. }
  3581. else
  3582. h->stat.i_consecutive_bframes[h->fenc->i_bframes]++;
  3583. psz_message[0] = '\0';
  3584. double dur = h->fenc->f_duration;
  3585. h->stat.f_frame_duration[h->sh.i_type] += dur;
  3586. if( h->param.analyse.b_psnr )
  3587. {
  3588. int64_t ssd[3] =
  3589. {
  3590. h->stat.frame.i_ssd[0],
  3591. h->stat.frame.i_ssd[1],
  3592. h->stat.frame.i_ssd[2],
  3593. };
  3594. int luma_size = h->param.i_width * h->param.i_height;
  3595. int chroma_size = CHROMA_SIZE( luma_size );
  3596. pic_out->prop.f_psnr[0] = calc_psnr( ssd[0], luma_size );
  3597. pic_out->prop.f_psnr[1] = calc_psnr( ssd[1], chroma_size );
  3598. pic_out->prop.f_psnr[2] = calc_psnr( ssd[2], chroma_size );
  3599. pic_out->prop.f_psnr_avg = calc_psnr( ssd[0] + ssd[1] + ssd[2], luma_size + chroma_size*2 );
  3600. h->stat.f_ssd_global[h->sh.i_type] += dur * (ssd[0] + ssd[1] + ssd[2]);
  3601. h->stat.f_psnr_average[h->sh.i_type] += dur * pic_out->prop.f_psnr_avg;
  3602. h->stat.f_psnr_mean_y[h->sh.i_type] += dur * pic_out->prop.f_psnr[0];
  3603. h->stat.f_psnr_mean_u[h->sh.i_type] += dur * pic_out->prop.f_psnr[1];
  3604. h->stat.f_psnr_mean_v[h->sh.i_type] += dur * pic_out->prop.f_psnr[2];
  3605. snprintf( psz_message, 80, " PSNR Y:%5.2f U:%5.2f V:%5.2f", pic_out->prop.f_psnr[0],
  3606. pic_out->prop.f_psnr[1],
  3607. pic_out->prop.f_psnr[2] );
  3608. }
  3609. if( h->param.analyse.b_ssim )
  3610. {
  3611. pic_out->prop.f_ssim = h->stat.frame.f_ssim / h->stat.frame.i_ssim_cnt;
  3612. h->stat.f_ssim_mean_y[h->sh.i_type] += pic_out->prop.f_ssim * dur;
  3613. int msg_len = strlen(psz_message);
  3614. snprintf( psz_message + msg_len, 80 - msg_len, " SSIM Y:%.5f", pic_out->prop.f_ssim );
  3615. }
  3616. psz_message[79] = '\0';
  3617. x264_log( h, X264_LOG_DEBUG,
  3618. "frame=%4d QP=%.2f NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
  3619. h->i_frame,
  3620. h->fdec->f_qp_avg_aq,
  3621. h->i_nal_ref_idc,
  3622. h->sh.i_type == SLICE_TYPE_I ? 'I' : (h->sh.i_type == SLICE_TYPE_P ? 'P' : 'B' ),
  3623. h->fdec->i_poc,
  3624. h->stat.frame.i_mb_count_i,
  3625. h->stat.frame.i_mb_count_p,
  3626. h->stat.frame.i_mb_count_skip,
  3627. frame_size,
  3628. psz_message );
  3629. // keep stats all in one place
  3630. thread_sync_stat( h->thread[0], h );
  3631. // for the use of the next frame
  3632. thread_sync_stat( thread_current, h );
  3633. #ifdef DEBUG_MB_TYPE
  3634. {
  3635. static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
  3636. 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
  3637. for( int mb_xy = 0; mb_xy < h->mb.i_mb_width * h->mb.i_mb_height; mb_xy++ )
  3638. {
  3639. if( h->mb.type[mb_xy] < X264_MBTYPE_MAX && h->mb.type[mb_xy] >= 0 )
  3640. fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
  3641. else
  3642. fprintf( stderr, "? " );
  3643. if( (mb_xy+1) % h->mb.i_mb_width == 0 )
  3644. fprintf( stderr, "\n" );
  3645. }
  3646. }
  3647. #endif
  3648. /* Remove duplicates, must be done near the end as breaks h->fref0 array
  3649. * by freeing some of its pointers. */
  3650. for( int i = 0; i < h->i_ref[0]; i++ )
  3651. if( h->fref[0][i] && h->fref[0][i]->b_duplicate )
  3652. {
  3653. x264_frame_push_blank_unused( h, h->fref[0][i] );
  3654. h->fref[0][i] = 0;
  3655. }
  3656. if( h->param.psz_dump_yuv )
  3657. frame_dump( h );
  3658. x264_emms();
  3659. return frame_size;
  3660. }
  3661. static void print_intra( int64_t *i_mb_count, double i_count, int b_print_pcm, char *intra )
  3662. {
  3663. intra += sprintf( intra, "I16..4%s: %4.1f%% %4.1f%% %4.1f%%",
  3664. b_print_pcm ? "..PCM" : "",
  3665. i_mb_count[I_16x16]/ i_count,
  3666. i_mb_count[I_8x8] / i_count,
  3667. i_mb_count[I_4x4] / i_count );
  3668. if( b_print_pcm )
  3669. sprintf( intra, " %4.1f%%", i_mb_count[I_PCM] / i_count );
  3670. }
  3671. /****************************************************************************
  3672. * x264_encoder_close:
  3673. ****************************************************************************/
  3674. void x264_encoder_close ( x264_t *h )
  3675. {
  3676. int64_t i_yuv_size = FRAME_SIZE( h->param.i_width * h->param.i_height );
  3677. int64_t i_mb_count_size[2][7] = {{0}};
  3678. char buf[200];
  3679. int b_print_pcm = h->stat.i_mb_count[SLICE_TYPE_I][I_PCM]
  3680. || h->stat.i_mb_count[SLICE_TYPE_P][I_PCM]
  3681. || h->stat.i_mb_count[SLICE_TYPE_B][I_PCM];
  3682. x264_lookahead_delete( h );
  3683. #if HAVE_OPENCL
  3684. x264_opencl_lookahead_delete( h );
  3685. x264_opencl_function_t *ocl = h->opencl.ocl;
  3686. #endif
  3687. if( h->param.b_sliced_threads )
  3688. threadpool_wait_all( h );
  3689. if( h->param.i_threads > 1 )
  3690. x264_threadpool_delete( h->threadpool );
  3691. if( h->param.i_lookahead_threads > 1 )
  3692. x264_threadpool_delete( h->lookaheadpool );
  3693. if( h->i_thread_frames > 1 )
  3694. {
  3695. for( int i = 0; i < h->i_thread_frames; i++ )
  3696. if( h->thread[i]->b_thread_active )
  3697. {
  3698. assert( h->thread[i]->fenc->i_reference_count == 1 );
  3699. x264_frame_delete( h->thread[i]->fenc );
  3700. }
  3701. x264_t *thread_prev = h->thread[h->i_thread_phase];
  3702. x264_thread_sync_ratecontrol( h, thread_prev, h );
  3703. x264_thread_sync_ratecontrol( thread_prev, thread_prev, h );
  3704. h->i_frame = thread_prev->i_frame + 1 - h->i_thread_frames;
  3705. }
  3706. h->i_frame++;
  3707. /* Slices used and PSNR */
  3708. for( int i = 0; i < 3; i++ )
  3709. {
  3710. static const uint8_t slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_P, SLICE_TYPE_B };
  3711. int i_slice = slice_order[i];
  3712. if( h->stat.i_frame_count[i_slice] > 0 )
  3713. {
  3714. int i_count = h->stat.i_frame_count[i_slice];
  3715. double dur = h->stat.f_frame_duration[i_slice];
  3716. if( h->param.analyse.b_psnr )
  3717. {
  3718. x264_log( h, X264_LOG_INFO,
  3719. "frame %c:%-5d Avg QP:%5.2f size:%6.0f PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f\n",
  3720. slice_type_to_char[i_slice],
  3721. i_count,
  3722. h->stat.f_frame_qp[i_slice] / i_count,
  3723. (double)h->stat.i_frame_size[i_slice] / i_count,
  3724. h->stat.f_psnr_mean_y[i_slice] / dur, h->stat.f_psnr_mean_u[i_slice] / dur, h->stat.f_psnr_mean_v[i_slice] / dur,
  3725. h->stat.f_psnr_average[i_slice] / dur,
  3726. calc_psnr( h->stat.f_ssd_global[i_slice], dur * i_yuv_size ) );
  3727. }
  3728. else
  3729. {
  3730. x264_log( h, X264_LOG_INFO,
  3731. "frame %c:%-5d Avg QP:%5.2f size:%6.0f\n",
  3732. slice_type_to_char[i_slice],
  3733. i_count,
  3734. h->stat.f_frame_qp[i_slice] / i_count,
  3735. (double)h->stat.i_frame_size[i_slice] / i_count );
  3736. }
  3737. }
  3738. }
  3739. if( h->param.i_bframe && h->stat.i_frame_count[SLICE_TYPE_B] )
  3740. {
  3741. char *p = buf;
  3742. int den = 0;
  3743. // weight by number of frames (including the I/P-frames) that are in a sequence of N B-frames
  3744. for( int i = 0; i <= h->param.i_bframe; i++ )
  3745. den += (i+1) * h->stat.i_consecutive_bframes[i];
  3746. for( int i = 0; i <= h->param.i_bframe; i++ )
  3747. p += sprintf( p, " %4.1f%%", 100. * (i+1) * h->stat.i_consecutive_bframes[i] / den );
  3748. x264_log( h, X264_LOG_INFO, "consecutive B-frames:%s\n", buf );
  3749. }
  3750. for( int i_type = 0; i_type < 2; i_type++ )
  3751. for( int i = 0; i < X264_PARTTYPE_MAX; i++ )
  3752. {
  3753. if( i == D_DIRECT_8x8 ) continue; /* direct is counted as its own type */
  3754. i_mb_count_size[i_type][x264_mb_partition_pixel_table[i]] += h->stat.i_mb_partition[i_type][i];
  3755. }
  3756. /* MB types used */
  3757. if( h->stat.i_frame_count[SLICE_TYPE_I] > 0 )
  3758. {
  3759. int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
  3760. double i_count = (double)h->stat.i_frame_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
  3761. print_intra( i_mb_count, i_count, b_print_pcm, buf );
  3762. x264_log( h, X264_LOG_INFO, "mb I %s\n", buf );
  3763. }
  3764. if( h->stat.i_frame_count[SLICE_TYPE_P] > 0 )
  3765. {
  3766. int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
  3767. double i_count = (double)h->stat.i_frame_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
  3768. int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_P];
  3769. print_intra( i_mb_count, i_count, b_print_pcm, buf );
  3770. x264_log( h, X264_LOG_INFO,
  3771. "mb P %s P16..4: %4.1f%% %4.1f%% %4.1f%% %4.1f%% %4.1f%% skip:%4.1f%%\n",
  3772. buf,
  3773. i_mb_size[PIXEL_16x16] / (i_count*4),
  3774. (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  3775. i_mb_size[PIXEL_8x8] / (i_count*4),
  3776. (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
  3777. i_mb_size[PIXEL_4x4] / (i_count*4),
  3778. i_mb_count[P_SKIP] / i_count );
  3779. }
  3780. if( h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
  3781. {
  3782. int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
  3783. double i_count = (double)h->stat.i_frame_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
  3784. double i_mb_list_count;
  3785. int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_B];
  3786. int64_t list_count[3] = {0}; /* 0 == L0, 1 == L1, 2 == BI */
  3787. print_intra( i_mb_count, i_count, b_print_pcm, buf );
  3788. for( int i = 0; i < X264_PARTTYPE_MAX; i++ )
  3789. for( int j = 0; j < 2; j++ )
  3790. {
  3791. int l0 = x264_mb_type_list_table[i][0][j];
  3792. int l1 = x264_mb_type_list_table[i][1][j];
  3793. if( l0 || l1 )
  3794. list_count[l1+l0*l1] += h->stat.i_mb_count[SLICE_TYPE_B][i] * 2;
  3795. }
  3796. list_count[0] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L0_8x8];
  3797. list_count[1] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L1_8x8];
  3798. list_count[2] += h->stat.i_mb_partition[SLICE_TYPE_B][D_BI_8x8];
  3799. i_mb_count[B_DIRECT] += (h->stat.i_mb_partition[SLICE_TYPE_B][D_DIRECT_8x8]+2)/4;
  3800. i_mb_list_count = (list_count[0] + list_count[1] + list_count[2]) / 100.0;
  3801. sprintf( buf + strlen(buf), " B16..8: %4.1f%% %4.1f%% %4.1f%% direct:%4.1f%% skip:%4.1f%%",
  3802. i_mb_size[PIXEL_16x16] / (i_count*4),
  3803. (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  3804. i_mb_size[PIXEL_8x8] / (i_count*4),
  3805. i_mb_count[B_DIRECT] / i_count,
  3806. i_mb_count[B_SKIP] / i_count );
  3807. if( i_mb_list_count != 0 )
  3808. sprintf( buf + strlen(buf), " L0:%4.1f%% L1:%4.1f%% BI:%4.1f%%",
  3809. list_count[0] / i_mb_list_count,
  3810. list_count[1] / i_mb_list_count,
  3811. list_count[2] / i_mb_list_count );
  3812. x264_log( h, X264_LOG_INFO, "mb B %s\n", buf );
  3813. }
  3814. x264_ratecontrol_summary( h );
  3815. if( h->stat.i_frame_count[SLICE_TYPE_I] + h->stat.i_frame_count[SLICE_TYPE_P] + h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
  3816. {
  3817. #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
  3818. #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
  3819. int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
  3820. int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
  3821. + SUM3b( h->stat.i_mb_count, I_16x16 );
  3822. int64_t i_all_intra = i_intra + SUM3b( h->stat.i_mb_count, I_PCM);
  3823. int64_t i_skip = SUM3b( h->stat.i_mb_count, P_SKIP )
  3824. + SUM3b( h->stat.i_mb_count, B_SKIP );
  3825. const int i_count = h->stat.i_frame_count[SLICE_TYPE_I] +
  3826. h->stat.i_frame_count[SLICE_TYPE_P] +
  3827. h->stat.i_frame_count[SLICE_TYPE_B];
  3828. int64_t i_mb_count = (int64_t)i_count * h->mb.i_mb_count;
  3829. int64_t i_inter = i_mb_count - i_skip - i_intra;
  3830. const double duration = h->stat.f_frame_duration[SLICE_TYPE_I] +
  3831. h->stat.f_frame_duration[SLICE_TYPE_P] +
  3832. h->stat.f_frame_duration[SLICE_TYPE_B];
  3833. float f_bitrate = SUM3(h->stat.i_frame_size) / duration / 125;
  3834. if( PARAM_INTERLACED )
  3835. {
  3836. char *fieldstats = buf;
  3837. fieldstats[0] = 0;
  3838. if( i_inter )
  3839. fieldstats += sprintf( fieldstats, " inter:%.1f%%", h->stat.i_mb_field[1] * 100.0 / i_inter );
  3840. if( i_skip )
  3841. fieldstats += sprintf( fieldstats, " skip:%.1f%%", h->stat.i_mb_field[2] * 100.0 / i_skip );
  3842. x264_log( h, X264_LOG_INFO, "field mbs: intra: %.1f%%%s\n",
  3843. h->stat.i_mb_field[0] * 100.0 / i_intra, buf );
  3844. }
  3845. if( h->pps->b_transform_8x8_mode )
  3846. {
  3847. buf[0] = 0;
  3848. if( h->stat.i_mb_count_8x8dct[0] )
  3849. sprintf( buf, " inter:%.1f%%", 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
  3850. x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%%%s\n", 100. * i_i8x8 / i_intra, buf );
  3851. }
  3852. if( (h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO ||
  3853. (h->stat.i_direct_frames[0] && h->stat.i_direct_frames[1]))
  3854. && h->stat.i_frame_count[SLICE_TYPE_B] )
  3855. {
  3856. x264_log( h, X264_LOG_INFO, "direct mvs spatial:%.1f%% temporal:%.1f%%\n",
  3857. h->stat.i_direct_frames[1] * 100. / h->stat.i_frame_count[SLICE_TYPE_B],
  3858. h->stat.i_direct_frames[0] * 100. / h->stat.i_frame_count[SLICE_TYPE_B] );
  3859. }
  3860. buf[0] = 0;
  3861. if( CHROMA_FORMAT )
  3862. {
  3863. int csize = CHROMA444 ? 4 : 1;
  3864. if( i_mb_count != i_all_intra )
  3865. sprintf( buf, " inter: %.1f%% %.1f%% %.1f%%",
  3866. h->stat.i_mb_cbp[1] * 100.0 / ((i_mb_count - i_all_intra)*4),
  3867. h->stat.i_mb_cbp[3] * 100.0 / ((i_mb_count - i_all_intra)*csize),
  3868. h->stat.i_mb_cbp[5] * 100.0 / ((i_mb_count - i_all_intra)*csize) );
  3869. x264_log( h, X264_LOG_INFO, "coded y,%s,%s intra: %.1f%% %.1f%% %.1f%%%s\n",
  3870. CHROMA444?"u":"uvDC", CHROMA444?"v":"uvAC",
  3871. h->stat.i_mb_cbp[0] * 100.0 / (i_all_intra*4),
  3872. h->stat.i_mb_cbp[2] * 100.0 / (i_all_intra*csize),
  3873. h->stat.i_mb_cbp[4] * 100.0 / (i_all_intra*csize), buf );
  3874. }
  3875. else
  3876. {
  3877. if( i_mb_count != i_all_intra )
  3878. sprintf( buf, " inter: %.1f%%", h->stat.i_mb_cbp[1] * 100.0 / ((i_mb_count - i_all_intra)*4) );
  3879. x264_log( h, X264_LOG_INFO, "coded y intra: %.1f%%%s\n",
  3880. h->stat.i_mb_cbp[0] * 100.0 / (i_all_intra*4), buf );
  3881. }
  3882. int64_t fixed_pred_modes[4][9] = {{0}};
  3883. int64_t sum_pred_modes[4] = {0};
  3884. for( int i = 0; i <= I_PRED_16x16_DC_128; i++ )
  3885. {
  3886. fixed_pred_modes[0][x264_mb_pred_mode16x16_fix[i]] += h->stat.i_mb_pred_mode[0][i];
  3887. sum_pred_modes[0] += h->stat.i_mb_pred_mode[0][i];
  3888. }
  3889. if( sum_pred_modes[0] )
  3890. x264_log( h, X264_LOG_INFO, "i16 v,h,dc,p: %2.0f%% %2.0f%% %2.0f%% %2.0f%%\n",
  3891. fixed_pred_modes[0][0] * 100.0 / sum_pred_modes[0],
  3892. fixed_pred_modes[0][1] * 100.0 / sum_pred_modes[0],
  3893. fixed_pred_modes[0][2] * 100.0 / sum_pred_modes[0],
  3894. fixed_pred_modes[0][3] * 100.0 / sum_pred_modes[0] );
  3895. for( int i = 1; i <= 2; i++ )
  3896. {
  3897. for( int j = 0; j <= I_PRED_8x8_DC_128; j++ )
  3898. {
  3899. fixed_pred_modes[i][x264_mb_pred_mode4x4_fix(j)] += h->stat.i_mb_pred_mode[i][j];
  3900. sum_pred_modes[i] += h->stat.i_mb_pred_mode[i][j];
  3901. }
  3902. if( sum_pred_modes[i] )
  3903. x264_log( h, X264_LOG_INFO, "i%d v,h,dc,ddl,ddr,vr,hd,vl,hu: %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%%\n", (3-i)*4,
  3904. fixed_pred_modes[i][0] * 100.0 / sum_pred_modes[i],
  3905. fixed_pred_modes[i][1] * 100.0 / sum_pred_modes[i],
  3906. fixed_pred_modes[i][2] * 100.0 / sum_pred_modes[i],
  3907. fixed_pred_modes[i][3] * 100.0 / sum_pred_modes[i],
  3908. fixed_pred_modes[i][4] * 100.0 / sum_pred_modes[i],
  3909. fixed_pred_modes[i][5] * 100.0 / sum_pred_modes[i],
  3910. fixed_pred_modes[i][6] * 100.0 / sum_pred_modes[i],
  3911. fixed_pred_modes[i][7] * 100.0 / sum_pred_modes[i],
  3912. fixed_pred_modes[i][8] * 100.0 / sum_pred_modes[i] );
  3913. }
  3914. for( int i = 0; i <= I_PRED_CHROMA_DC_128; i++ )
  3915. {
  3916. fixed_pred_modes[3][x264_mb_chroma_pred_mode_fix[i]] += h->stat.i_mb_pred_mode[3][i];
  3917. sum_pred_modes[3] += h->stat.i_mb_pred_mode[3][i];
  3918. }
  3919. if( sum_pred_modes[3] && !CHROMA444 )
  3920. x264_log( h, X264_LOG_INFO, "i8c dc,h,v,p: %2.0f%% %2.0f%% %2.0f%% %2.0f%%\n",
  3921. fixed_pred_modes[3][0] * 100.0 / sum_pred_modes[3],
  3922. fixed_pred_modes[3][1] * 100.0 / sum_pred_modes[3],
  3923. fixed_pred_modes[3][2] * 100.0 / sum_pred_modes[3],
  3924. fixed_pred_modes[3][3] * 100.0 / sum_pred_modes[3] );
  3925. if( h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE && h->stat.i_frame_count[SLICE_TYPE_P] > 0 )
  3926. {
  3927. buf[0] = 0;
  3928. if( CHROMA_FORMAT )
  3929. sprintf( buf, " UV:%.1f%%", h->stat.i_wpred[1] * 100.0 / h->stat.i_frame_count[SLICE_TYPE_P] );
  3930. x264_log( h, X264_LOG_INFO, "Weighted P-Frames: Y:%.1f%%%s\n",
  3931. h->stat.i_wpred[0] * 100.0 / h->stat.i_frame_count[SLICE_TYPE_P], buf );
  3932. }
  3933. for( int i_list = 0; i_list < 2; i_list++ )
  3934. for( int i_slice = 0; i_slice < 2; i_slice++ )
  3935. {
  3936. char *p = buf;
  3937. int64_t i_den = 0;
  3938. int i_max = 0;
  3939. for( int i = 0; i < X264_REF_MAX*2; i++ )
  3940. if( h->stat.i_mb_count_ref[i_slice][i_list][i] )
  3941. {
  3942. i_den += h->stat.i_mb_count_ref[i_slice][i_list][i];
  3943. i_max = i;
  3944. }
  3945. if( i_max == 0 )
  3946. continue;
  3947. for( int i = 0; i <= i_max; i++ )
  3948. p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i_list][i] / i_den );
  3949. x264_log( h, X264_LOG_INFO, "ref %c L%d:%s\n", "PB"[i_slice], i_list, buf );
  3950. }
  3951. if( h->param.analyse.b_ssim )
  3952. {
  3953. float ssim = SUM3( h->stat.f_ssim_mean_y ) / duration;
  3954. x264_log( h, X264_LOG_INFO, "SSIM Mean Y:%.7f (%6.3fdb)\n", ssim, calc_ssim_db( ssim ) );
  3955. }
  3956. if( h->param.analyse.b_psnr )
  3957. {
  3958. x264_log( h, X264_LOG_INFO,
  3959. "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
  3960. SUM3( h->stat.f_psnr_mean_y ) / duration,
  3961. SUM3( h->stat.f_psnr_mean_u ) / duration,
  3962. SUM3( h->stat.f_psnr_mean_v ) / duration,
  3963. SUM3( h->stat.f_psnr_average ) / duration,
  3964. calc_psnr( SUM3( h->stat.f_ssd_global ), duration * i_yuv_size ),
  3965. f_bitrate );
  3966. }
  3967. else
  3968. x264_log( h, X264_LOG_INFO, "kb/s:%.2f\n", f_bitrate );
  3969. }
  3970. /* rc */
  3971. x264_ratecontrol_delete( h );
  3972. /* param */
  3973. if( h->param.rc.psz_stat_out )
  3974. free( h->param.rc.psz_stat_out );
  3975. if( h->param.rc.psz_stat_in )
  3976. free( h->param.rc.psz_stat_in );
  3977. x264_cqm_delete( h );
  3978. x264_free( h->nal_buffer );
  3979. x264_free( h->reconfig_h );
  3980. x264_analyse_free_costs( h );
  3981. x264_free( h->cost_table );
  3982. if( h->i_thread_frames > 1 )
  3983. h = h->thread[h->i_thread_phase];
  3984. /* frames */
  3985. x264_frame_delete_list( h->frames.unused[0] );
  3986. x264_frame_delete_list( h->frames.unused[1] );
  3987. x264_frame_delete_list( h->frames.current );
  3988. x264_frame_delete_list( h->frames.blank_unused );
  3989. h = h->thread[0];
  3990. for( int i = 0; i < h->i_thread_frames; i++ )
  3991. if( h->thread[i]->b_thread_active )
  3992. for( int j = 0; j < h->thread[i]->i_ref[0]; j++ )
  3993. if( h->thread[i]->fref[0][j] && h->thread[i]->fref[0][j]->b_duplicate )
  3994. x264_frame_delete( h->thread[i]->fref[0][j] );
  3995. if( h->param.i_lookahead_threads > 1 )
  3996. for( int i = 0; i < h->param.i_lookahead_threads; i++ )
  3997. x264_free( h->lookahead_thread[i] );
  3998. for( int i = h->param.i_threads - 1; i >= 0; i-- )
  3999. {
  4000. x264_frame_t **frame;
  4001. if( !h->param.b_sliced_threads || i == 0 )
  4002. {
  4003. for( frame = h->thread[i]->frames.reference; *frame; frame++ )
  4004. {
  4005. assert( (*frame)->i_reference_count > 0 );
  4006. (*frame)->i_reference_count--;
  4007. if( (*frame)->i_reference_count == 0 )
  4008. x264_frame_delete( *frame );
  4009. }
  4010. frame = &h->thread[i]->fdec;
  4011. if( *frame )
  4012. {
  4013. assert( (*frame)->i_reference_count > 0 );
  4014. (*frame)->i_reference_count--;
  4015. if( (*frame)->i_reference_count == 0 )
  4016. x264_frame_delete( *frame );
  4017. }
  4018. x264_macroblock_cache_free( h->thread[i] );
  4019. }
  4020. x264_macroblock_thread_free( h->thread[i], 0 );
  4021. x264_free( h->thread[i]->out.p_bitstream );
  4022. x264_free( h->thread[i]->out.nal );
  4023. x264_pthread_mutex_destroy( &h->thread[i]->mutex );
  4024. x264_pthread_cond_destroy( &h->thread[i]->cv );
  4025. x264_free( h->thread[i] );
  4026. }
  4027. #if HAVE_OPENCL
  4028. x264_opencl_close_library( ocl );
  4029. #endif
  4030. }
  4031. int x264_encoder_delayed_frames( x264_t *h )
  4032. {
  4033. int delayed_frames = 0;
  4034. if( h->i_thread_frames > 1 )
  4035. {
  4036. for( int i = 0; i < h->i_thread_frames; i++ )
  4037. delayed_frames += h->thread[i]->b_thread_active;
  4038. h = h->thread[h->i_thread_phase];
  4039. }
  4040. for( int i = 0; h->frames.current[i]; i++ )
  4041. delayed_frames++;
  4042. x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  4043. x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  4044. x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  4045. delayed_frames += h->lookahead->ifbuf.i_size + h->lookahead->next.i_size + h->lookahead->ofbuf.i_size;
  4046. x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  4047. x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  4048. x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
  4049. return delayed_frames;
  4050. }
  4051. int x264_encoder_maximum_delayed_frames( x264_t *h )
  4052. {
  4053. return h->frames.i_delay;
  4054. }