mpegvideo_enc.c 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831
  1. /*
  2. * The simplest mpeg encoder (well, it was the simplest!)
  3. * Copyright (c) 2000,2001 Fabrice Bellard
  4. * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  5. *
  6. * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  7. *
  8. * This file is part of Libav.
  9. *
  10. * Libav is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * Libav 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 GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with Libav; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. /**
  25. * @file
  26. * The simplest mpeg encoder (well, it was the simplest!).
  27. */
  28. #include "libavutil/intmath.h"
  29. #include "avcodec.h"
  30. #include "dsputil.h"
  31. #include "mpegvideo.h"
  32. #include "mpegvideo_common.h"
  33. #include "h263.h"
  34. #include "mjpegenc.h"
  35. #include "msmpeg4.h"
  36. #include "faandct.h"
  37. #include "thread.h"
  38. #include "aandcttab.h"
  39. #include "flv.h"
  40. #include "mpeg4video.h"
  41. #include "internal.h"
  42. #include <limits.h>
  43. //#undef NDEBUG
  44. //#include <assert.h>
  45. static int encode_picture(MpegEncContext *s, int picture_number);
  46. static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
  47. static int sse_mb(MpegEncContext *s);
  48. static void denoise_dct_c(MpegEncContext *s, DCTELEM *block);
  49. static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
  50. /* enable all paranoid tests for rounding, overflows, etc... */
  51. //#define PARANOID
  52. //#define DEBUG
  53. static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
  54. static uint8_t default_fcode_tab[MAX_MV*2+1];
  55. void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
  56. const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
  57. {
  58. int qscale;
  59. int shift=0;
  60. for(qscale=qmin; qscale<=qmax; qscale++){
  61. int i;
  62. if (dsp->fdct == ff_jpeg_fdct_islow
  63. #ifdef FAAN_POSTSCALE
  64. || dsp->fdct == ff_faandct
  65. #endif
  66. ) {
  67. for(i=0;i<64;i++) {
  68. const int j= dsp->idct_permutation[i];
  69. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  70. /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  71. /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
  72. /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  73. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
  74. (qscale * quant_matrix[j]));
  75. }
  76. } else if (dsp->fdct == fdct_ifast
  77. #ifndef FAAN_POSTSCALE
  78. || dsp->fdct == ff_faandct
  79. #endif
  80. ) {
  81. for(i=0;i<64;i++) {
  82. const int j= dsp->idct_permutation[i];
  83. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  84. /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  85. /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
  86. /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  87. qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
  88. (ff_aanscales[i] * qscale * quant_matrix[j]));
  89. }
  90. } else {
  91. for(i=0;i<64;i++) {
  92. const int j= dsp->idct_permutation[i];
  93. /* We can safely suppose that 16 <= quant_matrix[i] <= 255
  94. So 16 <= qscale * quant_matrix[i] <= 7905
  95. so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
  96. so 32768 >= (1<<19) / (qscale * quant_matrix[i]) >= 67
  97. */
  98. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
  99. // qmat [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
  100. qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
  101. if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
  102. qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
  103. }
  104. }
  105. for(i=intra; i<64; i++){
  106. int64_t max= 8191;
  107. if (dsp->fdct == fdct_ifast
  108. #ifndef FAAN_POSTSCALE
  109. || dsp->fdct == ff_faandct
  110. #endif
  111. ) {
  112. max = (8191LL*ff_aanscales[i]) >> 14;
  113. }
  114. while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
  115. shift++;
  116. }
  117. }
  118. }
  119. if(shift){
  120. av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
  121. }
  122. }
  123. static inline void update_qscale(MpegEncContext *s){
  124. s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  125. s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
  126. s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
  127. }
  128. void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
  129. int i;
  130. if(matrix){
  131. put_bits(pb, 1, 1);
  132. for(i=0;i<64;i++) {
  133. put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
  134. }
  135. }else
  136. put_bits(pb, 1, 0);
  137. }
  138. /**
  139. * init s->current_picture.qscale_table from s->lambda_table
  140. */
  141. void ff_init_qscale_tab(MpegEncContext *s){
  142. int8_t * const qscale_table= s->current_picture.qscale_table;
  143. int i;
  144. for(i=0; i<s->mb_num; i++){
  145. unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
  146. int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  147. qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
  148. }
  149. }
  150. static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
  151. int i;
  152. dst->pict_type = src->pict_type;
  153. dst->quality = src->quality;
  154. dst->coded_picture_number = src->coded_picture_number;
  155. dst->display_picture_number = src->display_picture_number;
  156. // dst->reference = src->reference;
  157. dst->pts = src->pts;
  158. dst->interlaced_frame = src->interlaced_frame;
  159. dst->top_field_first = src->top_field_first;
  160. if(s->avctx->me_threshold){
  161. if(!src->motion_val[0])
  162. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
  163. if(!src->mb_type)
  164. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
  165. if(!src->ref_index[0])
  166. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
  167. if(src->motion_subsample_log2 != dst->motion_subsample_log2)
  168. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
  169. src->motion_subsample_log2, dst->motion_subsample_log2);
  170. memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
  171. for(i=0; i<2; i++){
  172. int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
  173. int height= ((16*s->mb_height)>>src->motion_subsample_log2);
  174. if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
  175. memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
  176. }
  177. if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
  178. memcpy(dst->ref_index[i], src->ref_index[i], s->mb_stride*4*s->mb_height*sizeof(int8_t));
  179. }
  180. }
  181. }
  182. }
  183. static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  184. #define COPY(a) dst->a= src->a
  185. COPY(pict_type);
  186. COPY(current_picture);
  187. COPY(f_code);
  188. COPY(b_code);
  189. COPY(qscale);
  190. COPY(lambda);
  191. COPY(lambda2);
  192. COPY(picture_in_gop_number);
  193. COPY(gop_picture_number);
  194. COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
  195. COPY(progressive_frame); //FIXME don't set in encode_header
  196. COPY(partitioned_frame); //FIXME don't set in encode_header
  197. #undef COPY
  198. }
  199. /**
  200. * sets the given MpegEncContext to defaults for encoding.
  201. * the changed fields will not depend upon the prior state of the MpegEncContext.
  202. */
  203. static void MPV_encode_defaults(MpegEncContext *s){
  204. int i;
  205. MPV_common_defaults(s);
  206. for(i=-16; i<16; i++){
  207. default_fcode_tab[i + MAX_MV]= 1;
  208. }
  209. s->me.mv_penalty= default_mv_penalty;
  210. s->fcode_tab= default_fcode_tab;
  211. }
  212. /* init video encoder */
  213. av_cold int MPV_encode_init(AVCodecContext *avctx)
  214. {
  215. MpegEncContext *s = avctx->priv_data;
  216. int i;
  217. int chroma_h_shift, chroma_v_shift;
  218. MPV_encode_defaults(s);
  219. switch (avctx->codec_id) {
  220. case CODEC_ID_MPEG2VIDEO:
  221. if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
  222. av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
  223. return -1;
  224. }
  225. break;
  226. case CODEC_ID_LJPEG:
  227. if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_YUVJ444P && avctx->pix_fmt != PIX_FMT_BGRA &&
  228. ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P && avctx->pix_fmt != PIX_FMT_YUV444P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
  229. av_log(avctx, AV_LOG_ERROR, "colorspace not supported in LJPEG\n");
  230. return -1;
  231. }
  232. break;
  233. case CODEC_ID_MJPEG:
  234. if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P &&
  235. ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_UNOFFICIAL)){
  236. av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
  237. return -1;
  238. }
  239. break;
  240. default:
  241. if(avctx->pix_fmt != PIX_FMT_YUV420P){
  242. av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
  243. return -1;
  244. }
  245. }
  246. switch (avctx->pix_fmt) {
  247. case PIX_FMT_YUVJ422P:
  248. case PIX_FMT_YUV422P:
  249. s->chroma_format = CHROMA_422;
  250. break;
  251. case PIX_FMT_YUVJ420P:
  252. case PIX_FMT_YUV420P:
  253. default:
  254. s->chroma_format = CHROMA_420;
  255. break;
  256. }
  257. s->bit_rate = avctx->bit_rate;
  258. s->width = avctx->width;
  259. s->height = avctx->height;
  260. if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
  261. av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
  262. avctx->gop_size=600;
  263. }
  264. s->gop_size = avctx->gop_size;
  265. s->avctx = avctx;
  266. s->flags= avctx->flags;
  267. s->flags2= avctx->flags2;
  268. s->max_b_frames= avctx->max_b_frames;
  269. s->codec_id= avctx->codec->id;
  270. s->luma_elim_threshold = avctx->luma_elim_threshold;
  271. s->chroma_elim_threshold= avctx->chroma_elim_threshold;
  272. s->strict_std_compliance= avctx->strict_std_compliance;
  273. s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
  274. s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
  275. s->mpeg_quant= avctx->mpeg_quant;
  276. s->rtp_mode= !!avctx->rtp_payload_size;
  277. s->intra_dc_precision= avctx->intra_dc_precision;
  278. s->user_specified_pts = AV_NOPTS_VALUE;
  279. if (s->gop_size <= 1) {
  280. s->intra_only = 1;
  281. s->gop_size = 12;
  282. } else {
  283. s->intra_only = 0;
  284. }
  285. s->me_method = avctx->me_method;
  286. /* Fixed QSCALE */
  287. s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
  288. s->adaptive_quant= ( s->avctx->lumi_masking
  289. || s->avctx->dark_masking
  290. || s->avctx->temporal_cplx_masking
  291. || s->avctx->spatial_cplx_masking
  292. || s->avctx->p_masking
  293. || s->avctx->border_masking
  294. || (s->flags&CODEC_FLAG_QP_RD))
  295. && !s->fixed_qscale;
  296. s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
  297. s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
  298. s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
  299. s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
  300. s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
  301. if(avctx->rc_max_rate && !avctx->rc_buffer_size){
  302. av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
  303. return -1;
  304. }
  305. if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
  306. av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
  307. }
  308. if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
  309. av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
  310. return -1;
  311. }
  312. if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
  313. av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
  314. return -1;
  315. }
  316. if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
  317. av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
  318. }
  319. if(avctx->rc_buffer_size && avctx->bit_rate*(int64_t)avctx->time_base.num > avctx->rc_buffer_size * (int64_t)avctx->time_base.den){
  320. av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
  321. return -1;
  322. }
  323. if(!s->fixed_qscale && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
  324. av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
  325. return -1;
  326. }
  327. if( s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
  328. && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
  329. && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
  330. av_log(avctx, AV_LOG_INFO, "Warning vbv_delay will be set to 0xFFFF (=VBR) as the specified vbv buffer is too large for the given bitrate!\n");
  331. }
  332. if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
  333. && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
  334. av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
  335. return -1;
  336. }
  337. if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
  338. av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
  339. return -1;
  340. }
  341. if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
  342. av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
  343. return -1;
  344. }
  345. if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
  346. av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
  347. return -1;
  348. }
  349. if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
  350. av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
  351. return -1;
  352. }
  353. if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
  354. av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
  355. return -1;
  356. }
  357. if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
  358. s->codec_id == CODEC_ID_H263P) &&
  359. (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
  360. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
  361. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  362. return -1;
  363. }
  364. if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
  365. && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
  366. av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
  367. return -1;
  368. }
  369. if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
  370. av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
  371. return -1;
  372. }
  373. if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
  374. av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
  375. return -1;
  376. }
  377. if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
  378. av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
  379. return -1;
  380. }
  381. if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
  382. av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
  383. return -1;
  384. }
  385. if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
  386. av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
  387. return -1;
  388. }
  389. if(s->flags & CODEC_FLAG_LOW_DELAY){
  390. if (s->codec_id != CODEC_ID_MPEG2VIDEO){
  391. av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
  392. return -1;
  393. }
  394. if (s->max_b_frames != 0){
  395. av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
  396. return -1;
  397. }
  398. }
  399. if(s->q_scale_type == 1){
  400. if(s->codec_id != CODEC_ID_MPEG2VIDEO){
  401. av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
  402. return -1;
  403. }
  404. if(avctx->qmax > 12){
  405. av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
  406. return -1;
  407. }
  408. }
  409. if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
  410. && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
  411. && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
  412. av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
  413. return -1;
  414. }
  415. if(s->avctx->thread_count < 1){
  416. av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
  417. return -1;
  418. }
  419. if(s->avctx->thread_count > 1)
  420. s->rtp_mode= 1;
  421. if(!avctx->time_base.den || !avctx->time_base.num){
  422. av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
  423. return -1;
  424. }
  425. i= (INT_MAX/2+128)>>8;
  426. if(avctx->me_threshold >= i){
  427. av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
  428. return -1;
  429. }
  430. if(avctx->mb_threshold >= i){
  431. av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
  432. return -1;
  433. }
  434. if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
  435. av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
  436. avctx->b_frame_strategy = 0;
  437. }
  438. i= av_gcd(avctx->time_base.den, avctx->time_base.num);
  439. if(i > 1){
  440. av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
  441. avctx->time_base.den /= i;
  442. avctx->time_base.num /= i;
  443. // return -1;
  444. }
  445. if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO || s->codec_id==CODEC_ID_MJPEG){
  446. s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
  447. s->inter_quant_bias= 0;
  448. }else{
  449. s->intra_quant_bias=0;
  450. s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
  451. }
  452. if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
  453. s->intra_quant_bias= avctx->intra_quant_bias;
  454. if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
  455. s->inter_quant_bias= avctx->inter_quant_bias;
  456. avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
  457. if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
  458. av_log(avctx, AV_LOG_ERROR, "timebase %d/%d not supported by MPEG 4 standard, "
  459. "the maximum admitted value for the timebase denominator is %d\n",
  460. s->avctx->time_base.num, s->avctx->time_base.den, (1<<16)-1);
  461. return -1;
  462. }
  463. s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
  464. switch(avctx->codec->id) {
  465. case CODEC_ID_MPEG1VIDEO:
  466. s->out_format = FMT_MPEG1;
  467. s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
  468. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  469. break;
  470. case CODEC_ID_MPEG2VIDEO:
  471. s->out_format = FMT_MPEG1;
  472. s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
  473. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  474. s->rtp_mode= 1;
  475. break;
  476. case CODEC_ID_LJPEG:
  477. case CODEC_ID_MJPEG:
  478. s->out_format = FMT_MJPEG;
  479. s->intra_only = 1; /* force intra only for jpeg */
  480. if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
  481. s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
  482. s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
  483. s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
  484. }else{
  485. s->mjpeg_vsample[0] = 2;
  486. s->mjpeg_vsample[1] = 2>>chroma_v_shift;
  487. s->mjpeg_vsample[2] = 2>>chroma_v_shift;
  488. s->mjpeg_hsample[0] = 2;
  489. s->mjpeg_hsample[1] = 2>>chroma_h_shift;
  490. s->mjpeg_hsample[2] = 2>>chroma_h_shift;
  491. }
  492. if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
  493. || ff_mjpeg_encode_init(s) < 0)
  494. return -1;
  495. avctx->delay=0;
  496. s->low_delay=1;
  497. break;
  498. case CODEC_ID_H261:
  499. if (!CONFIG_H261_ENCODER) return -1;
  500. if (ff_h261_get_picture_format(s->width, s->height) < 0) {
  501. av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.261 codec.\nValid sizes are 176x144, 352x288\n", s->width, s->height);
  502. return -1;
  503. }
  504. s->out_format = FMT_H261;
  505. avctx->delay=0;
  506. s->low_delay=1;
  507. break;
  508. case CODEC_ID_H263:
  509. if (!CONFIG_H263_ENCODER) return -1;
  510. if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 8) {
  511. av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
  512. return -1;
  513. }
  514. s->out_format = FMT_H263;
  515. s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
  516. avctx->delay=0;
  517. s->low_delay=1;
  518. break;
  519. case CODEC_ID_H263P:
  520. s->out_format = FMT_H263;
  521. s->h263_plus = 1;
  522. /* Fx */
  523. s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
  524. s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
  525. s->modified_quant= s->h263_aic;
  526. s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
  527. s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
  528. s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
  529. s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
  530. s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
  531. /* /Fx */
  532. /* These are just to be sure */
  533. avctx->delay=0;
  534. s->low_delay=1;
  535. break;
  536. case CODEC_ID_FLV1:
  537. s->out_format = FMT_H263;
  538. s->h263_flv = 2; /* format = 1; 11-bit codes */
  539. s->unrestricted_mv = 1;
  540. s->rtp_mode=0; /* don't allow GOB */
  541. avctx->delay=0;
  542. s->low_delay=1;
  543. break;
  544. case CODEC_ID_RV10:
  545. s->out_format = FMT_H263;
  546. avctx->delay=0;
  547. s->low_delay=1;
  548. break;
  549. case CODEC_ID_RV20:
  550. s->out_format = FMT_H263;
  551. avctx->delay=0;
  552. s->low_delay=1;
  553. s->modified_quant=1;
  554. s->h263_aic=1;
  555. s->h263_plus=1;
  556. s->loop_filter=1;
  557. s->unrestricted_mv= 0;
  558. break;
  559. case CODEC_ID_MPEG4:
  560. s->out_format = FMT_H263;
  561. s->h263_pred = 1;
  562. s->unrestricted_mv = 1;
  563. s->low_delay= s->max_b_frames ? 0 : 1;
  564. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  565. break;
  566. case CODEC_ID_MSMPEG4V2:
  567. s->out_format = FMT_H263;
  568. s->h263_pred = 1;
  569. s->unrestricted_mv = 1;
  570. s->msmpeg4_version= 2;
  571. avctx->delay=0;
  572. s->low_delay=1;
  573. break;
  574. case CODEC_ID_MSMPEG4V3:
  575. s->out_format = FMT_H263;
  576. s->h263_pred = 1;
  577. s->unrestricted_mv = 1;
  578. s->msmpeg4_version= 3;
  579. s->flipflop_rounding=1;
  580. avctx->delay=0;
  581. s->low_delay=1;
  582. break;
  583. case CODEC_ID_WMV1:
  584. s->out_format = FMT_H263;
  585. s->h263_pred = 1;
  586. s->unrestricted_mv = 1;
  587. s->msmpeg4_version= 4;
  588. s->flipflop_rounding=1;
  589. avctx->delay=0;
  590. s->low_delay=1;
  591. break;
  592. case CODEC_ID_WMV2:
  593. s->out_format = FMT_H263;
  594. s->h263_pred = 1;
  595. s->unrestricted_mv = 1;
  596. s->msmpeg4_version= 5;
  597. s->flipflop_rounding=1;
  598. avctx->delay=0;
  599. s->low_delay=1;
  600. break;
  601. default:
  602. return -1;
  603. }
  604. avctx->has_b_frames= !s->low_delay;
  605. s->encoding = 1;
  606. s->progressive_frame=
  607. s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
  608. /* init */
  609. if (MPV_common_init(s) < 0)
  610. return -1;
  611. if(!s->dct_quantize)
  612. s->dct_quantize = dct_quantize_c;
  613. if(!s->denoise_dct)
  614. s->denoise_dct = denoise_dct_c;
  615. s->fast_dct_quantize = s->dct_quantize;
  616. if(avctx->trellis)
  617. s->dct_quantize = dct_quantize_trellis_c;
  618. if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
  619. s->chroma_qscale_table= ff_h263_chroma_qscale_table;
  620. s->quant_precision=5;
  621. ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
  622. ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
  623. if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
  624. ff_h261_encode_init(s);
  625. if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  626. h263_encode_init(s);
  627. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  628. ff_msmpeg4_encode_init(s);
  629. if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  630. && s->out_format == FMT_MPEG1)
  631. ff_mpeg1_encode_init(s);
  632. /* init q matrix */
  633. for(i=0;i<64;i++) {
  634. int j= s->dsp.idct_permutation[i];
  635. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
  636. s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
  637. s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
  638. }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  639. s->intra_matrix[j] =
  640. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  641. }else
  642. { /* mpeg1/2 */
  643. s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
  644. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  645. }
  646. if(s->avctx->intra_matrix)
  647. s->intra_matrix[j] = s->avctx->intra_matrix[i];
  648. if(s->avctx->inter_matrix)
  649. s->inter_matrix[j] = s->avctx->inter_matrix[i];
  650. }
  651. /* precompute matrix */
  652. /* for mjpeg, we do include qscale in the matrix */
  653. if (s->out_format != FMT_MJPEG) {
  654. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  655. s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
  656. ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
  657. s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
  658. }
  659. if(ff_rate_control_init(s) < 0)
  660. return -1;
  661. return 0;
  662. }
  663. av_cold int MPV_encode_end(AVCodecContext *avctx)
  664. {
  665. MpegEncContext *s = avctx->priv_data;
  666. ff_rate_control_uninit(s);
  667. MPV_common_end(s);
  668. if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
  669. ff_mjpeg_encode_close(s);
  670. av_freep(&avctx->extradata);
  671. return 0;
  672. }
  673. static int get_sae(uint8_t *src, int ref, int stride){
  674. int x,y;
  675. int acc=0;
  676. for(y=0; y<16; y++){
  677. for(x=0; x<16; x++){
  678. acc+= FFABS(src[x+y*stride] - ref);
  679. }
  680. }
  681. return acc;
  682. }
  683. static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
  684. int x, y, w, h;
  685. int acc=0;
  686. w= s->width &~15;
  687. h= s->height&~15;
  688. for(y=0; y<h; y+=16){
  689. for(x=0; x<w; x+=16){
  690. int offset= x + y*stride;
  691. int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
  692. int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
  693. int sae = get_sae(src + offset, mean, stride);
  694. acc+= sae + 500 < sad;
  695. }
  696. }
  697. return acc;
  698. }
  699. static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
  700. AVFrame *pic=NULL;
  701. int64_t pts;
  702. int i;
  703. const int encoding_delay= s->max_b_frames;
  704. int direct=1;
  705. if(pic_arg){
  706. pts= pic_arg->pts;
  707. pic_arg->display_picture_number= s->input_picture_number++;
  708. if(pts != AV_NOPTS_VALUE){
  709. if(s->user_specified_pts != AV_NOPTS_VALUE){
  710. int64_t time= pts;
  711. int64_t last= s->user_specified_pts;
  712. if(time <= last){
  713. av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
  714. return -1;
  715. }
  716. }
  717. s->user_specified_pts= pts;
  718. }else{
  719. if(s->user_specified_pts != AV_NOPTS_VALUE){
  720. s->user_specified_pts=
  721. pts= s->user_specified_pts + 1;
  722. av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
  723. }else{
  724. pts= pic_arg->display_picture_number;
  725. }
  726. }
  727. }
  728. if(pic_arg){
  729. if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
  730. if(pic_arg->linesize[0] != s->linesize) direct=0;
  731. if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
  732. if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
  733. // av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
  734. if(direct){
  735. i= ff_find_unused_picture(s, 1);
  736. pic= (AVFrame*)&s->picture[i];
  737. pic->reference= 3;
  738. for(i=0; i<4; i++){
  739. pic->data[i]= pic_arg->data[i];
  740. pic->linesize[i]= pic_arg->linesize[i];
  741. }
  742. if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
  743. return -1;
  744. }
  745. }else{
  746. i= ff_find_unused_picture(s, 0);
  747. pic= (AVFrame*)&s->picture[i];
  748. pic->reference= 3;
  749. if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
  750. return -1;
  751. }
  752. if( pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
  753. && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
  754. && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
  755. // empty
  756. }else{
  757. int h_chroma_shift, v_chroma_shift;
  758. avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  759. for(i=0; i<3; i++){
  760. int src_stride= pic_arg->linesize[i];
  761. int dst_stride= i ? s->uvlinesize : s->linesize;
  762. int h_shift= i ? h_chroma_shift : 0;
  763. int v_shift= i ? v_chroma_shift : 0;
  764. int w= s->width >>h_shift;
  765. int h= s->height>>v_shift;
  766. uint8_t *src= pic_arg->data[i];
  767. uint8_t *dst= pic->data[i];
  768. if(!s->avctx->rc_buffer_size)
  769. dst +=INPLACE_OFFSET;
  770. if(src_stride==dst_stride)
  771. memcpy(dst, src, src_stride*h);
  772. else{
  773. while(h--){
  774. memcpy(dst, src, w);
  775. dst += dst_stride;
  776. src += src_stride;
  777. }
  778. }
  779. }
  780. }
  781. }
  782. copy_picture_attributes(s, pic, pic_arg);
  783. pic->pts= pts; //we set this here to avoid modifiying pic_arg
  784. }
  785. /* shift buffer entries */
  786. for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
  787. s->input_picture[i-1]= s->input_picture[i];
  788. s->input_picture[encoding_delay]= (Picture*)pic;
  789. return 0;
  790. }
  791. static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
  792. int x, y, plane;
  793. int score=0;
  794. int64_t score64=0;
  795. for(plane=0; plane<3; plane++){
  796. const int stride= p->linesize[plane];
  797. const int bw= plane ? 1 : 2;
  798. for(y=0; y<s->mb_height*bw; y++){
  799. for(x=0; x<s->mb_width*bw; x++){
  800. int off= p->type == FF_BUFFER_TYPE_SHARED ? 0: 16;
  801. int v= s->dsp.frame_skip_cmp[1](s, p->data[plane] + 8*(x + y*stride)+off, ref->data[plane] + 8*(x + y*stride), stride, 8);
  802. switch(s->avctx->frame_skip_exp){
  803. case 0: score= FFMAX(score, v); break;
  804. case 1: score+= FFABS(v);break;
  805. case 2: score+= v*v;break;
  806. case 3: score64+= FFABS(v*v*(int64_t)v);break;
  807. case 4: score64+= v*v*(int64_t)(v*v);break;
  808. }
  809. }
  810. }
  811. }
  812. if(score) score64= score;
  813. if(score64 < s->avctx->frame_skip_threshold)
  814. return 1;
  815. if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
  816. return 1;
  817. return 0;
  818. }
  819. static int estimate_best_b_count(MpegEncContext *s){
  820. AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
  821. AVCodecContext *c= avcodec_alloc_context();
  822. AVFrame input[FF_MAX_B_FRAMES+2];
  823. const int scale= s->avctx->brd_scale;
  824. int i, j, out_size, p_lambda, b_lambda, lambda2;
  825. int outbuf_size= s->width * s->height; //FIXME
  826. uint8_t *outbuf= av_malloc(outbuf_size);
  827. int64_t best_rd= INT64_MAX;
  828. int best_b_count= -1;
  829. assert(scale>=0 && scale <=3);
  830. // emms_c();
  831. p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
  832. b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  833. if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
  834. lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
  835. c->width = s->width >> scale;
  836. c->height= s->height>> scale;
  837. c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
  838. c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
  839. c->mb_decision= s->avctx->mb_decision;
  840. c->me_cmp= s->avctx->me_cmp;
  841. c->mb_cmp= s->avctx->mb_cmp;
  842. c->me_sub_cmp= s->avctx->me_sub_cmp;
  843. c->pix_fmt = PIX_FMT_YUV420P;
  844. c->time_base= s->avctx->time_base;
  845. c->max_b_frames= s->max_b_frames;
  846. if (avcodec_open2(c, codec, NULL) < 0)
  847. return -1;
  848. for(i=0; i<s->max_b_frames+2; i++){
  849. int ysize= c->width*c->height;
  850. int csize= (c->width/2)*(c->height/2);
  851. Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
  852. avcodec_get_frame_defaults(&input[i]);
  853. input[i].data[0]= av_malloc(ysize + 2*csize);
  854. input[i].data[1]= input[i].data[0] + ysize;
  855. input[i].data[2]= input[i].data[1] + csize;
  856. input[i].linesize[0]= c->width;
  857. input[i].linesize[1]=
  858. input[i].linesize[2]= c->width/2;
  859. if(pre_input_ptr && (!i || s->input_picture[i-1])) {
  860. pre_input= *pre_input_ptr;
  861. if(pre_input.type != FF_BUFFER_TYPE_SHARED && i) {
  862. pre_input.data[0]+=INPLACE_OFFSET;
  863. pre_input.data[1]+=INPLACE_OFFSET;
  864. pre_input.data[2]+=INPLACE_OFFSET;
  865. }
  866. s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0], pre_input.data[0], pre_input.linesize[0], c->width, c->height);
  867. s->dsp.shrink[scale](input[i].data[1], input[i].linesize[1], pre_input.data[1], pre_input.linesize[1], c->width>>1, c->height>>1);
  868. s->dsp.shrink[scale](input[i].data[2], input[i].linesize[2], pre_input.data[2], pre_input.linesize[2], c->width>>1, c->height>>1);
  869. }
  870. }
  871. for(j=0; j<s->max_b_frames+1; j++){
  872. int64_t rd=0;
  873. if(!s->input_picture[j])
  874. break;
  875. c->error[0]= c->error[1]= c->error[2]= 0;
  876. input[0].pict_type= AV_PICTURE_TYPE_I;
  877. input[0].quality= 1 * FF_QP2LAMBDA;
  878. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
  879. // rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  880. for(i=0; i<s->max_b_frames+1; i++){
  881. int is_p= i % (j+1) == j || i==s->max_b_frames;
  882. input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
  883. input[i+1].quality= is_p ? p_lambda : b_lambda;
  884. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
  885. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  886. }
  887. /* get the delayed frames */
  888. while(out_size){
  889. out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
  890. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  891. }
  892. rd += c->error[0] + c->error[1] + c->error[2];
  893. if(rd < best_rd){
  894. best_rd= rd;
  895. best_b_count= j;
  896. }
  897. }
  898. av_freep(&outbuf);
  899. avcodec_close(c);
  900. av_freep(&c);
  901. for(i=0; i<s->max_b_frames+2; i++){
  902. av_freep(&input[i].data[0]);
  903. }
  904. return best_b_count;
  905. }
  906. static int select_input_picture(MpegEncContext *s){
  907. int i;
  908. for(i=1; i<MAX_PICTURE_COUNT; i++)
  909. s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
  910. s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
  911. /* set next picture type & ordering */
  912. if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
  913. if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
  914. s->reordered_input_picture[0]= s->input_picture[0];
  915. s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_I;
  916. s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
  917. }else{
  918. int b_frames;
  919. if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
  920. if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
  921. //FIXME check that te gop check above is +-1 correct
  922. //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);
  923. if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
  924. for(i=0; i<4; i++)
  925. s->input_picture[0]->data[i]= NULL;
  926. s->input_picture[0]->type= 0;
  927. }else{
  928. assert( s->input_picture[0]->type==FF_BUFFER_TYPE_USER
  929. || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
  930. s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
  931. }
  932. emms_c();
  933. ff_vbv_update(s, 0);
  934. goto no_output_pic;
  935. }
  936. }
  937. if(s->flags&CODEC_FLAG_PASS2){
  938. for(i=0; i<s->max_b_frames+1; i++){
  939. int pict_num= s->input_picture[0]->display_picture_number + i;
  940. if(pict_num >= s->rc_context.num_entries)
  941. break;
  942. if(!s->input_picture[i]){
  943. s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
  944. break;
  945. }
  946. s->input_picture[i]->pict_type=
  947. s->rc_context.entry[pict_num].new_pict_type;
  948. }
  949. }
  950. if(s->avctx->b_frame_strategy==0){
  951. b_frames= s->max_b_frames;
  952. while(b_frames && !s->input_picture[b_frames]) b_frames--;
  953. }else if(s->avctx->b_frame_strategy==1){
  954. for(i=1; i<s->max_b_frames+1; i++){
  955. if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
  956. s->input_picture[i]->b_frame_score=
  957. get_intra_count(s, s->input_picture[i ]->data[0],
  958. s->input_picture[i-1]->data[0], s->linesize) + 1;
  959. }
  960. }
  961. for(i=0; i<s->max_b_frames+1; i++){
  962. if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
  963. }
  964. b_frames= FFMAX(0, i-1);
  965. /* reset scores */
  966. for(i=0; i<b_frames+1; i++){
  967. s->input_picture[i]->b_frame_score=0;
  968. }
  969. }else if(s->avctx->b_frame_strategy==2){
  970. b_frames= estimate_best_b_count(s);
  971. }else{
  972. av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  973. b_frames=0;
  974. }
  975. emms_c();
  976. //static int b_count=0;
  977. //b_count+= b_frames;
  978. //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
  979. for(i= b_frames - 1; i>=0; i--){
  980. int type= s->input_picture[i]->pict_type;
  981. if(type && type != AV_PICTURE_TYPE_B)
  982. b_frames= i;
  983. }
  984. if(s->input_picture[b_frames]->pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
  985. av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
  986. }
  987. if(s->picture_in_gop_number + b_frames >= s->gop_size){
  988. if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
  989. b_frames= s->gop_size - s->picture_in_gop_number - 1;
  990. }else{
  991. if(s->flags & CODEC_FLAG_CLOSED_GOP)
  992. b_frames=0;
  993. s->input_picture[b_frames]->pict_type= AV_PICTURE_TYPE_I;
  994. }
  995. }
  996. if( (s->flags & CODEC_FLAG_CLOSED_GOP)
  997. && b_frames
  998. && s->input_picture[b_frames]->pict_type== AV_PICTURE_TYPE_I)
  999. b_frames--;
  1000. s->reordered_input_picture[0]= s->input_picture[b_frames];
  1001. if(s->reordered_input_picture[0]->pict_type != AV_PICTURE_TYPE_I)
  1002. s->reordered_input_picture[0]->pict_type= AV_PICTURE_TYPE_P;
  1003. s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
  1004. for(i=0; i<b_frames; i++){
  1005. s->reordered_input_picture[i+1]= s->input_picture[i];
  1006. s->reordered_input_picture[i+1]->pict_type= AV_PICTURE_TYPE_B;
  1007. s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
  1008. }
  1009. }
  1010. }
  1011. no_output_pic:
  1012. if(s->reordered_input_picture[0]){
  1013. s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
  1014. ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
  1015. if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size){
  1016. // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
  1017. int i= ff_find_unused_picture(s, 0);
  1018. Picture *pic= &s->picture[i];
  1019. pic->reference = s->reordered_input_picture[0]->reference;
  1020. if(ff_alloc_picture(s, pic, 0) < 0){
  1021. return -1;
  1022. }
  1023. /* mark us unused / free shared pic */
  1024. if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
  1025. s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
  1026. for(i=0; i<4; i++)
  1027. s->reordered_input_picture[0]->data[i]= NULL;
  1028. s->reordered_input_picture[0]->type= 0;
  1029. copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
  1030. s->current_picture_ptr= pic;
  1031. }else{
  1032. // input is not a shared pix -> reuse buffer for current_pix
  1033. assert( s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
  1034. || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
  1035. s->current_picture_ptr= s->reordered_input_picture[0];
  1036. for(i=0; i<4; i++){
  1037. s->new_picture.data[i]+= INPLACE_OFFSET;
  1038. }
  1039. }
  1040. ff_copy_picture(&s->current_picture, s->current_picture_ptr);
  1041. s->picture_number= s->new_picture.display_picture_number;
  1042. //printf("dpn:%d\n", s->picture_number);
  1043. }else{
  1044. memset(&s->new_picture, 0, sizeof(Picture));
  1045. }
  1046. return 0;
  1047. }
  1048. int MPV_encode_picture(AVCodecContext *avctx,
  1049. unsigned char *buf, int buf_size, void *data)
  1050. {
  1051. MpegEncContext *s = avctx->priv_data;
  1052. AVFrame *pic_arg = data;
  1053. int i, stuffing_count, context_count = avctx->thread_count;
  1054. for(i=0; i<context_count; i++){
  1055. int start_y= s->thread_context[i]->start_mb_y;
  1056. int end_y= s->thread_context[i]-> end_mb_y;
  1057. int h= s->mb_height;
  1058. uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
  1059. uint8_t *end = buf + (size_t)(((int64_t) buf_size)* end_y/h);
  1060. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1061. }
  1062. s->picture_in_gop_number++;
  1063. if(load_input_picture(s, pic_arg) < 0)
  1064. return -1;
  1065. if(select_input_picture(s) < 0){
  1066. return -1;
  1067. }
  1068. /* output? */
  1069. if(s->new_picture.data[0]){
  1070. s->pict_type= s->new_picture.pict_type;
  1071. //emms_c();
  1072. //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
  1073. MPV_frame_start(s, avctx);
  1074. vbv_retry:
  1075. if (encode_picture(s, s->picture_number) < 0)
  1076. return -1;
  1077. avctx->header_bits = s->header_bits;
  1078. avctx->mv_bits = s->mv_bits;
  1079. avctx->misc_bits = s->misc_bits;
  1080. avctx->i_tex_bits = s->i_tex_bits;
  1081. avctx->p_tex_bits = s->p_tex_bits;
  1082. avctx->i_count = s->i_count;
  1083. avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
  1084. avctx->skip_count = s->skip_count;
  1085. MPV_frame_end(s);
  1086. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1087. ff_mjpeg_encode_picture_trailer(s);
  1088. if(avctx->rc_buffer_size){
  1089. RateControlContext *rcc= &s->rc_context;
  1090. int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1091. if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
  1092. s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
  1093. if(s->adaptive_quant){
  1094. int i;
  1095. for(i=0; i<s->mb_height*s->mb_stride; i++)
  1096. s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
  1097. }
  1098. s->mb_skipped = 0; //done in MPV_frame_start()
  1099. if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
  1100. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  1101. s->no_rounding ^= 1;
  1102. }
  1103. if(s->pict_type!=AV_PICTURE_TYPE_B){
  1104. s->time_base= s->last_time_base;
  1105. s->last_non_b_time= s->time - s->pp_time;
  1106. }
  1107. // av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
  1108. for(i=0; i<context_count; i++){
  1109. PutBitContext *pb= &s->thread_context[i]->pb;
  1110. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1111. }
  1112. goto vbv_retry;
  1113. }
  1114. assert(s->avctx->rc_max_rate);
  1115. }
  1116. if(s->flags&CODEC_FLAG_PASS1)
  1117. ff_write_pass1_stats(s);
  1118. for(i=0; i<4; i++){
  1119. s->current_picture_ptr->error[i]= s->current_picture.error[i];
  1120. avctx->error[i] += s->current_picture_ptr->error[i];
  1121. }
  1122. if(s->flags&CODEC_FLAG_PASS1)
  1123. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
  1124. flush_put_bits(&s->pb);
  1125. s->frame_bits = put_bits_count(&s->pb);
  1126. stuffing_count= ff_vbv_update(s, s->frame_bits);
  1127. if(stuffing_count){
  1128. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
  1129. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1130. return -1;
  1131. }
  1132. switch(s->codec_id){
  1133. case CODEC_ID_MPEG1VIDEO:
  1134. case CODEC_ID_MPEG2VIDEO:
  1135. while(stuffing_count--){
  1136. put_bits(&s->pb, 8, 0);
  1137. }
  1138. break;
  1139. case CODEC_ID_MPEG4:
  1140. put_bits(&s->pb, 16, 0);
  1141. put_bits(&s->pb, 16, 0x1C3);
  1142. stuffing_count -= 4;
  1143. while(stuffing_count--){
  1144. put_bits(&s->pb, 8, 0xFF);
  1145. }
  1146. break;
  1147. default:
  1148. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1149. }
  1150. flush_put_bits(&s->pb);
  1151. s->frame_bits = put_bits_count(&s->pb);
  1152. }
  1153. /* update mpeg1/2 vbv_delay for CBR */
  1154. if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
  1155. && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
  1156. int vbv_delay, min_delay;
  1157. double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
  1158. int minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
  1159. double bits = s->rc_context.buffer_index + minbits - inbits;
  1160. if(bits<0)
  1161. av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
  1162. assert(s->repeat_first_field==0);
  1163. vbv_delay= bits * 90000 / s->avctx->rc_max_rate;
  1164. min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
  1165. vbv_delay= FFMAX(vbv_delay, min_delay);
  1166. assert(vbv_delay < 0xFFFF);
  1167. s->vbv_delay_ptr[0] &= 0xF8;
  1168. s->vbv_delay_ptr[0] |= vbv_delay>>13;
  1169. s->vbv_delay_ptr[1] = vbv_delay>>5;
  1170. s->vbv_delay_ptr[2] &= 0x07;
  1171. s->vbv_delay_ptr[2] |= vbv_delay<<3;
  1172. avctx->vbv_delay = vbv_delay*300;
  1173. }
  1174. s->total_bits += s->frame_bits;
  1175. avctx->frame_bits = s->frame_bits;
  1176. }else{
  1177. assert((put_bits_ptr(&s->pb) == s->pb.buf));
  1178. s->frame_bits=0;
  1179. }
  1180. assert((s->frame_bits&7)==0);
  1181. return s->frame_bits/8;
  1182. }
  1183. static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
  1184. {
  1185. static const char tab[64]=
  1186. {3,2,2,1,1,1,1,1,
  1187. 1,1,1,1,1,1,1,1,
  1188. 1,1,1,1,1,1,1,1,
  1189. 0,0,0,0,0,0,0,0,
  1190. 0,0,0,0,0,0,0,0,
  1191. 0,0,0,0,0,0,0,0,
  1192. 0,0,0,0,0,0,0,0,
  1193. 0,0,0,0,0,0,0,0};
  1194. int score=0;
  1195. int run=0;
  1196. int i;
  1197. DCTELEM *block= s->block[n];
  1198. const int last_index= s->block_last_index[n];
  1199. int skip_dc;
  1200. if(threshold<0){
  1201. skip_dc=0;
  1202. threshold= -threshold;
  1203. }else
  1204. skip_dc=1;
  1205. /* Are all we could set to zero already zero? */
  1206. if(last_index<=skip_dc - 1) return;
  1207. for(i=0; i<=last_index; i++){
  1208. const int j = s->intra_scantable.permutated[i];
  1209. const int level = FFABS(block[j]);
  1210. if(level==1){
  1211. if(skip_dc && i==0) continue;
  1212. score+= tab[run];
  1213. run=0;
  1214. }else if(level>1){
  1215. return;
  1216. }else{
  1217. run++;
  1218. }
  1219. }
  1220. if(score >= threshold) return;
  1221. for(i=skip_dc; i<=last_index; i++){
  1222. const int j = s->intra_scantable.permutated[i];
  1223. block[j]=0;
  1224. }
  1225. if(block[0]) s->block_last_index[n]= 0;
  1226. else s->block_last_index[n]= -1;
  1227. }
  1228. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
  1229. {
  1230. int i;
  1231. const int maxlevel= s->max_qcoeff;
  1232. const int minlevel= s->min_qcoeff;
  1233. int overflow=0;
  1234. if(s->mb_intra){
  1235. i=1; //skip clipping of intra dc
  1236. }else
  1237. i=0;
  1238. for(;i<=last_index; i++){
  1239. const int j= s->intra_scantable.permutated[i];
  1240. int level = block[j];
  1241. if (level>maxlevel){
  1242. level=maxlevel;
  1243. overflow++;
  1244. }else if(level<minlevel){
  1245. level=minlevel;
  1246. overflow++;
  1247. }
  1248. block[j]= level;
  1249. }
  1250. if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1251. av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
  1252. }
  1253. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
  1254. int x, y;
  1255. //FIXME optimize
  1256. for(y=0; y<8; y++){
  1257. for(x=0; x<8; x++){
  1258. int x2, y2;
  1259. int sum=0;
  1260. int sqr=0;
  1261. int count=0;
  1262. for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
  1263. for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
  1264. int v= ptr[x2 + y2*stride];
  1265. sum += v;
  1266. sqr += v*v;
  1267. count++;
  1268. }
  1269. }
  1270. weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
  1271. }
  1272. }
  1273. }
  1274. static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
  1275. {
  1276. int16_t weight[8][64];
  1277. DCTELEM orig[8][64];
  1278. const int mb_x= s->mb_x;
  1279. const int mb_y= s->mb_y;
  1280. int i;
  1281. int skip_dct[8];
  1282. int dct_offset = s->linesize*8; //default for progressive frames
  1283. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1284. int wrap_y, wrap_c;
  1285. for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
  1286. if(s->adaptive_quant){
  1287. const int last_qp= s->qscale;
  1288. const int mb_xy= mb_x + mb_y*s->mb_stride;
  1289. s->lambda= s->lambda_table[mb_xy];
  1290. update_qscale(s);
  1291. if(!(s->flags&CODEC_FLAG_QP_RD)){
  1292. s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
  1293. s->dquant= s->qscale - last_qp;
  1294. if(s->out_format==FMT_H263){
  1295. s->dquant= av_clip(s->dquant, -2, 2);
  1296. if(s->codec_id==CODEC_ID_MPEG4){
  1297. if(!s->mb_intra){
  1298. if(s->pict_type == AV_PICTURE_TYPE_B){
  1299. if(s->dquant&1 || s->mv_dir&MV_DIRECT)
  1300. s->dquant= 0;
  1301. }
  1302. if(s->mv_type==MV_TYPE_8X8)
  1303. s->dquant=0;
  1304. }
  1305. }
  1306. }
  1307. }
  1308. ff_set_qscale(s, last_qp + s->dquant);
  1309. }else if(s->flags&CODEC_FLAG_QP_RD)
  1310. ff_set_qscale(s, s->qscale + s->dquant);
  1311. wrap_y = s->linesize;
  1312. wrap_c = s->uvlinesize;
  1313. ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  1314. ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1315. ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1316. if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
  1317. uint8_t *ebuf= s->edge_emu_buffer + 32;
  1318. s->dsp.emulated_edge_mc(ebuf , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width , s->height);
  1319. ptr_y= ebuf;
  1320. s->dsp.emulated_edge_mc(ebuf+18*wrap_y , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  1321. ptr_cb= ebuf+18*wrap_y;
  1322. s->dsp.emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  1323. ptr_cr= ebuf+18*wrap_y+8;
  1324. }
  1325. if (s->mb_intra) {
  1326. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1327. int progressive_score, interlaced_score;
  1328. s->interlaced_dct=0;
  1329. progressive_score= s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y, 8)
  1330. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
  1331. if(progressive_score > 0){
  1332. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y*2, 8)
  1333. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y , NULL, wrap_y*2, 8);
  1334. if(progressive_score > interlaced_score){
  1335. s->interlaced_dct=1;
  1336. dct_offset= wrap_y;
  1337. wrap_y<<=1;
  1338. if (s->chroma_format == CHROMA_422)
  1339. wrap_c<<=1;
  1340. }
  1341. }
  1342. }
  1343. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1344. s->dsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
  1345. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1346. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  1347. if(s->flags&CODEC_FLAG_GRAY){
  1348. skip_dct[4]= 1;
  1349. skip_dct[5]= 1;
  1350. }else{
  1351. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1352. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1353. if(!s->chroma_y_shift){ /* 422 */
  1354. s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
  1355. s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
  1356. }
  1357. }
  1358. }else{
  1359. op_pixels_func (*op_pix)[4];
  1360. qpel_mc_func (*op_qpix)[16];
  1361. uint8_t *dest_y, *dest_cb, *dest_cr;
  1362. dest_y = s->dest[0];
  1363. dest_cb = s->dest[1];
  1364. dest_cr = s->dest[2];
  1365. if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
  1366. op_pix = s->dsp.put_pixels_tab;
  1367. op_qpix= s->dsp.put_qpel_pixels_tab;
  1368. }else{
  1369. op_pix = s->dsp.put_no_rnd_pixels_tab;
  1370. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  1371. }
  1372. if (s->mv_dir & MV_DIR_FORWARD) {
  1373. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  1374. op_pix = s->dsp.avg_pixels_tab;
  1375. op_qpix= s->dsp.avg_qpel_pixels_tab;
  1376. }
  1377. if (s->mv_dir & MV_DIR_BACKWARD) {
  1378. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  1379. }
  1380. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1381. int progressive_score, interlaced_score;
  1382. s->interlaced_dct=0;
  1383. progressive_score= s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y, 8)
  1384. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
  1385. if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
  1386. if(progressive_score>0){
  1387. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y*2, 8)
  1388. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y , ptr_y + wrap_y , wrap_y*2, 8);
  1389. if(progressive_score > interlaced_score){
  1390. s->interlaced_dct=1;
  1391. dct_offset= wrap_y;
  1392. wrap_y<<=1;
  1393. if (s->chroma_format == CHROMA_422)
  1394. wrap_c<<=1;
  1395. }
  1396. }
  1397. }
  1398. s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
  1399. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1400. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
  1401. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
  1402. if(s->flags&CODEC_FLAG_GRAY){
  1403. skip_dct[4]= 1;
  1404. skip_dct[5]= 1;
  1405. }else{
  1406. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1407. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1408. if(!s->chroma_y_shift){ /* 422 */
  1409. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
  1410. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
  1411. }
  1412. }
  1413. /* pre quantization */
  1414. if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
  1415. //FIXME optimize
  1416. if(s->dsp.sad[1](NULL, ptr_y , dest_y , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
  1417. if(s->dsp.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
  1418. if(s->dsp.sad[1](NULL, ptr_y +dct_offset , dest_y +dct_offset , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
  1419. if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;
  1420. if(s->dsp.sad[1](NULL, ptr_cb , dest_cb , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
  1421. if(s->dsp.sad[1](NULL, ptr_cr , dest_cr , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
  1422. if(!s->chroma_y_shift){ /* 422 */
  1423. if(s->dsp.sad[1](NULL, ptr_cb +(dct_offset>>1), dest_cb +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[6]= 1;
  1424. if(s->dsp.sad[1](NULL, ptr_cr +(dct_offset>>1), dest_cr +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[7]= 1;
  1425. }
  1426. }
  1427. }
  1428. if(s->avctx->quantizer_noise_shaping){
  1429. if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y , wrap_y);
  1430. if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1431. if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1432. if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1433. if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb , wrap_c);
  1434. if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr , wrap_c);
  1435. if(!s->chroma_y_shift){ /* 422 */
  1436. if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
  1437. if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
  1438. }
  1439. memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
  1440. }
  1441. /* DCT & quantize */
  1442. assert(s->out_format!=FMT_MJPEG || s->qscale==8);
  1443. {
  1444. for(i=0;i<mb_block_count;i++) {
  1445. if(!skip_dct[i]){
  1446. int overflow;
  1447. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1448. // FIXME we could decide to change to quantizer instead of clipping
  1449. // JS: I don't think that would be a good idea it could lower quality instead
  1450. // of improve it. Just INTRADC clipping deserves changes in quantizer
  1451. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1452. }else
  1453. s->block_last_index[i]= -1;
  1454. }
  1455. if(s->avctx->quantizer_noise_shaping){
  1456. for(i=0;i<mb_block_count;i++) {
  1457. if(!skip_dct[i]){
  1458. s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
  1459. }
  1460. }
  1461. }
  1462. if(s->luma_elim_threshold && !s->mb_intra)
  1463. for(i=0; i<4; i++)
  1464. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1465. if(s->chroma_elim_threshold && !s->mb_intra)
  1466. for(i=4; i<mb_block_count; i++)
  1467. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1468. if(s->flags & CODEC_FLAG_CBP_RD){
  1469. for(i=0;i<mb_block_count;i++) {
  1470. if(s->block_last_index[i] == -1)
  1471. s->coded_score[i]= INT_MAX/256;
  1472. }
  1473. }
  1474. }
  1475. if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
  1476. s->block_last_index[4]=
  1477. s->block_last_index[5]= 0;
  1478. s->block[4][0]=
  1479. s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
  1480. }
  1481. //non c quantize code returns incorrect block_last_index FIXME
  1482. if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
  1483. for(i=0; i<mb_block_count; i++){
  1484. int j;
  1485. if(s->block_last_index[i]>0){
  1486. for(j=63; j>0; j--){
  1487. if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
  1488. }
  1489. s->block_last_index[i]= j;
  1490. }
  1491. }
  1492. }
  1493. /* huffman encode */
  1494. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1495. case CODEC_ID_MPEG1VIDEO:
  1496. case CODEC_ID_MPEG2VIDEO:
  1497. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1498. mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1499. break;
  1500. case CODEC_ID_MPEG4:
  1501. if (CONFIG_MPEG4_ENCODER)
  1502. mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1503. break;
  1504. case CODEC_ID_MSMPEG4V2:
  1505. case CODEC_ID_MSMPEG4V3:
  1506. case CODEC_ID_WMV1:
  1507. if (CONFIG_MSMPEG4_ENCODER)
  1508. msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1509. break;
  1510. case CODEC_ID_WMV2:
  1511. if (CONFIG_WMV2_ENCODER)
  1512. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1513. break;
  1514. case CODEC_ID_H261:
  1515. if (CONFIG_H261_ENCODER)
  1516. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1517. break;
  1518. case CODEC_ID_H263:
  1519. case CODEC_ID_H263P:
  1520. case CODEC_ID_FLV1:
  1521. case CODEC_ID_RV10:
  1522. case CODEC_ID_RV20:
  1523. if (CONFIG_H263_ENCODER)
  1524. h263_encode_mb(s, s->block, motion_x, motion_y);
  1525. break;
  1526. case CODEC_ID_MJPEG:
  1527. if (CONFIG_MJPEG_ENCODER)
  1528. ff_mjpeg_encode_mb(s, s->block);
  1529. break;
  1530. default:
  1531. assert(0);
  1532. }
  1533. }
  1534. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1535. {
  1536. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1537. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1538. }
  1539. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1540. int i;
  1541. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1542. /* mpeg1 */
  1543. d->mb_skip_run= s->mb_skip_run;
  1544. for(i=0; i<3; i++)
  1545. d->last_dc[i]= s->last_dc[i];
  1546. /* statistics */
  1547. d->mv_bits= s->mv_bits;
  1548. d->i_tex_bits= s->i_tex_bits;
  1549. d->p_tex_bits= s->p_tex_bits;
  1550. d->i_count= s->i_count;
  1551. d->f_count= s->f_count;
  1552. d->b_count= s->b_count;
  1553. d->skip_count= s->skip_count;
  1554. d->misc_bits= s->misc_bits;
  1555. d->last_bits= 0;
  1556. d->mb_skipped= 0;
  1557. d->qscale= s->qscale;
  1558. d->dquant= s->dquant;
  1559. d->esc3_level_length= s->esc3_level_length;
  1560. }
  1561. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1562. int i;
  1563. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1564. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1565. /* mpeg1 */
  1566. d->mb_skip_run= s->mb_skip_run;
  1567. for(i=0; i<3; i++)
  1568. d->last_dc[i]= s->last_dc[i];
  1569. /* statistics */
  1570. d->mv_bits= s->mv_bits;
  1571. d->i_tex_bits= s->i_tex_bits;
  1572. d->p_tex_bits= s->p_tex_bits;
  1573. d->i_count= s->i_count;
  1574. d->f_count= s->f_count;
  1575. d->b_count= s->b_count;
  1576. d->skip_count= s->skip_count;
  1577. d->misc_bits= s->misc_bits;
  1578. d->mb_intra= s->mb_intra;
  1579. d->mb_skipped= s->mb_skipped;
  1580. d->mv_type= s->mv_type;
  1581. d->mv_dir= s->mv_dir;
  1582. d->pb= s->pb;
  1583. if(s->data_partitioning){
  1584. d->pb2= s->pb2;
  1585. d->tex_pb= s->tex_pb;
  1586. }
  1587. d->block= s->block;
  1588. for(i=0; i<8; i++)
  1589. d->block_last_index[i]= s->block_last_index[i];
  1590. d->interlaced_dct= s->interlaced_dct;
  1591. d->qscale= s->qscale;
  1592. d->esc3_level_length= s->esc3_level_length;
  1593. }
  1594. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1595. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1596. int *dmin, int *next_block, int motion_x, int motion_y)
  1597. {
  1598. int score;
  1599. uint8_t *dest_backup[3];
  1600. copy_context_before_encode(s, backup, type);
  1601. s->block= s->blocks[*next_block];
  1602. s->pb= pb[*next_block];
  1603. if(s->data_partitioning){
  1604. s->pb2 = pb2 [*next_block];
  1605. s->tex_pb= tex_pb[*next_block];
  1606. }
  1607. if(*next_block){
  1608. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1609. s->dest[0] = s->rd_scratchpad;
  1610. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1611. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1612. assert(s->linesize >= 32); //FIXME
  1613. }
  1614. encode_mb(s, motion_x, motion_y);
  1615. score= put_bits_count(&s->pb);
  1616. if(s->data_partitioning){
  1617. score+= put_bits_count(&s->pb2);
  1618. score+= put_bits_count(&s->tex_pb);
  1619. }
  1620. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1621. MPV_decode_mb(s, s->block);
  1622. score *= s->lambda2;
  1623. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1624. }
  1625. if(*next_block){
  1626. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1627. }
  1628. if(score<*dmin){
  1629. *dmin= score;
  1630. *next_block^=1;
  1631. copy_context_after_encode(best, s, type);
  1632. }
  1633. }
  1634. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1635. uint32_t *sq = ff_squareTbl + 256;
  1636. int acc=0;
  1637. int x,y;
  1638. if(w==16 && h==16)
  1639. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  1640. else if(w==8 && h==8)
  1641. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  1642. for(y=0; y<h; y++){
  1643. for(x=0; x<w; x++){
  1644. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  1645. }
  1646. }
  1647. assert(acc>=0);
  1648. return acc;
  1649. }
  1650. static int sse_mb(MpegEncContext *s){
  1651. int w= 16;
  1652. int h= 16;
  1653. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  1654. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  1655. if(w==16 && h==16)
  1656. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  1657. return s->dsp.nsse[0](s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
  1658. +s->dsp.nsse[1](s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
  1659. +s->dsp.nsse[1](s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
  1660. }else{
  1661. return s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
  1662. +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
  1663. +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
  1664. }
  1665. else
  1666. return sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
  1667. +sse(s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
  1668. +sse(s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
  1669. }
  1670. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  1671. MpegEncContext *s= *(void**)arg;
  1672. s->me.pre_pass=1;
  1673. s->me.dia_size= s->avctx->pre_dia_size;
  1674. s->first_slice_line=1;
  1675. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  1676. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  1677. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1678. }
  1679. s->first_slice_line=0;
  1680. }
  1681. s->me.pre_pass=0;
  1682. return 0;
  1683. }
  1684. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  1685. MpegEncContext *s= *(void**)arg;
  1686. ff_check_alignment();
  1687. s->me.dia_size= s->avctx->dia_size;
  1688. s->first_slice_line=1;
  1689. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  1690. s->mb_x=0; //for block init below
  1691. ff_init_block_index(s);
  1692. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  1693. s->block_index[0]+=2;
  1694. s->block_index[1]+=2;
  1695. s->block_index[2]+=2;
  1696. s->block_index[3]+=2;
  1697. /* compute motion vector & mb_type and store in context */
  1698. if(s->pict_type==AV_PICTURE_TYPE_B)
  1699. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  1700. else
  1701. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1702. }
  1703. s->first_slice_line=0;
  1704. }
  1705. return 0;
  1706. }
  1707. static int mb_var_thread(AVCodecContext *c, void *arg){
  1708. MpegEncContext *s= *(void**)arg;
  1709. int mb_x, mb_y;
  1710. ff_check_alignment();
  1711. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1712. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1713. int xx = mb_x * 16;
  1714. int yy = mb_y * 16;
  1715. uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
  1716. int varc;
  1717. int sum = s->dsp.pix_sum(pix, s->linesize);
  1718. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
  1719. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  1720. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  1721. s->me.mb_var_sum_temp += varc;
  1722. }
  1723. }
  1724. return 0;
  1725. }
  1726. static void write_slice_end(MpegEncContext *s){
  1727. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
  1728. if(s->partitioned_frame){
  1729. ff_mpeg4_merge_partitions(s);
  1730. }
  1731. ff_mpeg4_stuffing(&s->pb);
  1732. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  1733. ff_mjpeg_encode_stuffing(&s->pb);
  1734. }
  1735. align_put_bits(&s->pb);
  1736. flush_put_bits(&s->pb);
  1737. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  1738. s->misc_bits+= get_bits_diff(s);
  1739. }
  1740. static int encode_thread(AVCodecContext *c, void *arg){
  1741. MpegEncContext *s= *(void**)arg;
  1742. int mb_x, mb_y, pdif = 0;
  1743. int chr_h= 16>>s->chroma_y_shift;
  1744. int i, j;
  1745. MpegEncContext best_s, backup_s;
  1746. uint8_t bit_buf[2][MAX_MB_BYTES];
  1747. uint8_t bit_buf2[2][MAX_MB_BYTES];
  1748. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  1749. PutBitContext pb[2], pb2[2], tex_pb[2];
  1750. //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
  1751. ff_check_alignment();
  1752. for(i=0; i<2; i++){
  1753. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  1754. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  1755. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  1756. }
  1757. s->last_bits= put_bits_count(&s->pb);
  1758. s->mv_bits=0;
  1759. s->misc_bits=0;
  1760. s->i_tex_bits=0;
  1761. s->p_tex_bits=0;
  1762. s->i_count=0;
  1763. s->f_count=0;
  1764. s->b_count=0;
  1765. s->skip_count=0;
  1766. for(i=0; i<3; i++){
  1767. /* init last dc values */
  1768. /* note: quant matrix value (8) is implied here */
  1769. s->last_dc[i] = 128 << s->intra_dc_precision;
  1770. s->current_picture.error[i] = 0;
  1771. }
  1772. s->mb_skip_run = 0;
  1773. memset(s->last_mv, 0, sizeof(s->last_mv));
  1774. s->last_mv_dir = 0;
  1775. switch(s->codec_id){
  1776. case CODEC_ID_H263:
  1777. case CODEC_ID_H263P:
  1778. case CODEC_ID_FLV1:
  1779. if (CONFIG_H263_ENCODER)
  1780. s->gob_index = ff_h263_get_gob_height(s);
  1781. break;
  1782. case CODEC_ID_MPEG4:
  1783. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  1784. ff_mpeg4_init_partitions(s);
  1785. break;
  1786. }
  1787. s->resync_mb_x=0;
  1788. s->resync_mb_y=0;
  1789. s->first_slice_line = 1;
  1790. s->ptr_lastgob = s->pb.buf;
  1791. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1792. // printf("row %d at %X\n", s->mb_y, (int)s);
  1793. s->mb_x=0;
  1794. s->mb_y= mb_y;
  1795. ff_set_qscale(s, s->qscale);
  1796. ff_init_block_index(s);
  1797. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1798. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  1799. int mb_type= s->mb_type[xy];
  1800. // int d;
  1801. int dmin= INT_MAX;
  1802. int dir;
  1803. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  1804. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1805. return -1;
  1806. }
  1807. if(s->data_partitioning){
  1808. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  1809. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  1810. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1811. return -1;
  1812. }
  1813. }
  1814. s->mb_x = mb_x;
  1815. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  1816. ff_update_block_index(s);
  1817. if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
  1818. ff_h261_reorder_mb_index(s);
  1819. xy= s->mb_y*s->mb_stride + s->mb_x;
  1820. mb_type= s->mb_type[xy];
  1821. }
  1822. /* write gob / video packet header */
  1823. if(s->rtp_mode){
  1824. int current_packet_size, is_gob_start;
  1825. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  1826. is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  1827. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  1828. switch(s->codec_id){
  1829. case CODEC_ID_H263:
  1830. case CODEC_ID_H263P:
  1831. if(!s->h263_slice_structured)
  1832. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  1833. break;
  1834. case CODEC_ID_MPEG2VIDEO:
  1835. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  1836. case CODEC_ID_MPEG1VIDEO:
  1837. if(s->mb_skip_run) is_gob_start=0;
  1838. break;
  1839. }
  1840. if(is_gob_start){
  1841. if(s->start_mb_y != mb_y || mb_x!=0){
  1842. write_slice_end(s);
  1843. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
  1844. ff_mpeg4_init_partitions(s);
  1845. }
  1846. }
  1847. assert((put_bits_count(&s->pb)&7) == 0);
  1848. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  1849. if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
  1850. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  1851. int d= 100 / s->avctx->error_rate;
  1852. if(r % d == 0){
  1853. current_packet_size=0;
  1854. #ifndef ALT_BITSTREAM_WRITER
  1855. s->pb.buf_ptr= s->ptr_lastgob;
  1856. #endif
  1857. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  1858. }
  1859. }
  1860. if (s->avctx->rtp_callback){
  1861. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  1862. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  1863. }
  1864. switch(s->codec_id){
  1865. case CODEC_ID_MPEG4:
  1866. if (CONFIG_MPEG4_ENCODER) {
  1867. ff_mpeg4_encode_video_packet_header(s);
  1868. ff_mpeg4_clean_buffers(s);
  1869. }
  1870. break;
  1871. case CODEC_ID_MPEG1VIDEO:
  1872. case CODEC_ID_MPEG2VIDEO:
  1873. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  1874. ff_mpeg1_encode_slice_header(s);
  1875. ff_mpeg1_clean_buffers(s);
  1876. }
  1877. break;
  1878. case CODEC_ID_H263:
  1879. case CODEC_ID_H263P:
  1880. if (CONFIG_H263_ENCODER)
  1881. h263_encode_gob_header(s, mb_y);
  1882. break;
  1883. }
  1884. if(s->flags&CODEC_FLAG_PASS1){
  1885. int bits= put_bits_count(&s->pb);
  1886. s->misc_bits+= bits - s->last_bits;
  1887. s->last_bits= bits;
  1888. }
  1889. s->ptr_lastgob += current_packet_size;
  1890. s->first_slice_line=1;
  1891. s->resync_mb_x=mb_x;
  1892. s->resync_mb_y=mb_y;
  1893. }
  1894. }
  1895. if( (s->resync_mb_x == s->mb_x)
  1896. && s->resync_mb_y+1 == s->mb_y){
  1897. s->first_slice_line=0;
  1898. }
  1899. s->mb_skipped=0;
  1900. s->dquant=0; //only for QP_RD
  1901. if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
  1902. int next_block=0;
  1903. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  1904. copy_context_before_encode(&backup_s, s, -1);
  1905. backup_s.pb= s->pb;
  1906. best_s.data_partitioning= s->data_partitioning;
  1907. best_s.partitioned_frame= s->partitioned_frame;
  1908. if(s->data_partitioning){
  1909. backup_s.pb2= s->pb2;
  1910. backup_s.tex_pb= s->tex_pb;
  1911. }
  1912. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  1913. s->mv_dir = MV_DIR_FORWARD;
  1914. s->mv_type = MV_TYPE_16X16;
  1915. s->mb_intra= 0;
  1916. s->mv[0][0][0] = s->p_mv_table[xy][0];
  1917. s->mv[0][0][1] = s->p_mv_table[xy][1];
  1918. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  1919. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1920. }
  1921. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  1922. s->mv_dir = MV_DIR_FORWARD;
  1923. s->mv_type = MV_TYPE_FIELD;
  1924. s->mb_intra= 0;
  1925. for(i=0; i<2; i++){
  1926. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  1927. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  1928. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  1929. }
  1930. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  1931. &dmin, &next_block, 0, 0);
  1932. }
  1933. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  1934. s->mv_dir = MV_DIR_FORWARD;
  1935. s->mv_type = MV_TYPE_16X16;
  1936. s->mb_intra= 0;
  1937. s->mv[0][0][0] = 0;
  1938. s->mv[0][0][1] = 0;
  1939. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  1940. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1941. }
  1942. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  1943. s->mv_dir = MV_DIR_FORWARD;
  1944. s->mv_type = MV_TYPE_8X8;
  1945. s->mb_intra= 0;
  1946. for(i=0; i<4; i++){
  1947. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  1948. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  1949. }
  1950. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  1951. &dmin, &next_block, 0, 0);
  1952. }
  1953. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  1954. s->mv_dir = MV_DIR_FORWARD;
  1955. s->mv_type = MV_TYPE_16X16;
  1956. s->mb_intra= 0;
  1957. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  1958. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  1959. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  1960. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1961. }
  1962. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  1963. s->mv_dir = MV_DIR_BACKWARD;
  1964. s->mv_type = MV_TYPE_16X16;
  1965. s->mb_intra= 0;
  1966. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  1967. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  1968. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  1969. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  1970. }
  1971. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  1972. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  1973. s->mv_type = MV_TYPE_16X16;
  1974. s->mb_intra= 0;
  1975. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  1976. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  1977. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  1978. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  1979. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  1980. &dmin, &next_block, 0, 0);
  1981. }
  1982. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  1983. s->mv_dir = MV_DIR_FORWARD;
  1984. s->mv_type = MV_TYPE_FIELD;
  1985. s->mb_intra= 0;
  1986. for(i=0; i<2; i++){
  1987. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  1988. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  1989. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  1990. }
  1991. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  1992. &dmin, &next_block, 0, 0);
  1993. }
  1994. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  1995. s->mv_dir = MV_DIR_BACKWARD;
  1996. s->mv_type = MV_TYPE_FIELD;
  1997. s->mb_intra= 0;
  1998. for(i=0; i<2; i++){
  1999. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2000. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2001. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2002. }
  2003. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  2004. &dmin, &next_block, 0, 0);
  2005. }
  2006. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  2007. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2008. s->mv_type = MV_TYPE_FIELD;
  2009. s->mb_intra= 0;
  2010. for(dir=0; dir<2; dir++){
  2011. for(i=0; i<2; i++){
  2012. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2013. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2014. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2015. }
  2016. }
  2017. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  2018. &dmin, &next_block, 0, 0);
  2019. }
  2020. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  2021. s->mv_dir = 0;
  2022. s->mv_type = MV_TYPE_16X16;
  2023. s->mb_intra= 1;
  2024. s->mv[0][0][0] = 0;
  2025. s->mv[0][0][1] = 0;
  2026. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  2027. &dmin, &next_block, 0, 0);
  2028. if(s->h263_pred || s->h263_aic){
  2029. if(best_s.mb_intra)
  2030. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  2031. else
  2032. ff_clean_intra_table_entries(s); //old mode?
  2033. }
  2034. }
  2035. if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
  2036. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  2037. const int last_qp= backup_s.qscale;
  2038. int qpi, qp, dc[6];
  2039. DCTELEM ac[6][16];
  2040. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2041. static const int dquant_tab[4]={-1,1,-2,2};
  2042. assert(backup_s.dquant == 0);
  2043. //FIXME intra
  2044. s->mv_dir= best_s.mv_dir;
  2045. s->mv_type = MV_TYPE_16X16;
  2046. s->mb_intra= best_s.mb_intra;
  2047. s->mv[0][0][0] = best_s.mv[0][0][0];
  2048. s->mv[0][0][1] = best_s.mv[0][0][1];
  2049. s->mv[1][0][0] = best_s.mv[1][0][0];
  2050. s->mv[1][0][1] = best_s.mv[1][0][1];
  2051. qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
  2052. for(; qpi<4; qpi++){
  2053. int dquant= dquant_tab[qpi];
  2054. qp= last_qp + dquant;
  2055. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2056. continue;
  2057. backup_s.dquant= dquant;
  2058. if(s->mb_intra && s->dc_val[0]){
  2059. for(i=0; i<6; i++){
  2060. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2061. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
  2062. }
  2063. }
  2064. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2065. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2066. if(best_s.qscale != qp){
  2067. if(s->mb_intra && s->dc_val[0]){
  2068. for(i=0; i<6; i++){
  2069. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2070. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
  2071. }
  2072. }
  2073. }
  2074. }
  2075. }
  2076. }
  2077. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2078. int mx= s->b_direct_mv_table[xy][0];
  2079. int my= s->b_direct_mv_table[xy][1];
  2080. backup_s.dquant = 0;
  2081. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2082. s->mb_intra= 0;
  2083. ff_mpeg4_set_direct_mv(s, mx, my);
  2084. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2085. &dmin, &next_block, mx, my);
  2086. }
  2087. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2088. backup_s.dquant = 0;
  2089. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2090. s->mb_intra= 0;
  2091. ff_mpeg4_set_direct_mv(s, 0, 0);
  2092. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2093. &dmin, &next_block, 0, 0);
  2094. }
  2095. if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
  2096. int coded=0;
  2097. for(i=0; i<6; i++)
  2098. coded |= s->block_last_index[i];
  2099. if(coded){
  2100. int mx,my;
  2101. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2102. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2103. mx=my=0; //FIXME find the one we actually used
  2104. ff_mpeg4_set_direct_mv(s, mx, my);
  2105. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2106. mx= s->mv[1][0][0];
  2107. my= s->mv[1][0][1];
  2108. }else{
  2109. mx= s->mv[0][0][0];
  2110. my= s->mv[0][0][1];
  2111. }
  2112. s->mv_dir= best_s.mv_dir;
  2113. s->mv_type = best_s.mv_type;
  2114. s->mb_intra= 0;
  2115. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2116. s->mv[0][0][1] = best_s.mv[0][0][1];
  2117. s->mv[1][0][0] = best_s.mv[1][0][0];
  2118. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2119. backup_s.dquant= 0;
  2120. s->skipdct=1;
  2121. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2122. &dmin, &next_block, mx, my);
  2123. s->skipdct=0;
  2124. }
  2125. }
  2126. s->current_picture.qscale_table[xy]= best_s.qscale;
  2127. copy_context_after_encode(s, &best_s, -1);
  2128. pb_bits_count= put_bits_count(&s->pb);
  2129. flush_put_bits(&s->pb);
  2130. ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2131. s->pb= backup_s.pb;
  2132. if(s->data_partitioning){
  2133. pb2_bits_count= put_bits_count(&s->pb2);
  2134. flush_put_bits(&s->pb2);
  2135. ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2136. s->pb2= backup_s.pb2;
  2137. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2138. flush_put_bits(&s->tex_pb);
  2139. ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2140. s->tex_pb= backup_s.tex_pb;
  2141. }
  2142. s->last_bits= put_bits_count(&s->pb);
  2143. if (CONFIG_H263_ENCODER &&
  2144. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2145. ff_h263_update_motion_val(s);
  2146. if(next_block==0){ //FIXME 16 vs linesize16
  2147. s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
  2148. s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2149. s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2150. }
  2151. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2152. MPV_decode_mb(s, s->block);
  2153. } else {
  2154. int motion_x = 0, motion_y = 0;
  2155. s->mv_type=MV_TYPE_16X16;
  2156. // only one MB-Type possible
  2157. switch(mb_type){
  2158. case CANDIDATE_MB_TYPE_INTRA:
  2159. s->mv_dir = 0;
  2160. s->mb_intra= 1;
  2161. motion_x= s->mv[0][0][0] = 0;
  2162. motion_y= s->mv[0][0][1] = 0;
  2163. break;
  2164. case CANDIDATE_MB_TYPE_INTER:
  2165. s->mv_dir = MV_DIR_FORWARD;
  2166. s->mb_intra= 0;
  2167. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2168. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2169. break;
  2170. case CANDIDATE_MB_TYPE_INTER_I:
  2171. s->mv_dir = MV_DIR_FORWARD;
  2172. s->mv_type = MV_TYPE_FIELD;
  2173. s->mb_intra= 0;
  2174. for(i=0; i<2; i++){
  2175. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2176. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2177. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2178. }
  2179. break;
  2180. case CANDIDATE_MB_TYPE_INTER4V:
  2181. s->mv_dir = MV_DIR_FORWARD;
  2182. s->mv_type = MV_TYPE_8X8;
  2183. s->mb_intra= 0;
  2184. for(i=0; i<4; i++){
  2185. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  2186. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  2187. }
  2188. break;
  2189. case CANDIDATE_MB_TYPE_DIRECT:
  2190. if (CONFIG_MPEG4_ENCODER) {
  2191. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2192. s->mb_intra= 0;
  2193. motion_x=s->b_direct_mv_table[xy][0];
  2194. motion_y=s->b_direct_mv_table[xy][1];
  2195. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2196. }
  2197. break;
  2198. case CANDIDATE_MB_TYPE_DIRECT0:
  2199. if (CONFIG_MPEG4_ENCODER) {
  2200. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2201. s->mb_intra= 0;
  2202. ff_mpeg4_set_direct_mv(s, 0, 0);
  2203. }
  2204. break;
  2205. case CANDIDATE_MB_TYPE_BIDIR:
  2206. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2207. s->mb_intra= 0;
  2208. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2209. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2210. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2211. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2212. break;
  2213. case CANDIDATE_MB_TYPE_BACKWARD:
  2214. s->mv_dir = MV_DIR_BACKWARD;
  2215. s->mb_intra= 0;
  2216. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2217. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2218. break;
  2219. case CANDIDATE_MB_TYPE_FORWARD:
  2220. s->mv_dir = MV_DIR_FORWARD;
  2221. s->mb_intra= 0;
  2222. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2223. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2224. // printf(" %d %d ", motion_x, motion_y);
  2225. break;
  2226. case CANDIDATE_MB_TYPE_FORWARD_I:
  2227. s->mv_dir = MV_DIR_FORWARD;
  2228. s->mv_type = MV_TYPE_FIELD;
  2229. s->mb_intra= 0;
  2230. for(i=0; i<2; i++){
  2231. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2232. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2233. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2234. }
  2235. break;
  2236. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2237. s->mv_dir = MV_DIR_BACKWARD;
  2238. s->mv_type = MV_TYPE_FIELD;
  2239. s->mb_intra= 0;
  2240. for(i=0; i<2; i++){
  2241. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2242. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2243. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2244. }
  2245. break;
  2246. case CANDIDATE_MB_TYPE_BIDIR_I:
  2247. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2248. s->mv_type = MV_TYPE_FIELD;
  2249. s->mb_intra= 0;
  2250. for(dir=0; dir<2; dir++){
  2251. for(i=0; i<2; i++){
  2252. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2253. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2254. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2255. }
  2256. }
  2257. break;
  2258. default:
  2259. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2260. }
  2261. encode_mb(s, motion_x, motion_y);
  2262. // RAL: Update last macroblock type
  2263. s->last_mv_dir = s->mv_dir;
  2264. if (CONFIG_H263_ENCODER &&
  2265. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2266. ff_h263_update_motion_val(s);
  2267. MPV_decode_mb(s, s->block);
  2268. }
  2269. /* clean the MV table in IPS frames for direct mode in B frames */
  2270. if(s->mb_intra /* && I,P,S_TYPE */){
  2271. s->p_mv_table[xy][0]=0;
  2272. s->p_mv_table[xy][1]=0;
  2273. }
  2274. if(s->flags&CODEC_FLAG_PSNR){
  2275. int w= 16;
  2276. int h= 16;
  2277. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2278. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2279. s->current_picture.error[0] += sse(
  2280. s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2281. s->dest[0], w, h, s->linesize);
  2282. s->current_picture.error[1] += sse(
  2283. s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2284. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2285. s->current_picture.error[2] += sse(
  2286. s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2287. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2288. }
  2289. if(s->loop_filter){
  2290. if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  2291. ff_h263_loop_filter(s);
  2292. }
  2293. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
  2294. }
  2295. }
  2296. //not beautiful here but we must write it before flushing so it has to be here
  2297. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
  2298. msmpeg4_encode_ext_header(s);
  2299. write_slice_end(s);
  2300. /* Send the last GOB if RTP */
  2301. if (s->avctx->rtp_callback) {
  2302. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2303. pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2304. /* Call the RTP callback to send the last GOB */
  2305. emms_c();
  2306. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2307. }
  2308. return 0;
  2309. }
  2310. #define MERGE(field) dst->field += src->field; src->field=0
  2311. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2312. MERGE(me.scene_change_score);
  2313. MERGE(me.mc_mb_var_sum_temp);
  2314. MERGE(me.mb_var_sum_temp);
  2315. }
  2316. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2317. int i;
  2318. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2319. MERGE(dct_count[1]);
  2320. MERGE(mv_bits);
  2321. MERGE(i_tex_bits);
  2322. MERGE(p_tex_bits);
  2323. MERGE(i_count);
  2324. MERGE(f_count);
  2325. MERGE(b_count);
  2326. MERGE(skip_count);
  2327. MERGE(misc_bits);
  2328. MERGE(error_count);
  2329. MERGE(padding_bug_score);
  2330. MERGE(current_picture.error[0]);
  2331. MERGE(current_picture.error[1]);
  2332. MERGE(current_picture.error[2]);
  2333. if(dst->avctx->noise_reduction){
  2334. for(i=0; i<64; i++){
  2335. MERGE(dct_error_sum[0][i]);
  2336. MERGE(dct_error_sum[1][i]);
  2337. }
  2338. }
  2339. assert(put_bits_count(&src->pb) % 8 ==0);
  2340. assert(put_bits_count(&dst->pb) % 8 ==0);
  2341. ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2342. flush_put_bits(&dst->pb);
  2343. }
  2344. static int estimate_qp(MpegEncContext *s, int dry_run){
  2345. if (s->next_lambda){
  2346. s->current_picture_ptr->quality=
  2347. s->current_picture.quality = s->next_lambda;
  2348. if(!dry_run) s->next_lambda= 0;
  2349. } else if (!s->fixed_qscale) {
  2350. s->current_picture_ptr->quality=
  2351. s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
  2352. if (s->current_picture.quality < 0)
  2353. return -1;
  2354. }
  2355. if(s->adaptive_quant){
  2356. switch(s->codec_id){
  2357. case CODEC_ID_MPEG4:
  2358. if (CONFIG_MPEG4_ENCODER)
  2359. ff_clean_mpeg4_qscales(s);
  2360. break;
  2361. case CODEC_ID_H263:
  2362. case CODEC_ID_H263P:
  2363. case CODEC_ID_FLV1:
  2364. if (CONFIG_H263_ENCODER)
  2365. ff_clean_h263_qscales(s);
  2366. break;
  2367. default:
  2368. ff_init_qscale_tab(s);
  2369. }
  2370. s->lambda= s->lambda_table[0];
  2371. //FIXME broken
  2372. }else
  2373. s->lambda= s->current_picture.quality;
  2374. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  2375. update_qscale(s);
  2376. return 0;
  2377. }
  2378. /* must be called before writing the header */
  2379. static void set_frame_distances(MpegEncContext * s){
  2380. assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
  2381. s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
  2382. if(s->pict_type==AV_PICTURE_TYPE_B){
  2383. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  2384. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  2385. }else{
  2386. s->pp_time= s->time - s->last_non_b_time;
  2387. s->last_non_b_time= s->time;
  2388. assert(s->picture_number==0 || s->pp_time > 0);
  2389. }
  2390. }
  2391. static int encode_picture(MpegEncContext *s, int picture_number)
  2392. {
  2393. int i;
  2394. int bits;
  2395. int context_count = s->avctx->thread_count;
  2396. s->picture_number = picture_number;
  2397. /* Reset the average MB variance */
  2398. s->me.mb_var_sum_temp =
  2399. s->me.mc_mb_var_sum_temp = 0;
  2400. /* we need to initialize some time vars before we can encode b-frames */
  2401. // RAL: Condition added for MPEG1VIDEO
  2402. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
  2403. set_frame_distances(s);
  2404. if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
  2405. ff_set_mpeg4_time(s);
  2406. s->me.scene_change_score=0;
  2407. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  2408. if(s->pict_type==AV_PICTURE_TYPE_I){
  2409. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2410. else s->no_rounding=0;
  2411. }else if(s->pict_type!=AV_PICTURE_TYPE_B){
  2412. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2413. s->no_rounding ^= 1;
  2414. }
  2415. if(s->flags & CODEC_FLAG_PASS2){
  2416. if (estimate_qp(s,1) < 0)
  2417. return -1;
  2418. ff_get_2pass_fcode(s);
  2419. }else if(!(s->flags & CODEC_FLAG_QSCALE)){
  2420. if(s->pict_type==AV_PICTURE_TYPE_B)
  2421. s->lambda= s->last_lambda_for[s->pict_type];
  2422. else
  2423. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  2424. update_qscale(s);
  2425. }
  2426. s->mb_intra=0; //for the rate distortion & bit compare functions
  2427. for(i=1; i<context_count; i++){
  2428. ff_update_duplicate_context(s->thread_context[i], s);
  2429. }
  2430. if(ff_init_me(s)<0)
  2431. return -1;
  2432. /* Estimate motion for every MB */
  2433. if(s->pict_type != AV_PICTURE_TYPE_I){
  2434. s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  2435. s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  2436. if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
  2437. if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
  2438. s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2439. }
  2440. }
  2441. s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2442. }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
  2443. /* I-Frame */
  2444. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2445. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2446. if(!s->fixed_qscale){
  2447. /* finding spatial complexity for I-frame rate control */
  2448. s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2449. }
  2450. }
  2451. for(i=1; i<context_count; i++){
  2452. merge_context_after_me(s, s->thread_context[i]);
  2453. }
  2454. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  2455. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  2456. emms_c();
  2457. if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
  2458. s->pict_type= AV_PICTURE_TYPE_I;
  2459. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2460. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2461. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2462. }
  2463. if(!s->umvplus){
  2464. if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
  2465. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  2466. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2467. int a,b;
  2468. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  2469. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  2470. s->f_code= FFMAX3(s->f_code, a, b);
  2471. }
  2472. ff_fix_long_p_mvs(s);
  2473. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  2474. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2475. int j;
  2476. for(i=0; i<2; i++){
  2477. for(j=0; j<2; j++)
  2478. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  2479. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  2480. }
  2481. }
  2482. }
  2483. if(s->pict_type==AV_PICTURE_TYPE_B){
  2484. int a, b;
  2485. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  2486. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2487. s->f_code = FFMAX(a, b);
  2488. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  2489. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2490. s->b_code = FFMAX(a, b);
  2491. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  2492. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  2493. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2494. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2495. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2496. int dir, j;
  2497. for(dir=0; dir<2; dir++){
  2498. for(i=0; i<2; i++){
  2499. for(j=0; j<2; j++){
  2500. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  2501. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  2502. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  2503. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  2504. }
  2505. }
  2506. }
  2507. }
  2508. }
  2509. }
  2510. if (estimate_qp(s, 0) < 0)
  2511. return -1;
  2512. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
  2513. s->qscale= 3; //reduce clipping problems
  2514. if (s->out_format == FMT_MJPEG) {
  2515. /* for mjpeg, we do include qscale in the matrix */
  2516. for(i=1;i<64;i++){
  2517. int j= s->dsp.idct_permutation[i];
  2518. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  2519. }
  2520. s->y_dc_scale_table=
  2521. s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
  2522. s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
  2523. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2524. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2525. s->qscale= 8;
  2526. }
  2527. //FIXME var duplication
  2528. s->current_picture_ptr->key_frame=
  2529. s->current_picture.key_frame= s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
  2530. s->current_picture_ptr->pict_type=
  2531. s->current_picture.pict_type= s->pict_type;
  2532. if(s->current_picture.key_frame)
  2533. s->picture_in_gop_number=0;
  2534. s->last_bits= put_bits_count(&s->pb);
  2535. switch(s->out_format) {
  2536. case FMT_MJPEG:
  2537. if (CONFIG_MJPEG_ENCODER)
  2538. ff_mjpeg_encode_picture_header(s);
  2539. break;
  2540. case FMT_H261:
  2541. if (CONFIG_H261_ENCODER)
  2542. ff_h261_encode_picture_header(s, picture_number);
  2543. break;
  2544. case FMT_H263:
  2545. if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
  2546. ff_wmv2_encode_picture_header(s, picture_number);
  2547. else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  2548. msmpeg4_encode_picture_header(s, picture_number);
  2549. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  2550. mpeg4_encode_picture_header(s, picture_number);
  2551. else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
  2552. rv10_encode_picture_header(s, picture_number);
  2553. else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
  2554. rv20_encode_picture_header(s, picture_number);
  2555. else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
  2556. ff_flv_encode_picture_header(s, picture_number);
  2557. else if (CONFIG_H263_ENCODER)
  2558. h263_encode_picture_header(s, picture_number);
  2559. break;
  2560. case FMT_MPEG1:
  2561. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2562. mpeg1_encode_picture_header(s, picture_number);
  2563. break;
  2564. case FMT_H264:
  2565. break;
  2566. default:
  2567. assert(0);
  2568. }
  2569. bits= put_bits_count(&s->pb);
  2570. s->header_bits= bits - s->last_bits;
  2571. for(i=1; i<context_count; i++){
  2572. update_duplicate_context_after_me(s->thread_context[i], s);
  2573. }
  2574. s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2575. for(i=1; i<context_count; i++){
  2576. merge_context_after_encode(s, s->thread_context[i]);
  2577. }
  2578. emms_c();
  2579. return 0;
  2580. }
  2581. static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
  2582. const int intra= s->mb_intra;
  2583. int i;
  2584. s->dct_count[intra]++;
  2585. for(i=0; i<64; i++){
  2586. int level= block[i];
  2587. if(level){
  2588. if(level>0){
  2589. s->dct_error_sum[intra][i] += level;
  2590. level -= s->dct_offset[intra][i];
  2591. if(level<0) level=0;
  2592. }else{
  2593. s->dct_error_sum[intra][i] -= level;
  2594. level += s->dct_offset[intra][i];
  2595. if(level>0) level=0;
  2596. }
  2597. block[i]= level;
  2598. }
  2599. }
  2600. }
  2601. static int dct_quantize_trellis_c(MpegEncContext *s,
  2602. DCTELEM *block, int n,
  2603. int qscale, int *overflow){
  2604. const int *qmat;
  2605. const uint8_t *scantable= s->intra_scantable.scantable;
  2606. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2607. int max=0;
  2608. unsigned int threshold1, threshold2;
  2609. int bias=0;
  2610. int run_tab[65];
  2611. int level_tab[65];
  2612. int score_tab[65];
  2613. int survivor[65];
  2614. int survivor_count;
  2615. int last_run=0;
  2616. int last_level=0;
  2617. int last_score= 0;
  2618. int last_i;
  2619. int coeff[2][64];
  2620. int coeff_count[64];
  2621. int qmul, qadd, start_i, last_non_zero, i, dc;
  2622. const int esc_length= s->ac_esc_length;
  2623. uint8_t * length;
  2624. uint8_t * last_length;
  2625. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  2626. s->dsp.fdct (block);
  2627. if(s->dct_error_sum)
  2628. s->denoise_dct(s, block);
  2629. qmul= qscale*16;
  2630. qadd= ((qscale-1)|1)*8;
  2631. if (s->mb_intra) {
  2632. int q;
  2633. if (!s->h263_aic) {
  2634. if (n < 4)
  2635. q = s->y_dc_scale;
  2636. else
  2637. q = s->c_dc_scale;
  2638. q = q << 3;
  2639. } else{
  2640. /* For AIC we skip quant/dequant of INTRADC */
  2641. q = 1 << 3;
  2642. qadd=0;
  2643. }
  2644. /* note: block[0] is assumed to be positive */
  2645. block[0] = (block[0] + (q >> 1)) / q;
  2646. start_i = 1;
  2647. last_non_zero = 0;
  2648. qmat = s->q_intra_matrix[qscale];
  2649. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2650. bias= 1<<(QMAT_SHIFT-1);
  2651. length = s->intra_ac_vlc_length;
  2652. last_length= s->intra_ac_vlc_last_length;
  2653. } else {
  2654. start_i = 0;
  2655. last_non_zero = -1;
  2656. qmat = s->q_inter_matrix[qscale];
  2657. length = s->inter_ac_vlc_length;
  2658. last_length= s->inter_ac_vlc_last_length;
  2659. }
  2660. last_i= start_i;
  2661. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  2662. threshold2= (threshold1<<1);
  2663. for(i=63; i>=start_i; i--) {
  2664. const int j = scantable[i];
  2665. int level = block[j] * qmat[j];
  2666. if(((unsigned)(level+threshold1))>threshold2){
  2667. last_non_zero = i;
  2668. break;
  2669. }
  2670. }
  2671. for(i=start_i; i<=last_non_zero; i++) {
  2672. const int j = scantable[i];
  2673. int level = block[j] * qmat[j];
  2674. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  2675. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  2676. if(((unsigned)(level+threshold1))>threshold2){
  2677. if(level>0){
  2678. level= (bias + level)>>QMAT_SHIFT;
  2679. coeff[0][i]= level;
  2680. coeff[1][i]= level-1;
  2681. // coeff[2][k]= level-2;
  2682. }else{
  2683. level= (bias - level)>>QMAT_SHIFT;
  2684. coeff[0][i]= -level;
  2685. coeff[1][i]= -level+1;
  2686. // coeff[2][k]= -level+2;
  2687. }
  2688. coeff_count[i]= FFMIN(level, 2);
  2689. assert(coeff_count[i]);
  2690. max |=level;
  2691. }else{
  2692. coeff[0][i]= (level>>31)|1;
  2693. coeff_count[i]= 1;
  2694. }
  2695. }
  2696. *overflow= s->max_qcoeff < max; //overflow might have happened
  2697. if(last_non_zero < start_i){
  2698. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2699. return last_non_zero;
  2700. }
  2701. score_tab[start_i]= 0;
  2702. survivor[0]= start_i;
  2703. survivor_count= 1;
  2704. for(i=start_i; i<=last_non_zero; i++){
  2705. int level_index, j, zero_distortion;
  2706. int dct_coeff= FFABS(block[ scantable[i] ]);
  2707. int best_score=256*256*256*120;
  2708. if ( s->dsp.fdct == fdct_ifast
  2709. #ifndef FAAN_POSTSCALE
  2710. || s->dsp.fdct == ff_faandct
  2711. #endif
  2712. )
  2713. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  2714. zero_distortion= dct_coeff*dct_coeff;
  2715. for(level_index=0; level_index < coeff_count[i]; level_index++){
  2716. int distortion;
  2717. int level= coeff[level_index][i];
  2718. const int alevel= FFABS(level);
  2719. int unquant_coeff;
  2720. assert(level);
  2721. if(s->out_format == FMT_H263){
  2722. unquant_coeff= alevel*qmul + qadd;
  2723. }else{ //MPEG1
  2724. j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
  2725. if(s->mb_intra){
  2726. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  2727. unquant_coeff = (unquant_coeff - 1) | 1;
  2728. }else{
  2729. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  2730. unquant_coeff = (unquant_coeff - 1) | 1;
  2731. }
  2732. unquant_coeff<<= 3;
  2733. }
  2734. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  2735. level+=64;
  2736. if((level&(~127)) == 0){
  2737. for(j=survivor_count-1; j>=0; j--){
  2738. int run= i - survivor[j];
  2739. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2740. score += score_tab[i-run];
  2741. if(score < best_score){
  2742. best_score= score;
  2743. run_tab[i+1]= run;
  2744. level_tab[i+1]= level-64;
  2745. }
  2746. }
  2747. if(s->out_format == FMT_H263){
  2748. for(j=survivor_count-1; j>=0; j--){
  2749. int run= i - survivor[j];
  2750. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2751. score += score_tab[i-run];
  2752. if(score < last_score){
  2753. last_score= score;
  2754. last_run= run;
  2755. last_level= level-64;
  2756. last_i= i+1;
  2757. }
  2758. }
  2759. }
  2760. }else{
  2761. distortion += esc_length*lambda;
  2762. for(j=survivor_count-1; j>=0; j--){
  2763. int run= i - survivor[j];
  2764. int score= distortion + score_tab[i-run];
  2765. if(score < best_score){
  2766. best_score= score;
  2767. run_tab[i+1]= run;
  2768. level_tab[i+1]= level-64;
  2769. }
  2770. }
  2771. if(s->out_format == FMT_H263){
  2772. for(j=survivor_count-1; j>=0; j--){
  2773. int run= i - survivor[j];
  2774. int score= distortion + score_tab[i-run];
  2775. if(score < last_score){
  2776. last_score= score;
  2777. last_run= run;
  2778. last_level= level-64;
  2779. last_i= i+1;
  2780. }
  2781. }
  2782. }
  2783. }
  2784. }
  2785. score_tab[i+1]= best_score;
  2786. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  2787. if(last_non_zero <= 27){
  2788. for(; survivor_count; survivor_count--){
  2789. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  2790. break;
  2791. }
  2792. }else{
  2793. for(; survivor_count; survivor_count--){
  2794. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  2795. break;
  2796. }
  2797. }
  2798. survivor[ survivor_count++ ]= i+1;
  2799. }
  2800. if(s->out_format != FMT_H263){
  2801. last_score= 256*256*256*120;
  2802. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  2803. int score= score_tab[i];
  2804. if(i) score += lambda*2; //FIXME exacter?
  2805. if(score < last_score){
  2806. last_score= score;
  2807. last_i= i;
  2808. last_level= level_tab[i];
  2809. last_run= run_tab[i];
  2810. }
  2811. }
  2812. }
  2813. s->coded_score[n] = last_score;
  2814. dc= FFABS(block[0]);
  2815. last_non_zero= last_i - 1;
  2816. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2817. if(last_non_zero < start_i)
  2818. return last_non_zero;
  2819. if(last_non_zero == 0 && start_i == 0){
  2820. int best_level= 0;
  2821. int best_score= dc * dc;
  2822. for(i=0; i<coeff_count[0]; i++){
  2823. int level= coeff[i][0];
  2824. int alevel= FFABS(level);
  2825. int unquant_coeff, score, distortion;
  2826. if(s->out_format == FMT_H263){
  2827. unquant_coeff= (alevel*qmul + qadd)>>3;
  2828. }else{ //MPEG1
  2829. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  2830. unquant_coeff = (unquant_coeff - 1) | 1;
  2831. }
  2832. unquant_coeff = (unquant_coeff + 4) >> 3;
  2833. unquant_coeff<<= 3 + 3;
  2834. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  2835. level+=64;
  2836. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  2837. else score= distortion + esc_length*lambda;
  2838. if(score < best_score){
  2839. best_score= score;
  2840. best_level= level - 64;
  2841. }
  2842. }
  2843. block[0]= best_level;
  2844. s->coded_score[n] = best_score - dc*dc;
  2845. if(best_level == 0) return -1;
  2846. else return last_non_zero;
  2847. }
  2848. i= last_i;
  2849. assert(last_level);
  2850. block[ perm_scantable[last_non_zero] ]= last_level;
  2851. i -= last_run + 1;
  2852. for(; i>start_i; i -= run_tab[i] + 1){
  2853. block[ perm_scantable[i-1] ]= level_tab[i];
  2854. }
  2855. return last_non_zero;
  2856. }
  2857. //#define REFINE_STATS 1
  2858. static int16_t basis[64][64];
  2859. static void build_basis(uint8_t *perm){
  2860. int i, j, x, y;
  2861. emms_c();
  2862. for(i=0; i<8; i++){
  2863. for(j=0; j<8; j++){
  2864. for(y=0; y<8; y++){
  2865. for(x=0; x<8; x++){
  2866. double s= 0.25*(1<<BASIS_SHIFT);
  2867. int index= 8*i + j;
  2868. int perm_index= perm[index];
  2869. if(i==0) s*= sqrt(0.5);
  2870. if(j==0) s*= sqrt(0.5);
  2871. basis[perm_index][8*x + y]= lrintf(s * cos((M_PI/8.0)*i*(x+0.5)) * cos((M_PI/8.0)*j*(y+0.5)));
  2872. }
  2873. }
  2874. }
  2875. }
  2876. }
  2877. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  2878. DCTELEM *block, int16_t *weight, DCTELEM *orig,
  2879. int n, int qscale){
  2880. int16_t rem[64];
  2881. LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
  2882. const uint8_t *scantable= s->intra_scantable.scantable;
  2883. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2884. // unsigned int threshold1, threshold2;
  2885. // int bias=0;
  2886. int run_tab[65];
  2887. int prev_run=0;
  2888. int prev_level=0;
  2889. int qmul, qadd, start_i, last_non_zero, i, dc;
  2890. uint8_t * length;
  2891. uint8_t * last_length;
  2892. int lambda;
  2893. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  2894. #ifdef REFINE_STATS
  2895. static int count=0;
  2896. static int after_last=0;
  2897. static int to_zero=0;
  2898. static int from_zero=0;
  2899. static int raise=0;
  2900. static int lower=0;
  2901. static int messed_sign=0;
  2902. #endif
  2903. if(basis[0][0] == 0)
  2904. build_basis(s->dsp.idct_permutation);
  2905. qmul= qscale*2;
  2906. qadd= (qscale-1)|1;
  2907. if (s->mb_intra) {
  2908. if (!s->h263_aic) {
  2909. if (n < 4)
  2910. q = s->y_dc_scale;
  2911. else
  2912. q = s->c_dc_scale;
  2913. } else{
  2914. /* For AIC we skip quant/dequant of INTRADC */
  2915. q = 1;
  2916. qadd=0;
  2917. }
  2918. q <<= RECON_SHIFT-3;
  2919. /* note: block[0] is assumed to be positive */
  2920. dc= block[0]*q;
  2921. // block[0] = (block[0] + (q >> 1)) / q;
  2922. start_i = 1;
  2923. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2924. // bias= 1<<(QMAT_SHIFT-1);
  2925. length = s->intra_ac_vlc_length;
  2926. last_length= s->intra_ac_vlc_last_length;
  2927. } else {
  2928. dc= 0;
  2929. start_i = 0;
  2930. length = s->inter_ac_vlc_length;
  2931. last_length= s->inter_ac_vlc_last_length;
  2932. }
  2933. last_non_zero = s->block_last_index[n];
  2934. #ifdef REFINE_STATS
  2935. {START_TIMER
  2936. #endif
  2937. dc += (1<<(RECON_SHIFT-1));
  2938. for(i=0; i<64; i++){
  2939. rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
  2940. }
  2941. #ifdef REFINE_STATS
  2942. STOP_TIMER("memset rem[]")}
  2943. #endif
  2944. sum=0;
  2945. for(i=0; i<64; i++){
  2946. int one= 36;
  2947. int qns=4;
  2948. int w;
  2949. w= FFABS(weight[i]) + qns*one;
  2950. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  2951. weight[i] = w;
  2952. // w=weight[i] = (63*qns + (w/2)) / w;
  2953. assert(w>0);
  2954. assert(w<(1<<6));
  2955. sum += w*w;
  2956. }
  2957. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  2958. #ifdef REFINE_STATS
  2959. {START_TIMER
  2960. #endif
  2961. run=0;
  2962. rle_index=0;
  2963. for(i=start_i; i<=last_non_zero; i++){
  2964. int j= perm_scantable[i];
  2965. const int level= block[j];
  2966. int coeff;
  2967. if(level){
  2968. if(level<0) coeff= qmul*level - qadd;
  2969. else coeff= qmul*level + qadd;
  2970. run_tab[rle_index++]=run;
  2971. run=0;
  2972. s->dsp.add_8x8basis(rem, basis[j], coeff);
  2973. }else{
  2974. run++;
  2975. }
  2976. }
  2977. #ifdef REFINE_STATS
  2978. if(last_non_zero>0){
  2979. STOP_TIMER("init rem[]")
  2980. }
  2981. }
  2982. {START_TIMER
  2983. #endif
  2984. for(;;){
  2985. int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
  2986. int best_coeff=0;
  2987. int best_change=0;
  2988. int run2, best_unquant_change=0, analyze_gradient;
  2989. #ifdef REFINE_STATS
  2990. {START_TIMER
  2991. #endif
  2992. analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
  2993. if(analyze_gradient){
  2994. #ifdef REFINE_STATS
  2995. {START_TIMER
  2996. #endif
  2997. for(i=0; i<64; i++){
  2998. int w= weight[i];
  2999. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  3000. }
  3001. #ifdef REFINE_STATS
  3002. STOP_TIMER("rem*w*w")}
  3003. {START_TIMER
  3004. #endif
  3005. s->dsp.fdct(d1);
  3006. #ifdef REFINE_STATS
  3007. STOP_TIMER("dct")}
  3008. #endif
  3009. }
  3010. if(start_i){
  3011. const int level= block[0];
  3012. int change, old_coeff;
  3013. assert(s->mb_intra);
  3014. old_coeff= q*level;
  3015. for(change=-1; change<=1; change+=2){
  3016. int new_level= level + change;
  3017. int score, new_coeff;
  3018. new_coeff= q*new_level;
  3019. if(new_coeff >= 2048 || new_coeff < 0)
  3020. continue;
  3021. score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
  3022. if(score<best_score){
  3023. best_score= score;
  3024. best_coeff= 0;
  3025. best_change= change;
  3026. best_unquant_change= new_coeff - old_coeff;
  3027. }
  3028. }
  3029. }
  3030. run=0;
  3031. rle_index=0;
  3032. run2= run_tab[rle_index++];
  3033. prev_level=0;
  3034. prev_run=0;
  3035. for(i=start_i; i<64; i++){
  3036. int j= perm_scantable[i];
  3037. const int level= block[j];
  3038. int change, old_coeff;
  3039. if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  3040. break;
  3041. if(level){
  3042. if(level<0) old_coeff= qmul*level - qadd;
  3043. else old_coeff= qmul*level + qadd;
  3044. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3045. }else{
  3046. old_coeff=0;
  3047. run2--;
  3048. assert(run2>=0 || i >= last_non_zero );
  3049. }
  3050. for(change=-1; change<=1; change+=2){
  3051. int new_level= level + change;
  3052. int score, new_coeff, unquant_change;
  3053. score=0;
  3054. if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3055. continue;
  3056. if(new_level){
  3057. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3058. else new_coeff= qmul*new_level + qadd;
  3059. if(new_coeff >= 2048 || new_coeff <= -2048)
  3060. continue;
  3061. //FIXME check for overflow
  3062. if(level){
  3063. if(level < 63 && level > -63){
  3064. if(i < last_non_zero)
  3065. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3066. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3067. else
  3068. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3069. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3070. }
  3071. }else{
  3072. assert(FFABS(new_level)==1);
  3073. if(analyze_gradient){
  3074. int g= d1[ scantable[i] ];
  3075. if(g && (g^new_level) >= 0)
  3076. continue;
  3077. }
  3078. if(i < last_non_zero){
  3079. int next_i= i + run2 + 1;
  3080. int next_level= block[ perm_scantable[next_i] ] + 64;
  3081. if(next_level&(~127))
  3082. next_level= 0;
  3083. if(next_i < last_non_zero)
  3084. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3085. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3086. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3087. else
  3088. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3089. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3090. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3091. }else{
  3092. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3093. if(prev_level){
  3094. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3095. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3096. }
  3097. }
  3098. }
  3099. }else{
  3100. new_coeff=0;
  3101. assert(FFABS(level)==1);
  3102. if(i < last_non_zero){
  3103. int next_i= i + run2 + 1;
  3104. int next_level= block[ perm_scantable[next_i] ] + 64;
  3105. if(next_level&(~127))
  3106. next_level= 0;
  3107. if(next_i < last_non_zero)
  3108. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3109. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3110. - length[UNI_AC_ENC_INDEX(run, 65)];
  3111. else
  3112. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3113. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3114. - length[UNI_AC_ENC_INDEX(run, 65)];
  3115. }else{
  3116. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3117. if(prev_level){
  3118. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3119. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3120. }
  3121. }
  3122. }
  3123. score *= lambda;
  3124. unquant_change= new_coeff - old_coeff;
  3125. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3126. score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
  3127. if(score<best_score){
  3128. best_score= score;
  3129. best_coeff= i;
  3130. best_change= change;
  3131. best_unquant_change= unquant_change;
  3132. }
  3133. }
  3134. if(level){
  3135. prev_level= level + 64;
  3136. if(prev_level&(~127))
  3137. prev_level= 0;
  3138. prev_run= run;
  3139. run=0;
  3140. }else{
  3141. run++;
  3142. }
  3143. }
  3144. #ifdef REFINE_STATS
  3145. STOP_TIMER("iterative step")}
  3146. #endif
  3147. if(best_change){
  3148. int j= perm_scantable[ best_coeff ];
  3149. block[j] += best_change;
  3150. if(best_coeff > last_non_zero){
  3151. last_non_zero= best_coeff;
  3152. assert(block[j]);
  3153. #ifdef REFINE_STATS
  3154. after_last++;
  3155. #endif
  3156. }else{
  3157. #ifdef REFINE_STATS
  3158. if(block[j]){
  3159. if(block[j] - best_change){
  3160. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3161. raise++;
  3162. }else{
  3163. lower++;
  3164. }
  3165. }else{
  3166. from_zero++;
  3167. }
  3168. }else{
  3169. to_zero++;
  3170. }
  3171. #endif
  3172. for(; last_non_zero>=start_i; last_non_zero--){
  3173. if(block[perm_scantable[last_non_zero]])
  3174. break;
  3175. }
  3176. }
  3177. #ifdef REFINE_STATS
  3178. count++;
  3179. if(256*256*256*64 % count == 0){
  3180. printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
  3181. }
  3182. #endif
  3183. run=0;
  3184. rle_index=0;
  3185. for(i=start_i; i<=last_non_zero; i++){
  3186. int j= perm_scantable[i];
  3187. const int level= block[j];
  3188. if(level){
  3189. run_tab[rle_index++]=run;
  3190. run=0;
  3191. }else{
  3192. run++;
  3193. }
  3194. }
  3195. s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3196. }else{
  3197. break;
  3198. }
  3199. }
  3200. #ifdef REFINE_STATS
  3201. if(last_non_zero>0){
  3202. STOP_TIMER("iterative search")
  3203. }
  3204. }
  3205. #endif
  3206. return last_non_zero;
  3207. }
  3208. int dct_quantize_c(MpegEncContext *s,
  3209. DCTELEM *block, int n,
  3210. int qscale, int *overflow)
  3211. {
  3212. int i, j, level, last_non_zero, q, start_i;
  3213. const int *qmat;
  3214. const uint8_t *scantable= s->intra_scantable.scantable;
  3215. int bias;
  3216. int max=0;
  3217. unsigned int threshold1, threshold2;
  3218. s->dsp.fdct (block);
  3219. if(s->dct_error_sum)
  3220. s->denoise_dct(s, block);
  3221. if (s->mb_intra) {
  3222. if (!s->h263_aic) {
  3223. if (n < 4)
  3224. q = s->y_dc_scale;
  3225. else
  3226. q = s->c_dc_scale;
  3227. q = q << 3;
  3228. } else
  3229. /* For AIC we skip quant/dequant of INTRADC */
  3230. q = 1 << 3;
  3231. /* note: block[0] is assumed to be positive */
  3232. block[0] = (block[0] + (q >> 1)) / q;
  3233. start_i = 1;
  3234. last_non_zero = 0;
  3235. qmat = s->q_intra_matrix[qscale];
  3236. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3237. } else {
  3238. start_i = 0;
  3239. last_non_zero = -1;
  3240. qmat = s->q_inter_matrix[qscale];
  3241. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3242. }
  3243. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3244. threshold2= (threshold1<<1);
  3245. for(i=63;i>=start_i;i--) {
  3246. j = scantable[i];
  3247. level = block[j] * qmat[j];
  3248. if(((unsigned)(level+threshold1))>threshold2){
  3249. last_non_zero = i;
  3250. break;
  3251. }else{
  3252. block[j]=0;
  3253. }
  3254. }
  3255. for(i=start_i; i<=last_non_zero; i++) {
  3256. j = scantable[i];
  3257. level = block[j] * qmat[j];
  3258. // if( bias+level >= (1<<QMAT_SHIFT)
  3259. // || bias-level >= (1<<QMAT_SHIFT)){
  3260. if(((unsigned)(level+threshold1))>threshold2){
  3261. if(level>0){
  3262. level= (bias + level)>>QMAT_SHIFT;
  3263. block[j]= level;
  3264. }else{
  3265. level= (bias - level)>>QMAT_SHIFT;
  3266. block[j]= -level;
  3267. }
  3268. max |=level;
  3269. }else{
  3270. block[j]=0;
  3271. }
  3272. }
  3273. *overflow= s->max_qcoeff < max; //overflow might have happened
  3274. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3275. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3276. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3277. return last_non_zero;
  3278. }
  3279. AVCodec ff_h263_encoder = {
  3280. "h263",
  3281. AVMEDIA_TYPE_VIDEO,
  3282. CODEC_ID_H263,
  3283. sizeof(MpegEncContext),
  3284. MPV_encode_init,
  3285. MPV_encode_picture,
  3286. MPV_encode_end,
  3287. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3288. .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3289. };
  3290. AVCodec ff_h263p_encoder = {
  3291. "h263p",
  3292. AVMEDIA_TYPE_VIDEO,
  3293. CODEC_ID_H263P,
  3294. sizeof(MpegEncContext),
  3295. MPV_encode_init,
  3296. MPV_encode_picture,
  3297. MPV_encode_end,
  3298. .capabilities = CODEC_CAP_SLICE_THREADS,
  3299. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3300. .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  3301. };
  3302. AVCodec ff_msmpeg4v2_encoder = {
  3303. "msmpeg4v2",
  3304. AVMEDIA_TYPE_VIDEO,
  3305. CODEC_ID_MSMPEG4V2,
  3306. sizeof(MpegEncContext),
  3307. MPV_encode_init,
  3308. MPV_encode_picture,
  3309. MPV_encode_end,
  3310. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3311. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  3312. };
  3313. AVCodec ff_msmpeg4v3_encoder = {
  3314. "msmpeg4",
  3315. AVMEDIA_TYPE_VIDEO,
  3316. CODEC_ID_MSMPEG4V3,
  3317. sizeof(MpegEncContext),
  3318. MPV_encode_init,
  3319. MPV_encode_picture,
  3320. MPV_encode_end,
  3321. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3322. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  3323. };
  3324. AVCodec ff_wmv1_encoder = {
  3325. "wmv1",
  3326. AVMEDIA_TYPE_VIDEO,
  3327. CODEC_ID_WMV1,
  3328. sizeof(MpegEncContext),
  3329. MPV_encode_init,
  3330. MPV_encode_picture,
  3331. MPV_encode_end,
  3332. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3333. .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  3334. };