mpegvideo_enc.c 138 KB

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