mpegvideo_enc.c 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820
  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. s->progressive_frame=
  579. s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
  580. /* init */
  581. if (MPV_common_init(s) < 0)
  582. return -1;
  583. if(!s->dct_quantize)
  584. s->dct_quantize = dct_quantize_c;
  585. if(!s->denoise_dct)
  586. s->denoise_dct = denoise_dct_c;
  587. s->fast_dct_quantize = s->dct_quantize;
  588. if(avctx->trellis)
  589. s->dct_quantize = dct_quantize_trellis_c;
  590. if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
  591. s->chroma_qscale_table= ff_h263_chroma_qscale_table;
  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. ff_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. ff_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. ff_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->header_bits = s->header_bits;
  1041. avctx->mv_bits = s->mv_bits;
  1042. avctx->misc_bits = s->misc_bits;
  1043. avctx->i_tex_bits = s->i_tex_bits;
  1044. avctx->p_tex_bits = s->p_tex_bits;
  1045. avctx->i_count = s->i_count;
  1046. avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
  1047. avctx->skip_count = s->skip_count;
  1048. MPV_frame_end(s);
  1049. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1050. ff_mjpeg_encode_picture_trailer(s);
  1051. if(avctx->rc_buffer_size){
  1052. RateControlContext *rcc= &s->rc_context;
  1053. int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1054. if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
  1055. s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
  1056. if(s->adaptive_quant){
  1057. int i;
  1058. for(i=0; i<s->mb_height*s->mb_stride; i++)
  1059. s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
  1060. }
  1061. s->mb_skipped = 0; //done in MPV_frame_start()
  1062. if(s->pict_type==FF_P_TYPE){ //done in encode_picture() so we must undo it
  1063. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  1064. s->no_rounding ^= 1;
  1065. }
  1066. if(s->pict_type!=FF_B_TYPE){
  1067. s->time_base= s->last_time_base;
  1068. s->last_non_b_time= s->time - s->pp_time;
  1069. }
  1070. // av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
  1071. for(i=0; i<avctx->thread_count; i++){
  1072. PutBitContext *pb= &s->thread_context[i]->pb;
  1073. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1074. }
  1075. goto vbv_retry;
  1076. }
  1077. assert(s->avctx->rc_max_rate);
  1078. }
  1079. if(s->flags&CODEC_FLAG_PASS1)
  1080. ff_write_pass1_stats(s);
  1081. for(i=0; i<4; i++){
  1082. s->current_picture_ptr->error[i]= s->current_picture.error[i];
  1083. avctx->error[i] += s->current_picture_ptr->error[i];
  1084. }
  1085. if(s->flags&CODEC_FLAG_PASS1)
  1086. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
  1087. flush_put_bits(&s->pb);
  1088. s->frame_bits = put_bits_count(&s->pb);
  1089. stuffing_count= ff_vbv_update(s, s->frame_bits);
  1090. if(stuffing_count){
  1091. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
  1092. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1093. return -1;
  1094. }
  1095. switch(s->codec_id){
  1096. case CODEC_ID_MPEG1VIDEO:
  1097. case CODEC_ID_MPEG2VIDEO:
  1098. while(stuffing_count--){
  1099. put_bits(&s->pb, 8, 0);
  1100. }
  1101. break;
  1102. case CODEC_ID_MPEG4:
  1103. put_bits(&s->pb, 16, 0);
  1104. put_bits(&s->pb, 16, 0x1C3);
  1105. stuffing_count -= 4;
  1106. while(stuffing_count--){
  1107. put_bits(&s->pb, 8, 0xFF);
  1108. }
  1109. break;
  1110. default:
  1111. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1112. }
  1113. flush_put_bits(&s->pb);
  1114. s->frame_bits = put_bits_count(&s->pb);
  1115. }
  1116. /* update mpeg1/2 vbv_delay for CBR */
  1117. if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
  1118. && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
  1119. int vbv_delay, min_delay;
  1120. double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
  1121. int minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
  1122. double bits = s->rc_context.buffer_index + minbits - inbits;
  1123. if(bits<0)
  1124. av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
  1125. assert(s->repeat_first_field==0);
  1126. vbv_delay= bits * 90000 / s->avctx->rc_max_rate;
  1127. min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
  1128. vbv_delay= FFMAX(vbv_delay, min_delay);
  1129. assert(vbv_delay < 0xFFFF);
  1130. s->vbv_delay_ptr[0] &= 0xF8;
  1131. s->vbv_delay_ptr[0] |= vbv_delay>>13;
  1132. s->vbv_delay_ptr[1] = vbv_delay>>5;
  1133. s->vbv_delay_ptr[2] &= 0x07;
  1134. s->vbv_delay_ptr[2] |= vbv_delay<<3;
  1135. }
  1136. s->total_bits += s->frame_bits;
  1137. avctx->frame_bits = s->frame_bits;
  1138. }else{
  1139. assert((put_bits_ptr(&s->pb) == s->pb.buf));
  1140. s->frame_bits=0;
  1141. }
  1142. assert((s->frame_bits&7)==0);
  1143. return s->frame_bits/8;
  1144. }
  1145. static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
  1146. {
  1147. static const char tab[64]=
  1148. {3,2,2,1,1,1,1,1,
  1149. 1,1,1,1,1,1,1,1,
  1150. 1,1,1,1,1,1,1,1,
  1151. 0,0,0,0,0,0,0,0,
  1152. 0,0,0,0,0,0,0,0,
  1153. 0,0,0,0,0,0,0,0,
  1154. 0,0,0,0,0,0,0,0,
  1155. 0,0,0,0,0,0,0,0};
  1156. int score=0;
  1157. int run=0;
  1158. int i;
  1159. DCTELEM *block= s->block[n];
  1160. const int last_index= s->block_last_index[n];
  1161. int skip_dc;
  1162. if(threshold<0){
  1163. skip_dc=0;
  1164. threshold= -threshold;
  1165. }else
  1166. skip_dc=1;
  1167. /* Are all we could set to zero already zero? */
  1168. if(last_index<=skip_dc - 1) return;
  1169. for(i=0; i<=last_index; i++){
  1170. const int j = s->intra_scantable.permutated[i];
  1171. const int level = FFABS(block[j]);
  1172. if(level==1){
  1173. if(skip_dc && i==0) continue;
  1174. score+= tab[run];
  1175. run=0;
  1176. }else if(level>1){
  1177. return;
  1178. }else{
  1179. run++;
  1180. }
  1181. }
  1182. if(score >= threshold) return;
  1183. for(i=skip_dc; i<=last_index; i++){
  1184. const int j = s->intra_scantable.permutated[i];
  1185. block[j]=0;
  1186. }
  1187. if(block[0]) s->block_last_index[n]= 0;
  1188. else s->block_last_index[n]= -1;
  1189. }
  1190. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
  1191. {
  1192. int i;
  1193. const int maxlevel= s->max_qcoeff;
  1194. const int minlevel= s->min_qcoeff;
  1195. int overflow=0;
  1196. if(s->mb_intra){
  1197. i=1; //skip clipping of intra dc
  1198. }else
  1199. i=0;
  1200. for(;i<=last_index; i++){
  1201. const int j= s->intra_scantable.permutated[i];
  1202. int level = block[j];
  1203. if (level>maxlevel){
  1204. level=maxlevel;
  1205. overflow++;
  1206. }else if(level<minlevel){
  1207. level=minlevel;
  1208. overflow++;
  1209. }
  1210. block[j]= level;
  1211. }
  1212. if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1213. av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
  1214. }
  1215. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
  1216. int x, y;
  1217. //FIXME optimize
  1218. for(y=0; y<8; y++){
  1219. for(x=0; x<8; x++){
  1220. int x2, y2;
  1221. int sum=0;
  1222. int sqr=0;
  1223. int count=0;
  1224. for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
  1225. for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
  1226. int v= ptr[x2 + y2*stride];
  1227. sum += v;
  1228. sqr += v*v;
  1229. count++;
  1230. }
  1231. }
  1232. weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
  1233. }
  1234. }
  1235. }
  1236. static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
  1237. {
  1238. int16_t weight[8][64];
  1239. DCTELEM orig[8][64];
  1240. const int mb_x= s->mb_x;
  1241. const int mb_y= s->mb_y;
  1242. int i;
  1243. int skip_dct[8];
  1244. int dct_offset = s->linesize*8; //default for progressive frames
  1245. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1246. int wrap_y, wrap_c;
  1247. for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
  1248. if(s->adaptive_quant){
  1249. const int last_qp= s->qscale;
  1250. const int mb_xy= mb_x + mb_y*s->mb_stride;
  1251. s->lambda= s->lambda_table[mb_xy];
  1252. update_qscale(s);
  1253. if(!(s->flags&CODEC_FLAG_QP_RD)){
  1254. s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
  1255. s->dquant= s->qscale - last_qp;
  1256. if(s->out_format==FMT_H263){
  1257. s->dquant= av_clip(s->dquant, -2, 2);
  1258. if(s->codec_id==CODEC_ID_MPEG4){
  1259. if(!s->mb_intra){
  1260. if(s->pict_type == FF_B_TYPE){
  1261. if(s->dquant&1 || s->mv_dir&MV_DIRECT)
  1262. s->dquant= 0;
  1263. }
  1264. if(s->mv_type==MV_TYPE_8X8)
  1265. s->dquant=0;
  1266. }
  1267. }
  1268. }
  1269. }
  1270. ff_set_qscale(s, last_qp + s->dquant);
  1271. }else if(s->flags&CODEC_FLAG_QP_RD)
  1272. ff_set_qscale(s, s->qscale + s->dquant);
  1273. wrap_y = s->linesize;
  1274. wrap_c = s->uvlinesize;
  1275. ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  1276. ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1277. ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1278. if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
  1279. uint8_t *ebuf= s->edge_emu_buffer + 32;
  1280. ff_emulated_edge_mc(ebuf , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width , s->height);
  1281. ptr_y= ebuf;
  1282. 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);
  1283. ptr_cb= ebuf+18*wrap_y;
  1284. 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);
  1285. ptr_cr= ebuf+18*wrap_y+8;
  1286. }
  1287. if (s->mb_intra) {
  1288. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1289. int progressive_score, interlaced_score;
  1290. s->interlaced_dct=0;
  1291. progressive_score= s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y, 8)
  1292. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
  1293. if(progressive_score > 0){
  1294. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y*2, 8)
  1295. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y , NULL, wrap_y*2, 8);
  1296. if(progressive_score > interlaced_score){
  1297. s->interlaced_dct=1;
  1298. dct_offset= wrap_y;
  1299. wrap_y<<=1;
  1300. if (s->chroma_format == CHROMA_422)
  1301. wrap_c<<=1;
  1302. }
  1303. }
  1304. }
  1305. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1306. s->dsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
  1307. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1308. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  1309. if(s->flags&CODEC_FLAG_GRAY){
  1310. skip_dct[4]= 1;
  1311. skip_dct[5]= 1;
  1312. }else{
  1313. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1314. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1315. if(!s->chroma_y_shift){ /* 422 */
  1316. s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
  1317. s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
  1318. }
  1319. }
  1320. }else{
  1321. op_pixels_func (*op_pix)[4];
  1322. qpel_mc_func (*op_qpix)[16];
  1323. uint8_t *dest_y, *dest_cb, *dest_cr;
  1324. dest_y = s->dest[0];
  1325. dest_cb = s->dest[1];
  1326. dest_cr = s->dest[2];
  1327. if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){
  1328. op_pix = s->dsp.put_pixels_tab;
  1329. op_qpix= s->dsp.put_qpel_pixels_tab;
  1330. }else{
  1331. op_pix = s->dsp.put_no_rnd_pixels_tab;
  1332. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  1333. }
  1334. if (s->mv_dir & MV_DIR_FORWARD) {
  1335. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  1336. op_pix = s->dsp.avg_pixels_tab;
  1337. op_qpix= s->dsp.avg_qpel_pixels_tab;
  1338. }
  1339. if (s->mv_dir & MV_DIR_BACKWARD) {
  1340. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  1341. }
  1342. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1343. int progressive_score, interlaced_score;
  1344. s->interlaced_dct=0;
  1345. progressive_score= s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y, 8)
  1346. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
  1347. if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
  1348. if(progressive_score>0){
  1349. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y*2, 8)
  1350. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y , ptr_y + wrap_y , wrap_y*2, 8);
  1351. if(progressive_score > interlaced_score){
  1352. s->interlaced_dct=1;
  1353. dct_offset= wrap_y;
  1354. wrap_y<<=1;
  1355. if (s->chroma_format == CHROMA_422)
  1356. wrap_c<<=1;
  1357. }
  1358. }
  1359. }
  1360. s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
  1361. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1362. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
  1363. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
  1364. if(s->flags&CODEC_FLAG_GRAY){
  1365. skip_dct[4]= 1;
  1366. skip_dct[5]= 1;
  1367. }else{
  1368. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1369. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1370. if(!s->chroma_y_shift){ /* 422 */
  1371. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
  1372. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
  1373. }
  1374. }
  1375. /* pre quantization */
  1376. if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
  1377. //FIXME optimize
  1378. if(s->dsp.sad[1](NULL, ptr_y , dest_y , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
  1379. if(s->dsp.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
  1380. if(s->dsp.sad[1](NULL, ptr_y +dct_offset , dest_y +dct_offset , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
  1381. 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;
  1382. if(s->dsp.sad[1](NULL, ptr_cb , dest_cb , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
  1383. if(s->dsp.sad[1](NULL, ptr_cr , dest_cr , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
  1384. if(!s->chroma_y_shift){ /* 422 */
  1385. 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;
  1386. 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;
  1387. }
  1388. }
  1389. }
  1390. if(s->avctx->quantizer_noise_shaping){
  1391. if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y , wrap_y);
  1392. if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1393. if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1394. if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1395. if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb , wrap_c);
  1396. if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr , wrap_c);
  1397. if(!s->chroma_y_shift){ /* 422 */
  1398. if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
  1399. if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
  1400. }
  1401. memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
  1402. }
  1403. /* DCT & quantize */
  1404. assert(s->out_format!=FMT_MJPEG || s->qscale==8);
  1405. {
  1406. for(i=0;i<mb_block_count;i++) {
  1407. if(!skip_dct[i]){
  1408. int overflow;
  1409. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1410. // FIXME we could decide to change to quantizer instead of clipping
  1411. // JS: I don't think that would be a good idea it could lower quality instead
  1412. // of improve it. Just INTRADC clipping deserves changes in quantizer
  1413. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1414. }else
  1415. s->block_last_index[i]= -1;
  1416. }
  1417. if(s->avctx->quantizer_noise_shaping){
  1418. for(i=0;i<mb_block_count;i++) {
  1419. if(!skip_dct[i]){
  1420. s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
  1421. }
  1422. }
  1423. }
  1424. if(s->luma_elim_threshold && !s->mb_intra)
  1425. for(i=0; i<4; i++)
  1426. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1427. if(s->chroma_elim_threshold && !s->mb_intra)
  1428. for(i=4; i<mb_block_count; i++)
  1429. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1430. if(s->flags & CODEC_FLAG_CBP_RD){
  1431. for(i=0;i<mb_block_count;i++) {
  1432. if(s->block_last_index[i] == -1)
  1433. s->coded_score[i]= INT_MAX/256;
  1434. }
  1435. }
  1436. }
  1437. if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
  1438. s->block_last_index[4]=
  1439. s->block_last_index[5]= 0;
  1440. s->block[4][0]=
  1441. s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
  1442. }
  1443. //non c quantize code returns incorrect block_last_index FIXME
  1444. if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
  1445. for(i=0; i<mb_block_count; i++){
  1446. int j;
  1447. if(s->block_last_index[i]>0){
  1448. for(j=63; j>0; j--){
  1449. if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
  1450. }
  1451. s->block_last_index[i]= j;
  1452. }
  1453. }
  1454. }
  1455. /* huffman encode */
  1456. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1457. case CODEC_ID_MPEG1VIDEO:
  1458. case CODEC_ID_MPEG2VIDEO:
  1459. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1460. mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1461. break;
  1462. case CODEC_ID_MPEG4:
  1463. if (CONFIG_MPEG4_ENCODER)
  1464. mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1465. break;
  1466. case CODEC_ID_MSMPEG4V2:
  1467. case CODEC_ID_MSMPEG4V3:
  1468. case CODEC_ID_WMV1:
  1469. if (CONFIG_MSMPEG4_ENCODER)
  1470. msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1471. break;
  1472. case CODEC_ID_WMV2:
  1473. if (CONFIG_WMV2_ENCODER)
  1474. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1475. break;
  1476. case CODEC_ID_H261:
  1477. if (CONFIG_H261_ENCODER)
  1478. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1479. break;
  1480. case CODEC_ID_H263:
  1481. case CODEC_ID_H263P:
  1482. case CODEC_ID_FLV1:
  1483. case CODEC_ID_RV10:
  1484. case CODEC_ID_RV20:
  1485. if (CONFIG_H263_ENCODER)
  1486. h263_encode_mb(s, s->block, motion_x, motion_y);
  1487. break;
  1488. case CODEC_ID_MJPEG:
  1489. if (CONFIG_MJPEG_ENCODER)
  1490. ff_mjpeg_encode_mb(s, s->block);
  1491. break;
  1492. default:
  1493. assert(0);
  1494. }
  1495. }
  1496. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1497. {
  1498. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1499. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1500. }
  1501. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1502. int i;
  1503. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1504. /* mpeg1 */
  1505. d->mb_skip_run= s->mb_skip_run;
  1506. for(i=0; i<3; i++)
  1507. d->last_dc[i]= s->last_dc[i];
  1508. /* statistics */
  1509. d->mv_bits= s->mv_bits;
  1510. d->i_tex_bits= s->i_tex_bits;
  1511. d->p_tex_bits= s->p_tex_bits;
  1512. d->i_count= s->i_count;
  1513. d->f_count= s->f_count;
  1514. d->b_count= s->b_count;
  1515. d->skip_count= s->skip_count;
  1516. d->misc_bits= s->misc_bits;
  1517. d->last_bits= 0;
  1518. d->mb_skipped= 0;
  1519. d->qscale= s->qscale;
  1520. d->dquant= s->dquant;
  1521. d->esc3_level_length= s->esc3_level_length;
  1522. }
  1523. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1524. int i;
  1525. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1526. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1527. /* mpeg1 */
  1528. d->mb_skip_run= s->mb_skip_run;
  1529. for(i=0; i<3; i++)
  1530. d->last_dc[i]= s->last_dc[i];
  1531. /* statistics */
  1532. d->mv_bits= s->mv_bits;
  1533. d->i_tex_bits= s->i_tex_bits;
  1534. d->p_tex_bits= s->p_tex_bits;
  1535. d->i_count= s->i_count;
  1536. d->f_count= s->f_count;
  1537. d->b_count= s->b_count;
  1538. d->skip_count= s->skip_count;
  1539. d->misc_bits= s->misc_bits;
  1540. d->mb_intra= s->mb_intra;
  1541. d->mb_skipped= s->mb_skipped;
  1542. d->mv_type= s->mv_type;
  1543. d->mv_dir= s->mv_dir;
  1544. d->pb= s->pb;
  1545. if(s->data_partitioning){
  1546. d->pb2= s->pb2;
  1547. d->tex_pb= s->tex_pb;
  1548. }
  1549. d->block= s->block;
  1550. for(i=0; i<8; i++)
  1551. d->block_last_index[i]= s->block_last_index[i];
  1552. d->interlaced_dct= s->interlaced_dct;
  1553. d->qscale= s->qscale;
  1554. d->esc3_level_length= s->esc3_level_length;
  1555. }
  1556. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1557. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1558. int *dmin, int *next_block, int motion_x, int motion_y)
  1559. {
  1560. int score;
  1561. uint8_t *dest_backup[3];
  1562. copy_context_before_encode(s, backup, type);
  1563. s->block= s->blocks[*next_block];
  1564. s->pb= pb[*next_block];
  1565. if(s->data_partitioning){
  1566. s->pb2 = pb2 [*next_block];
  1567. s->tex_pb= tex_pb[*next_block];
  1568. }
  1569. if(*next_block){
  1570. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1571. s->dest[0] = s->rd_scratchpad;
  1572. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1573. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1574. assert(s->linesize >= 32); //FIXME
  1575. }
  1576. encode_mb(s, motion_x, motion_y);
  1577. score= put_bits_count(&s->pb);
  1578. if(s->data_partitioning){
  1579. score+= put_bits_count(&s->pb2);
  1580. score+= put_bits_count(&s->tex_pb);
  1581. }
  1582. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1583. MPV_decode_mb(s, s->block);
  1584. score *= s->lambda2;
  1585. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1586. }
  1587. if(*next_block){
  1588. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1589. }
  1590. if(score<*dmin){
  1591. *dmin= score;
  1592. *next_block^=1;
  1593. copy_context_after_encode(best, s, type);
  1594. }
  1595. }
  1596. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1597. uint32_t *sq = ff_squareTbl + 256;
  1598. int acc=0;
  1599. int x,y;
  1600. if(w==16 && h==16)
  1601. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  1602. else if(w==8 && h==8)
  1603. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  1604. for(y=0; y<h; y++){
  1605. for(x=0; x<w; x++){
  1606. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  1607. }
  1608. }
  1609. assert(acc>=0);
  1610. return acc;
  1611. }
  1612. static int sse_mb(MpegEncContext *s){
  1613. int w= 16;
  1614. int h= 16;
  1615. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  1616. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  1617. if(w==16 && h==16)
  1618. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  1619. 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)
  1620. +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)
  1621. +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);
  1622. }else{
  1623. 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)
  1624. +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)
  1625. +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);
  1626. }
  1627. else
  1628. 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)
  1629. +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)
  1630. +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);
  1631. }
  1632. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  1633. MpegEncContext *s= *(void**)arg;
  1634. s->me.pre_pass=1;
  1635. s->me.dia_size= s->avctx->pre_dia_size;
  1636. s->first_slice_line=1;
  1637. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  1638. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  1639. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1640. }
  1641. s->first_slice_line=0;
  1642. }
  1643. s->me.pre_pass=0;
  1644. return 0;
  1645. }
  1646. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  1647. MpegEncContext *s= *(void**)arg;
  1648. ff_check_alignment();
  1649. s->me.dia_size= s->avctx->dia_size;
  1650. s->first_slice_line=1;
  1651. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  1652. s->mb_x=0; //for block init below
  1653. ff_init_block_index(s);
  1654. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  1655. s->block_index[0]+=2;
  1656. s->block_index[1]+=2;
  1657. s->block_index[2]+=2;
  1658. s->block_index[3]+=2;
  1659. /* compute motion vector & mb_type and store in context */
  1660. if(s->pict_type==FF_B_TYPE)
  1661. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  1662. else
  1663. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1664. }
  1665. s->first_slice_line=0;
  1666. }
  1667. return 0;
  1668. }
  1669. static int mb_var_thread(AVCodecContext *c, void *arg){
  1670. MpegEncContext *s= *(void**)arg;
  1671. int mb_x, mb_y;
  1672. ff_check_alignment();
  1673. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1674. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1675. int xx = mb_x * 16;
  1676. int yy = mb_y * 16;
  1677. uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
  1678. int varc;
  1679. int sum = s->dsp.pix_sum(pix, s->linesize);
  1680. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
  1681. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  1682. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  1683. s->me.mb_var_sum_temp += varc;
  1684. }
  1685. }
  1686. return 0;
  1687. }
  1688. static void write_slice_end(MpegEncContext *s){
  1689. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
  1690. if(s->partitioned_frame){
  1691. ff_mpeg4_merge_partitions(s);
  1692. }
  1693. ff_mpeg4_stuffing(&s->pb);
  1694. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  1695. ff_mjpeg_encode_stuffing(&s->pb);
  1696. }
  1697. align_put_bits(&s->pb);
  1698. flush_put_bits(&s->pb);
  1699. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  1700. s->misc_bits+= get_bits_diff(s);
  1701. }
  1702. static int encode_thread(AVCodecContext *c, void *arg){
  1703. MpegEncContext *s= *(void**)arg;
  1704. int mb_x, mb_y, pdif = 0;
  1705. int chr_h= 16>>s->chroma_y_shift;
  1706. int i, j;
  1707. MpegEncContext best_s, backup_s;
  1708. uint8_t bit_buf[2][MAX_MB_BYTES];
  1709. uint8_t bit_buf2[2][MAX_MB_BYTES];
  1710. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  1711. PutBitContext pb[2], pb2[2], tex_pb[2];
  1712. //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
  1713. ff_check_alignment();
  1714. for(i=0; i<2; i++){
  1715. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  1716. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  1717. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  1718. }
  1719. s->last_bits= put_bits_count(&s->pb);
  1720. s->mv_bits=0;
  1721. s->misc_bits=0;
  1722. s->i_tex_bits=0;
  1723. s->p_tex_bits=0;
  1724. s->i_count=0;
  1725. s->f_count=0;
  1726. s->b_count=0;
  1727. s->skip_count=0;
  1728. for(i=0; i<3; i++){
  1729. /* init last dc values */
  1730. /* note: quant matrix value (8) is implied here */
  1731. s->last_dc[i] = 128 << s->intra_dc_precision;
  1732. s->current_picture.error[i] = 0;
  1733. }
  1734. s->mb_skip_run = 0;
  1735. memset(s->last_mv, 0, sizeof(s->last_mv));
  1736. s->last_mv_dir = 0;
  1737. switch(s->codec_id){
  1738. case CODEC_ID_H263:
  1739. case CODEC_ID_H263P:
  1740. case CODEC_ID_FLV1:
  1741. if (CONFIG_H263_ENCODER)
  1742. s->gob_index = ff_h263_get_gob_height(s);
  1743. break;
  1744. case CODEC_ID_MPEG4:
  1745. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  1746. ff_mpeg4_init_partitions(s);
  1747. break;
  1748. }
  1749. s->resync_mb_x=0;
  1750. s->resync_mb_y=0;
  1751. s->first_slice_line = 1;
  1752. s->ptr_lastgob = s->pb.buf;
  1753. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1754. // printf("row %d at %X\n", s->mb_y, (int)s);
  1755. s->mb_x=0;
  1756. s->mb_y= mb_y;
  1757. ff_set_qscale(s, s->qscale);
  1758. ff_init_block_index(s);
  1759. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1760. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  1761. int mb_type= s->mb_type[xy];
  1762. // int d;
  1763. int dmin= INT_MAX;
  1764. int dir;
  1765. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  1766. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1767. return -1;
  1768. }
  1769. if(s->data_partitioning){
  1770. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  1771. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  1772. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1773. return -1;
  1774. }
  1775. }
  1776. s->mb_x = mb_x;
  1777. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  1778. ff_update_block_index(s);
  1779. if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
  1780. ff_h261_reorder_mb_index(s);
  1781. xy= s->mb_y*s->mb_stride + s->mb_x;
  1782. mb_type= s->mb_type[xy];
  1783. }
  1784. /* write gob / video packet header */
  1785. if(s->rtp_mode){
  1786. int current_packet_size, is_gob_start;
  1787. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  1788. is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  1789. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  1790. switch(s->codec_id){
  1791. case CODEC_ID_H263:
  1792. case CODEC_ID_H263P:
  1793. if(!s->h263_slice_structured)
  1794. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  1795. break;
  1796. case CODEC_ID_MPEG2VIDEO:
  1797. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  1798. case CODEC_ID_MPEG1VIDEO:
  1799. if(s->mb_skip_run) is_gob_start=0;
  1800. break;
  1801. }
  1802. if(is_gob_start){
  1803. if(s->start_mb_y != mb_y || mb_x!=0){
  1804. write_slice_end(s);
  1805. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
  1806. ff_mpeg4_init_partitions(s);
  1807. }
  1808. }
  1809. assert((put_bits_count(&s->pb)&7) == 0);
  1810. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  1811. if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
  1812. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  1813. int d= 100 / s->avctx->error_rate;
  1814. if(r % d == 0){
  1815. current_packet_size=0;
  1816. #ifndef ALT_BITSTREAM_WRITER
  1817. s->pb.buf_ptr= s->ptr_lastgob;
  1818. #endif
  1819. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  1820. }
  1821. }
  1822. if (s->avctx->rtp_callback){
  1823. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  1824. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  1825. }
  1826. switch(s->codec_id){
  1827. case CODEC_ID_MPEG4:
  1828. if (CONFIG_MPEG4_ENCODER) {
  1829. ff_mpeg4_encode_video_packet_header(s);
  1830. ff_mpeg4_clean_buffers(s);
  1831. }
  1832. break;
  1833. case CODEC_ID_MPEG1VIDEO:
  1834. case CODEC_ID_MPEG2VIDEO:
  1835. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  1836. ff_mpeg1_encode_slice_header(s);
  1837. ff_mpeg1_clean_buffers(s);
  1838. }
  1839. break;
  1840. case CODEC_ID_H263:
  1841. case CODEC_ID_H263P:
  1842. if (CONFIG_H263_ENCODER)
  1843. h263_encode_gob_header(s, mb_y);
  1844. break;
  1845. }
  1846. if(s->flags&CODEC_FLAG_PASS1){
  1847. int bits= put_bits_count(&s->pb);
  1848. s->misc_bits+= bits - s->last_bits;
  1849. s->last_bits= bits;
  1850. }
  1851. s->ptr_lastgob += current_packet_size;
  1852. s->first_slice_line=1;
  1853. s->resync_mb_x=mb_x;
  1854. s->resync_mb_y=mb_y;
  1855. }
  1856. }
  1857. if( (s->resync_mb_x == s->mb_x)
  1858. && s->resync_mb_y+1 == s->mb_y){
  1859. s->first_slice_line=0;
  1860. }
  1861. s->mb_skipped=0;
  1862. s->dquant=0; //only for QP_RD
  1863. if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
  1864. int next_block=0;
  1865. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  1866. copy_context_before_encode(&backup_s, s, -1);
  1867. backup_s.pb= s->pb;
  1868. best_s.data_partitioning= s->data_partitioning;
  1869. best_s.partitioned_frame= s->partitioned_frame;
  1870. if(s->data_partitioning){
  1871. backup_s.pb2= s->pb2;
  1872. backup_s.tex_pb= s->tex_pb;
  1873. }
  1874. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  1875. s->mv_dir = MV_DIR_FORWARD;
  1876. s->mv_type = MV_TYPE_16X16;
  1877. s->mb_intra= 0;
  1878. s->mv[0][0][0] = s->p_mv_table[xy][0];
  1879. s->mv[0][0][1] = s->p_mv_table[xy][1];
  1880. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  1881. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1882. }
  1883. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  1884. s->mv_dir = MV_DIR_FORWARD;
  1885. s->mv_type = MV_TYPE_FIELD;
  1886. s->mb_intra= 0;
  1887. for(i=0; i<2; i++){
  1888. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  1889. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  1890. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  1891. }
  1892. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  1893. &dmin, &next_block, 0, 0);
  1894. }
  1895. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  1896. s->mv_dir = MV_DIR_FORWARD;
  1897. s->mv_type = MV_TYPE_16X16;
  1898. s->mb_intra= 0;
  1899. s->mv[0][0][0] = 0;
  1900. s->mv[0][0][1] = 0;
  1901. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  1902. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1903. }
  1904. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  1905. s->mv_dir = MV_DIR_FORWARD;
  1906. s->mv_type = MV_TYPE_8X8;
  1907. s->mb_intra= 0;
  1908. for(i=0; i<4; i++){
  1909. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  1910. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  1911. }
  1912. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  1913. &dmin, &next_block, 0, 0);
  1914. }
  1915. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  1916. s->mv_dir = MV_DIR_FORWARD;
  1917. s->mv_type = MV_TYPE_16X16;
  1918. s->mb_intra= 0;
  1919. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  1920. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  1921. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  1922. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1923. }
  1924. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  1925. s->mv_dir = MV_DIR_BACKWARD;
  1926. s->mv_type = MV_TYPE_16X16;
  1927. s->mb_intra= 0;
  1928. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  1929. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  1930. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  1931. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  1932. }
  1933. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  1934. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  1935. s->mv_type = MV_TYPE_16X16;
  1936. s->mb_intra= 0;
  1937. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  1938. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  1939. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  1940. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  1941. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  1942. &dmin, &next_block, 0, 0);
  1943. }
  1944. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  1945. s->mv_dir = MV_DIR_FORWARD;
  1946. s->mv_type = MV_TYPE_FIELD;
  1947. s->mb_intra= 0;
  1948. for(i=0; i<2; i++){
  1949. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  1950. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  1951. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  1952. }
  1953. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  1954. &dmin, &next_block, 0, 0);
  1955. }
  1956. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  1957. s->mv_dir = MV_DIR_BACKWARD;
  1958. s->mv_type = MV_TYPE_FIELD;
  1959. s->mb_intra= 0;
  1960. for(i=0; i<2; i++){
  1961. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  1962. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  1963. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  1964. }
  1965. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  1966. &dmin, &next_block, 0, 0);
  1967. }
  1968. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  1969. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  1970. s->mv_type = MV_TYPE_FIELD;
  1971. s->mb_intra= 0;
  1972. for(dir=0; dir<2; dir++){
  1973. for(i=0; i<2; i++){
  1974. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  1975. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  1976. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  1977. }
  1978. }
  1979. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  1980. &dmin, &next_block, 0, 0);
  1981. }
  1982. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  1983. s->mv_dir = 0;
  1984. s->mv_type = MV_TYPE_16X16;
  1985. s->mb_intra= 1;
  1986. s->mv[0][0][0] = 0;
  1987. s->mv[0][0][1] = 0;
  1988. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  1989. &dmin, &next_block, 0, 0);
  1990. if(s->h263_pred || s->h263_aic){
  1991. if(best_s.mb_intra)
  1992. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  1993. else
  1994. ff_clean_intra_table_entries(s); //old mode?
  1995. }
  1996. }
  1997. if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
  1998. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  1999. const int last_qp= backup_s.qscale;
  2000. int qpi, qp, dc[6];
  2001. DCTELEM ac[6][16];
  2002. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2003. static const int dquant_tab[4]={-1,1,-2,2};
  2004. assert(backup_s.dquant == 0);
  2005. //FIXME intra
  2006. s->mv_dir= best_s.mv_dir;
  2007. s->mv_type = MV_TYPE_16X16;
  2008. s->mb_intra= best_s.mb_intra;
  2009. s->mv[0][0][0] = best_s.mv[0][0][0];
  2010. s->mv[0][0][1] = best_s.mv[0][0][1];
  2011. s->mv[1][0][0] = best_s.mv[1][0][0];
  2012. s->mv[1][0][1] = best_s.mv[1][0][1];
  2013. qpi = s->pict_type == FF_B_TYPE ? 2 : 0;
  2014. for(; qpi<4; qpi++){
  2015. int dquant= dquant_tab[qpi];
  2016. qp= last_qp + dquant;
  2017. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2018. continue;
  2019. backup_s.dquant= dquant;
  2020. if(s->mb_intra && s->dc_val[0]){
  2021. for(i=0; i<6; i++){
  2022. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2023. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
  2024. }
  2025. }
  2026. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2027. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2028. if(best_s.qscale != qp){
  2029. if(s->mb_intra && s->dc_val[0]){
  2030. for(i=0; i<6; i++){
  2031. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2032. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
  2033. }
  2034. }
  2035. }
  2036. }
  2037. }
  2038. }
  2039. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2040. int mx= s->b_direct_mv_table[xy][0];
  2041. int my= s->b_direct_mv_table[xy][1];
  2042. backup_s.dquant = 0;
  2043. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2044. s->mb_intra= 0;
  2045. ff_mpeg4_set_direct_mv(s, mx, my);
  2046. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2047. &dmin, &next_block, mx, my);
  2048. }
  2049. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2050. backup_s.dquant = 0;
  2051. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2052. s->mb_intra= 0;
  2053. ff_mpeg4_set_direct_mv(s, 0, 0);
  2054. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2055. &dmin, &next_block, 0, 0);
  2056. }
  2057. if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
  2058. int coded=0;
  2059. for(i=0; i<6; i++)
  2060. coded |= s->block_last_index[i];
  2061. if(coded){
  2062. int mx,my;
  2063. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2064. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2065. mx=my=0; //FIXME find the one we actually used
  2066. ff_mpeg4_set_direct_mv(s, mx, my);
  2067. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2068. mx= s->mv[1][0][0];
  2069. my= s->mv[1][0][1];
  2070. }else{
  2071. mx= s->mv[0][0][0];
  2072. my= s->mv[0][0][1];
  2073. }
  2074. s->mv_dir= best_s.mv_dir;
  2075. s->mv_type = best_s.mv_type;
  2076. s->mb_intra= 0;
  2077. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2078. s->mv[0][0][1] = best_s.mv[0][0][1];
  2079. s->mv[1][0][0] = best_s.mv[1][0][0];
  2080. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2081. backup_s.dquant= 0;
  2082. s->skipdct=1;
  2083. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2084. &dmin, &next_block, mx, my);
  2085. s->skipdct=0;
  2086. }
  2087. }
  2088. s->current_picture.qscale_table[xy]= best_s.qscale;
  2089. copy_context_after_encode(s, &best_s, -1);
  2090. pb_bits_count= put_bits_count(&s->pb);
  2091. flush_put_bits(&s->pb);
  2092. ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2093. s->pb= backup_s.pb;
  2094. if(s->data_partitioning){
  2095. pb2_bits_count= put_bits_count(&s->pb2);
  2096. flush_put_bits(&s->pb2);
  2097. ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2098. s->pb2= backup_s.pb2;
  2099. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2100. flush_put_bits(&s->tex_pb);
  2101. ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2102. s->tex_pb= backup_s.tex_pb;
  2103. }
  2104. s->last_bits= put_bits_count(&s->pb);
  2105. if (CONFIG_ANY_H263_ENCODER &&
  2106. s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
  2107. ff_h263_update_motion_val(s);
  2108. if(next_block==0){ //FIXME 16 vs linesize16
  2109. s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
  2110. s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2111. s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2112. }
  2113. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2114. MPV_decode_mb(s, s->block);
  2115. } else {
  2116. int motion_x = 0, motion_y = 0;
  2117. s->mv_type=MV_TYPE_16X16;
  2118. // only one MB-Type possible
  2119. switch(mb_type){
  2120. case CANDIDATE_MB_TYPE_INTRA:
  2121. s->mv_dir = 0;
  2122. s->mb_intra= 1;
  2123. motion_x= s->mv[0][0][0] = 0;
  2124. motion_y= s->mv[0][0][1] = 0;
  2125. break;
  2126. case CANDIDATE_MB_TYPE_INTER:
  2127. s->mv_dir = MV_DIR_FORWARD;
  2128. s->mb_intra= 0;
  2129. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2130. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2131. break;
  2132. case CANDIDATE_MB_TYPE_INTER_I:
  2133. s->mv_dir = MV_DIR_FORWARD;
  2134. s->mv_type = MV_TYPE_FIELD;
  2135. s->mb_intra= 0;
  2136. for(i=0; i<2; i++){
  2137. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2138. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2139. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2140. }
  2141. break;
  2142. case CANDIDATE_MB_TYPE_INTER4V:
  2143. s->mv_dir = MV_DIR_FORWARD;
  2144. s->mv_type = MV_TYPE_8X8;
  2145. s->mb_intra= 0;
  2146. for(i=0; i<4; i++){
  2147. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  2148. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  2149. }
  2150. break;
  2151. case CANDIDATE_MB_TYPE_DIRECT:
  2152. if (CONFIG_MPEG4_ENCODER) {
  2153. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2154. s->mb_intra= 0;
  2155. motion_x=s->b_direct_mv_table[xy][0];
  2156. motion_y=s->b_direct_mv_table[xy][1];
  2157. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2158. }
  2159. break;
  2160. case CANDIDATE_MB_TYPE_DIRECT0:
  2161. if (CONFIG_MPEG4_ENCODER) {
  2162. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2163. s->mb_intra= 0;
  2164. ff_mpeg4_set_direct_mv(s, 0, 0);
  2165. }
  2166. break;
  2167. case CANDIDATE_MB_TYPE_BIDIR:
  2168. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2169. s->mb_intra= 0;
  2170. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2171. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2172. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2173. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2174. break;
  2175. case CANDIDATE_MB_TYPE_BACKWARD:
  2176. s->mv_dir = MV_DIR_BACKWARD;
  2177. s->mb_intra= 0;
  2178. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2179. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2180. break;
  2181. case CANDIDATE_MB_TYPE_FORWARD:
  2182. s->mv_dir = MV_DIR_FORWARD;
  2183. s->mb_intra= 0;
  2184. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2185. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2186. // printf(" %d %d ", motion_x, motion_y);
  2187. break;
  2188. case CANDIDATE_MB_TYPE_FORWARD_I:
  2189. s->mv_dir = MV_DIR_FORWARD;
  2190. s->mv_type = MV_TYPE_FIELD;
  2191. s->mb_intra= 0;
  2192. for(i=0; i<2; i++){
  2193. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2194. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2195. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2196. }
  2197. break;
  2198. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2199. s->mv_dir = MV_DIR_BACKWARD;
  2200. s->mv_type = MV_TYPE_FIELD;
  2201. s->mb_intra= 0;
  2202. for(i=0; i<2; i++){
  2203. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2204. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2205. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2206. }
  2207. break;
  2208. case CANDIDATE_MB_TYPE_BIDIR_I:
  2209. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2210. s->mv_type = MV_TYPE_FIELD;
  2211. s->mb_intra= 0;
  2212. for(dir=0; dir<2; dir++){
  2213. for(i=0; i<2; i++){
  2214. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2215. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2216. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2217. }
  2218. }
  2219. break;
  2220. default:
  2221. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2222. }
  2223. encode_mb(s, motion_x, motion_y);
  2224. // RAL: Update last macroblock type
  2225. s->last_mv_dir = s->mv_dir;
  2226. if (CONFIG_ANY_H263_ENCODER &&
  2227. s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
  2228. ff_h263_update_motion_val(s);
  2229. MPV_decode_mb(s, s->block);
  2230. }
  2231. /* clean the MV table in IPS frames for direct mode in B frames */
  2232. if(s->mb_intra /* && I,P,S_TYPE */){
  2233. s->p_mv_table[xy][0]=0;
  2234. s->p_mv_table[xy][1]=0;
  2235. }
  2236. if(s->flags&CODEC_FLAG_PSNR){
  2237. int w= 16;
  2238. int h= 16;
  2239. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2240. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2241. s->current_picture.error[0] += sse(
  2242. s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2243. s->dest[0], w, h, s->linesize);
  2244. s->current_picture.error[1] += sse(
  2245. s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2246. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2247. s->current_picture.error[2] += sse(
  2248. s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2249. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2250. }
  2251. if(s->loop_filter){
  2252. if(CONFIG_ANY_H263_ENCODER && s->out_format == FMT_H263)
  2253. ff_h263_loop_filter(s);
  2254. }
  2255. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
  2256. }
  2257. }
  2258. //not beautiful here but we must write it before flushing so it has to be here
  2259. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == FF_I_TYPE)
  2260. msmpeg4_encode_ext_header(s);
  2261. write_slice_end(s);
  2262. /* Send the last GOB if RTP */
  2263. if (s->avctx->rtp_callback) {
  2264. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2265. pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2266. /* Call the RTP callback to send the last GOB */
  2267. emms_c();
  2268. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2269. }
  2270. return 0;
  2271. }
  2272. #define MERGE(field) dst->field += src->field; src->field=0
  2273. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2274. MERGE(me.scene_change_score);
  2275. MERGE(me.mc_mb_var_sum_temp);
  2276. MERGE(me.mb_var_sum_temp);
  2277. }
  2278. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2279. int i;
  2280. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2281. MERGE(dct_count[1]);
  2282. MERGE(mv_bits);
  2283. MERGE(i_tex_bits);
  2284. MERGE(p_tex_bits);
  2285. MERGE(i_count);
  2286. MERGE(f_count);
  2287. MERGE(b_count);
  2288. MERGE(skip_count);
  2289. MERGE(misc_bits);
  2290. MERGE(error_count);
  2291. MERGE(padding_bug_score);
  2292. MERGE(current_picture.error[0]);
  2293. MERGE(current_picture.error[1]);
  2294. MERGE(current_picture.error[2]);
  2295. if(dst->avctx->noise_reduction){
  2296. for(i=0; i<64; i++){
  2297. MERGE(dct_error_sum[0][i]);
  2298. MERGE(dct_error_sum[1][i]);
  2299. }
  2300. }
  2301. assert(put_bits_count(&src->pb) % 8 ==0);
  2302. assert(put_bits_count(&dst->pb) % 8 ==0);
  2303. ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2304. flush_put_bits(&dst->pb);
  2305. }
  2306. static int estimate_qp(MpegEncContext *s, int dry_run){
  2307. if (s->next_lambda){
  2308. s->current_picture_ptr->quality=
  2309. s->current_picture.quality = s->next_lambda;
  2310. if(!dry_run) s->next_lambda= 0;
  2311. } else if (!s->fixed_qscale) {
  2312. s->current_picture_ptr->quality=
  2313. s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
  2314. if (s->current_picture.quality < 0)
  2315. return -1;
  2316. }
  2317. if(s->adaptive_quant){
  2318. switch(s->codec_id){
  2319. case CODEC_ID_MPEG4:
  2320. if (CONFIG_MPEG4_ENCODER)
  2321. ff_clean_mpeg4_qscales(s);
  2322. break;
  2323. case CODEC_ID_H263:
  2324. case CODEC_ID_H263P:
  2325. case CODEC_ID_FLV1:
  2326. if (CONFIG_H263_ENCODER)
  2327. ff_clean_h263_qscales(s);
  2328. break;
  2329. }
  2330. s->lambda= s->lambda_table[0];
  2331. //FIXME broken
  2332. }else
  2333. s->lambda= s->current_picture.quality;
  2334. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  2335. update_qscale(s);
  2336. return 0;
  2337. }
  2338. /* must be called before writing the header */
  2339. static void set_frame_distances(MpegEncContext * s){
  2340. assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
  2341. s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
  2342. if(s->pict_type==FF_B_TYPE){
  2343. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  2344. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  2345. }else{
  2346. s->pp_time= s->time - s->last_non_b_time;
  2347. s->last_non_b_time= s->time;
  2348. assert(s->picture_number==0 || s->pp_time > 0);
  2349. }
  2350. }
  2351. static int encode_picture(MpegEncContext *s, int picture_number)
  2352. {
  2353. int i;
  2354. int bits;
  2355. s->picture_number = picture_number;
  2356. /* Reset the average MB variance */
  2357. s->me.mb_var_sum_temp =
  2358. s->me.mc_mb_var_sum_temp = 0;
  2359. /* we need to initialize some time vars before we can encode b-frames */
  2360. // RAL: Condition added for MPEG1VIDEO
  2361. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->h263_msmpeg4))
  2362. set_frame_distances(s);
  2363. if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
  2364. ff_set_mpeg4_time(s);
  2365. s->me.scene_change_score=0;
  2366. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  2367. if(s->pict_type==FF_I_TYPE){
  2368. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2369. else s->no_rounding=0;
  2370. }else if(s->pict_type!=FF_B_TYPE){
  2371. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2372. s->no_rounding ^= 1;
  2373. }
  2374. if(s->flags & CODEC_FLAG_PASS2){
  2375. if (estimate_qp(s,1) < 0)
  2376. return -1;
  2377. ff_get_2pass_fcode(s);
  2378. }else if(!(s->flags & CODEC_FLAG_QSCALE)){
  2379. if(s->pict_type==FF_B_TYPE)
  2380. s->lambda= s->last_lambda_for[s->pict_type];
  2381. else
  2382. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  2383. update_qscale(s);
  2384. }
  2385. s->mb_intra=0; //for the rate distortion & bit compare functions
  2386. for(i=1; i<s->avctx->thread_count; i++){
  2387. ff_update_duplicate_context(s->thread_context[i], s);
  2388. }
  2389. if(ff_init_me(s)<0)
  2390. return -1;
  2391. /* Estimate motion for every MB */
  2392. if(s->pict_type != FF_I_TYPE){
  2393. s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  2394. s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  2395. if(s->pict_type != FF_B_TYPE && s->avctx->me_threshold==0){
  2396. if((s->avctx->pre_me && s->last_non_b_pict_type==FF_I_TYPE) || s->avctx->pre_me==2){
  2397. s->avctx->execute(s->avctx, pre_estimate_motion_thread, (void**)&(s->thread_context[0]), NULL, s->avctx->thread_count, sizeof(void*));
  2398. }
  2399. }
  2400. s->avctx->execute(s->avctx, estimate_motion_thread, (void**)&(s->thread_context[0]), NULL, s->avctx->thread_count, sizeof(void*));
  2401. }else /* if(s->pict_type == FF_I_TYPE) */{
  2402. /* I-Frame */
  2403. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2404. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2405. if(!s->fixed_qscale){
  2406. /* finding spatial complexity for I-frame rate control */
  2407. s->avctx->execute(s->avctx, mb_var_thread, (void**)&(s->thread_context[0]), NULL, s->avctx->thread_count, sizeof(void*));
  2408. }
  2409. }
  2410. for(i=1; i<s->avctx->thread_count; i++){
  2411. merge_context_after_me(s, s->thread_context[i]);
  2412. }
  2413. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  2414. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  2415. emms_c();
  2416. if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == FF_P_TYPE){
  2417. s->pict_type= FF_I_TYPE;
  2418. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2419. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2420. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2421. }
  2422. if(!s->umvplus){
  2423. if(s->pict_type==FF_P_TYPE || s->pict_type==FF_S_TYPE) {
  2424. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  2425. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2426. int a,b;
  2427. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  2428. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  2429. s->f_code= FFMAX3(s->f_code, a, b);
  2430. }
  2431. ff_fix_long_p_mvs(s);
  2432. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  2433. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2434. int j;
  2435. for(i=0; i<2; i++){
  2436. for(j=0; j<2; j++)
  2437. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  2438. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  2439. }
  2440. }
  2441. }
  2442. if(s->pict_type==FF_B_TYPE){
  2443. int a, b;
  2444. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  2445. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2446. s->f_code = FFMAX(a, b);
  2447. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  2448. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2449. s->b_code = FFMAX(a, b);
  2450. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  2451. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  2452. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2453. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2454. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2455. int dir, j;
  2456. for(dir=0; dir<2; dir++){
  2457. for(i=0; i<2; i++){
  2458. for(j=0; j<2; j++){
  2459. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  2460. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  2461. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  2462. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  2463. }
  2464. }
  2465. }
  2466. }
  2467. }
  2468. }
  2469. if (estimate_qp(s, 0) < 0)
  2470. return -1;
  2471. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==FF_I_TYPE && !(s->flags & CODEC_FLAG_QSCALE))
  2472. s->qscale= 3; //reduce clipping problems
  2473. if (s->out_format == FMT_MJPEG) {
  2474. /* for mjpeg, we do include qscale in the matrix */
  2475. s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
  2476. for(i=1;i<64;i++){
  2477. int j= s->dsp.idct_permutation[i];
  2478. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  2479. }
  2480. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2481. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2482. s->qscale= 8;
  2483. }
  2484. //FIXME var duplication
  2485. s->current_picture_ptr->key_frame=
  2486. s->current_picture.key_frame= s->pict_type == FF_I_TYPE; //FIXME pic_ptr
  2487. s->current_picture_ptr->pict_type=
  2488. s->current_picture.pict_type= s->pict_type;
  2489. if(s->current_picture.key_frame)
  2490. s->picture_in_gop_number=0;
  2491. s->last_bits= put_bits_count(&s->pb);
  2492. switch(s->out_format) {
  2493. case FMT_MJPEG:
  2494. if (CONFIG_MJPEG_ENCODER)
  2495. ff_mjpeg_encode_picture_header(s);
  2496. break;
  2497. case FMT_H261:
  2498. if (CONFIG_H261_ENCODER)
  2499. ff_h261_encode_picture_header(s, picture_number);
  2500. break;
  2501. case FMT_H263:
  2502. if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
  2503. ff_wmv2_encode_picture_header(s, picture_number);
  2504. else if (CONFIG_MSMPEG4_ENCODER && s->h263_msmpeg4)
  2505. msmpeg4_encode_picture_header(s, picture_number);
  2506. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  2507. mpeg4_encode_picture_header(s, picture_number);
  2508. else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
  2509. rv10_encode_picture_header(s, picture_number);
  2510. else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
  2511. rv20_encode_picture_header(s, picture_number);
  2512. else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
  2513. ff_flv_encode_picture_header(s, picture_number);
  2514. else if (CONFIG_ANY_H263_ENCODER)
  2515. h263_encode_picture_header(s, picture_number);
  2516. break;
  2517. case FMT_MPEG1:
  2518. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2519. mpeg1_encode_picture_header(s, picture_number);
  2520. break;
  2521. case FMT_H264:
  2522. break;
  2523. default:
  2524. assert(0);
  2525. }
  2526. bits= put_bits_count(&s->pb);
  2527. s->header_bits= bits - s->last_bits;
  2528. for(i=1; i<s->avctx->thread_count; i++){
  2529. update_duplicate_context_after_me(s->thread_context[i], s);
  2530. }
  2531. s->avctx->execute(s->avctx, encode_thread, (void**)&(s->thread_context[0]), NULL, s->avctx->thread_count, sizeof(void*));
  2532. for(i=1; i<s->avctx->thread_count; i++){
  2533. merge_context_after_encode(s, s->thread_context[i]);
  2534. }
  2535. emms_c();
  2536. return 0;
  2537. }
  2538. void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
  2539. const int intra= s->mb_intra;
  2540. int i;
  2541. s->dct_count[intra]++;
  2542. for(i=0; i<64; i++){
  2543. int level= block[i];
  2544. if(level){
  2545. if(level>0){
  2546. s->dct_error_sum[intra][i] += level;
  2547. level -= s->dct_offset[intra][i];
  2548. if(level<0) level=0;
  2549. }else{
  2550. s->dct_error_sum[intra][i] -= level;
  2551. level += s->dct_offset[intra][i];
  2552. if(level>0) level=0;
  2553. }
  2554. block[i]= level;
  2555. }
  2556. }
  2557. }
  2558. int dct_quantize_trellis_c(MpegEncContext *s,
  2559. DCTELEM *block, int n,
  2560. int qscale, int *overflow){
  2561. const int *qmat;
  2562. const uint8_t *scantable= s->intra_scantable.scantable;
  2563. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2564. int max=0;
  2565. unsigned int threshold1, threshold2;
  2566. int bias=0;
  2567. int run_tab[65];
  2568. int level_tab[65];
  2569. int score_tab[65];
  2570. int survivor[65];
  2571. int survivor_count;
  2572. int last_run=0;
  2573. int last_level=0;
  2574. int last_score= 0;
  2575. int last_i;
  2576. int coeff[2][64];
  2577. int coeff_count[64];
  2578. int qmul, qadd, start_i, last_non_zero, i, dc;
  2579. const int esc_length= s->ac_esc_length;
  2580. uint8_t * length;
  2581. uint8_t * last_length;
  2582. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  2583. s->dsp.fdct (block);
  2584. if(s->dct_error_sum)
  2585. s->denoise_dct(s, block);
  2586. qmul= qscale*16;
  2587. qadd= ((qscale-1)|1)*8;
  2588. if (s->mb_intra) {
  2589. int q;
  2590. if (!s->h263_aic) {
  2591. if (n < 4)
  2592. q = s->y_dc_scale;
  2593. else
  2594. q = s->c_dc_scale;
  2595. q = q << 3;
  2596. } else{
  2597. /* For AIC we skip quant/dequant of INTRADC */
  2598. q = 1 << 3;
  2599. qadd=0;
  2600. }
  2601. /* note: block[0] is assumed to be positive */
  2602. block[0] = (block[0] + (q >> 1)) / q;
  2603. start_i = 1;
  2604. last_non_zero = 0;
  2605. qmat = s->q_intra_matrix[qscale];
  2606. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2607. bias= 1<<(QMAT_SHIFT-1);
  2608. length = s->intra_ac_vlc_length;
  2609. last_length= s->intra_ac_vlc_last_length;
  2610. } else {
  2611. start_i = 0;
  2612. last_non_zero = -1;
  2613. qmat = s->q_inter_matrix[qscale];
  2614. length = s->inter_ac_vlc_length;
  2615. last_length= s->inter_ac_vlc_last_length;
  2616. }
  2617. last_i= start_i;
  2618. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  2619. threshold2= (threshold1<<1);
  2620. for(i=63; i>=start_i; i--) {
  2621. const int j = scantable[i];
  2622. int level = block[j] * qmat[j];
  2623. if(((unsigned)(level+threshold1))>threshold2){
  2624. last_non_zero = i;
  2625. break;
  2626. }
  2627. }
  2628. for(i=start_i; i<=last_non_zero; i++) {
  2629. const int j = scantable[i];
  2630. int level = block[j] * qmat[j];
  2631. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  2632. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  2633. if(((unsigned)(level+threshold1))>threshold2){
  2634. if(level>0){
  2635. level= (bias + level)>>QMAT_SHIFT;
  2636. coeff[0][i]= level;
  2637. coeff[1][i]= level-1;
  2638. // coeff[2][k]= level-2;
  2639. }else{
  2640. level= (bias - level)>>QMAT_SHIFT;
  2641. coeff[0][i]= -level;
  2642. coeff[1][i]= -level+1;
  2643. // coeff[2][k]= -level+2;
  2644. }
  2645. coeff_count[i]= FFMIN(level, 2);
  2646. assert(coeff_count[i]);
  2647. max |=level;
  2648. }else{
  2649. coeff[0][i]= (level>>31)|1;
  2650. coeff_count[i]= 1;
  2651. }
  2652. }
  2653. *overflow= s->max_qcoeff < max; //overflow might have happened
  2654. if(last_non_zero < start_i){
  2655. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2656. return last_non_zero;
  2657. }
  2658. score_tab[start_i]= 0;
  2659. survivor[0]= start_i;
  2660. survivor_count= 1;
  2661. for(i=start_i; i<=last_non_zero; i++){
  2662. int level_index, j, zero_distortion;
  2663. int dct_coeff= FFABS(block[ scantable[i] ]);
  2664. int best_score=256*256*256*120;
  2665. if ( s->dsp.fdct == fdct_ifast
  2666. #ifndef FAAN_POSTSCALE
  2667. || s->dsp.fdct == ff_faandct
  2668. #endif
  2669. )
  2670. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  2671. zero_distortion= dct_coeff*dct_coeff;
  2672. for(level_index=0; level_index < coeff_count[i]; level_index++){
  2673. int distortion;
  2674. int level= coeff[level_index][i];
  2675. const int alevel= FFABS(level);
  2676. int unquant_coeff;
  2677. assert(level);
  2678. if(s->out_format == FMT_H263){
  2679. unquant_coeff= alevel*qmul + qadd;
  2680. }else{ //MPEG1
  2681. j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
  2682. if(s->mb_intra){
  2683. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  2684. unquant_coeff = (unquant_coeff - 1) | 1;
  2685. }else{
  2686. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  2687. unquant_coeff = (unquant_coeff - 1) | 1;
  2688. }
  2689. unquant_coeff<<= 3;
  2690. }
  2691. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  2692. level+=64;
  2693. if((level&(~127)) == 0){
  2694. for(j=survivor_count-1; j>=0; j--){
  2695. int run= i - survivor[j];
  2696. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2697. score += score_tab[i-run];
  2698. if(score < best_score){
  2699. best_score= score;
  2700. run_tab[i+1]= run;
  2701. level_tab[i+1]= level-64;
  2702. }
  2703. }
  2704. if(s->out_format == FMT_H263){
  2705. for(j=survivor_count-1; j>=0; j--){
  2706. int run= i - survivor[j];
  2707. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2708. score += score_tab[i-run];
  2709. if(score < last_score){
  2710. last_score= score;
  2711. last_run= run;
  2712. last_level= level-64;
  2713. last_i= i+1;
  2714. }
  2715. }
  2716. }
  2717. }else{
  2718. distortion += esc_length*lambda;
  2719. for(j=survivor_count-1; j>=0; j--){
  2720. int run= i - survivor[j];
  2721. int score= distortion + score_tab[i-run];
  2722. if(score < best_score){
  2723. best_score= score;
  2724. run_tab[i+1]= run;
  2725. level_tab[i+1]= level-64;
  2726. }
  2727. }
  2728. if(s->out_format == FMT_H263){
  2729. for(j=survivor_count-1; j>=0; j--){
  2730. int run= i - survivor[j];
  2731. int score= distortion + score_tab[i-run];
  2732. if(score < last_score){
  2733. last_score= score;
  2734. last_run= run;
  2735. last_level= level-64;
  2736. last_i= i+1;
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. score_tab[i+1]= best_score;
  2743. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  2744. if(last_non_zero <= 27){
  2745. for(; survivor_count; survivor_count--){
  2746. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  2747. break;
  2748. }
  2749. }else{
  2750. for(; survivor_count; survivor_count--){
  2751. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  2752. break;
  2753. }
  2754. }
  2755. survivor[ survivor_count++ ]= i+1;
  2756. }
  2757. if(s->out_format != FMT_H263){
  2758. last_score= 256*256*256*120;
  2759. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  2760. int score= score_tab[i];
  2761. if(i) score += lambda*2; //FIXME exacter?
  2762. if(score < last_score){
  2763. last_score= score;
  2764. last_i= i;
  2765. last_level= level_tab[i];
  2766. last_run= run_tab[i];
  2767. }
  2768. }
  2769. }
  2770. s->coded_score[n] = last_score;
  2771. dc= FFABS(block[0]);
  2772. last_non_zero= last_i - 1;
  2773. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2774. if(last_non_zero < start_i)
  2775. return last_non_zero;
  2776. if(last_non_zero == 0 && start_i == 0){
  2777. int best_level= 0;
  2778. int best_score= dc * dc;
  2779. for(i=0; i<coeff_count[0]; i++){
  2780. int level= coeff[i][0];
  2781. int alevel= FFABS(level);
  2782. int unquant_coeff, score, distortion;
  2783. if(s->out_format == FMT_H263){
  2784. unquant_coeff= (alevel*qmul + qadd)>>3;
  2785. }else{ //MPEG1
  2786. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  2787. unquant_coeff = (unquant_coeff - 1) | 1;
  2788. }
  2789. unquant_coeff = (unquant_coeff + 4) >> 3;
  2790. unquant_coeff<<= 3 + 3;
  2791. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  2792. level+=64;
  2793. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  2794. else score= distortion + esc_length*lambda;
  2795. if(score < best_score){
  2796. best_score= score;
  2797. best_level= level - 64;
  2798. }
  2799. }
  2800. block[0]= best_level;
  2801. s->coded_score[n] = best_score - dc*dc;
  2802. if(best_level == 0) return -1;
  2803. else return last_non_zero;
  2804. }
  2805. i= last_i;
  2806. assert(last_level);
  2807. block[ perm_scantable[last_non_zero] ]= last_level;
  2808. i -= last_run + 1;
  2809. for(; i>start_i; i -= run_tab[i] + 1){
  2810. block[ perm_scantable[i-1] ]= level_tab[i];
  2811. }
  2812. return last_non_zero;
  2813. }
  2814. //#define REFINE_STATS 1
  2815. static int16_t basis[64][64];
  2816. static void build_basis(uint8_t *perm){
  2817. int i, j, x, y;
  2818. emms_c();
  2819. for(i=0; i<8; i++){
  2820. for(j=0; j<8; j++){
  2821. for(y=0; y<8; y++){
  2822. for(x=0; x<8; x++){
  2823. double s= 0.25*(1<<BASIS_SHIFT);
  2824. int index= 8*i + j;
  2825. int perm_index= perm[index];
  2826. if(i==0) s*= sqrt(0.5);
  2827. if(j==0) s*= sqrt(0.5);
  2828. 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)));
  2829. }
  2830. }
  2831. }
  2832. }
  2833. }
  2834. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  2835. DCTELEM *block, int16_t *weight, DCTELEM *orig,
  2836. int n, int qscale){
  2837. int16_t rem[64];
  2838. DECLARE_ALIGNED_16(DCTELEM, d1[64]);
  2839. const uint8_t *scantable= s->intra_scantable.scantable;
  2840. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2841. // unsigned int threshold1, threshold2;
  2842. // int bias=0;
  2843. int run_tab[65];
  2844. int prev_run=0;
  2845. int prev_level=0;
  2846. int qmul, qadd, start_i, last_non_zero, i, dc;
  2847. uint8_t * length;
  2848. uint8_t * last_length;
  2849. int lambda;
  2850. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  2851. #ifdef REFINE_STATS
  2852. static int count=0;
  2853. static int after_last=0;
  2854. static int to_zero=0;
  2855. static int from_zero=0;
  2856. static int raise=0;
  2857. static int lower=0;
  2858. static int messed_sign=0;
  2859. #endif
  2860. if(basis[0][0] == 0)
  2861. build_basis(s->dsp.idct_permutation);
  2862. qmul= qscale*2;
  2863. qadd= (qscale-1)|1;
  2864. if (s->mb_intra) {
  2865. if (!s->h263_aic) {
  2866. if (n < 4)
  2867. q = s->y_dc_scale;
  2868. else
  2869. q = s->c_dc_scale;
  2870. } else{
  2871. /* For AIC we skip quant/dequant of INTRADC */
  2872. q = 1;
  2873. qadd=0;
  2874. }
  2875. q <<= RECON_SHIFT-3;
  2876. /* note: block[0] is assumed to be positive */
  2877. dc= block[0]*q;
  2878. // block[0] = (block[0] + (q >> 1)) / q;
  2879. start_i = 1;
  2880. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2881. // bias= 1<<(QMAT_SHIFT-1);
  2882. length = s->intra_ac_vlc_length;
  2883. last_length= s->intra_ac_vlc_last_length;
  2884. } else {
  2885. dc= 0;
  2886. start_i = 0;
  2887. length = s->inter_ac_vlc_length;
  2888. last_length= s->inter_ac_vlc_last_length;
  2889. }
  2890. last_non_zero = s->block_last_index[n];
  2891. #ifdef REFINE_STATS
  2892. {START_TIMER
  2893. #endif
  2894. dc += (1<<(RECON_SHIFT-1));
  2895. for(i=0; i<64; i++){
  2896. rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
  2897. }
  2898. #ifdef REFINE_STATS
  2899. STOP_TIMER("memset rem[]")}
  2900. #endif
  2901. sum=0;
  2902. for(i=0; i<64; i++){
  2903. int one= 36;
  2904. int qns=4;
  2905. int w;
  2906. w= FFABS(weight[i]) + qns*one;
  2907. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  2908. weight[i] = w;
  2909. // w=weight[i] = (63*qns + (w/2)) / w;
  2910. assert(w>0);
  2911. assert(w<(1<<6));
  2912. sum += w*w;
  2913. }
  2914. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  2915. #ifdef REFINE_STATS
  2916. {START_TIMER
  2917. #endif
  2918. run=0;
  2919. rle_index=0;
  2920. for(i=start_i; i<=last_non_zero; i++){
  2921. int j= perm_scantable[i];
  2922. const int level= block[j];
  2923. int coeff;
  2924. if(level){
  2925. if(level<0) coeff= qmul*level - qadd;
  2926. else coeff= qmul*level + qadd;
  2927. run_tab[rle_index++]=run;
  2928. run=0;
  2929. s->dsp.add_8x8basis(rem, basis[j], coeff);
  2930. }else{
  2931. run++;
  2932. }
  2933. }
  2934. #ifdef REFINE_STATS
  2935. if(last_non_zero>0){
  2936. STOP_TIMER("init rem[]")
  2937. }
  2938. }
  2939. {START_TIMER
  2940. #endif
  2941. for(;;){
  2942. int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
  2943. int best_coeff=0;
  2944. int best_change=0;
  2945. int run2, best_unquant_change=0, analyze_gradient;
  2946. #ifdef REFINE_STATS
  2947. {START_TIMER
  2948. #endif
  2949. analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
  2950. if(analyze_gradient){
  2951. #ifdef REFINE_STATS
  2952. {START_TIMER
  2953. #endif
  2954. for(i=0; i<64; i++){
  2955. int w= weight[i];
  2956. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  2957. }
  2958. #ifdef REFINE_STATS
  2959. STOP_TIMER("rem*w*w")}
  2960. {START_TIMER
  2961. #endif
  2962. s->dsp.fdct(d1);
  2963. #ifdef REFINE_STATS
  2964. STOP_TIMER("dct")}
  2965. #endif
  2966. }
  2967. if(start_i){
  2968. const int level= block[0];
  2969. int change, old_coeff;
  2970. assert(s->mb_intra);
  2971. old_coeff= q*level;
  2972. for(change=-1; change<=1; change+=2){
  2973. int new_level= level + change;
  2974. int score, new_coeff;
  2975. new_coeff= q*new_level;
  2976. if(new_coeff >= 2048 || new_coeff < 0)
  2977. continue;
  2978. score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
  2979. if(score<best_score){
  2980. best_score= score;
  2981. best_coeff= 0;
  2982. best_change= change;
  2983. best_unquant_change= new_coeff - old_coeff;
  2984. }
  2985. }
  2986. }
  2987. run=0;
  2988. rle_index=0;
  2989. run2= run_tab[rle_index++];
  2990. prev_level=0;
  2991. prev_run=0;
  2992. for(i=start_i; i<64; i++){
  2993. int j= perm_scantable[i];
  2994. const int level= block[j];
  2995. int change, old_coeff;
  2996. if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  2997. break;
  2998. if(level){
  2999. if(level<0) old_coeff= qmul*level - qadd;
  3000. else old_coeff= qmul*level + qadd;
  3001. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3002. }else{
  3003. old_coeff=0;
  3004. run2--;
  3005. assert(run2>=0 || i >= last_non_zero );
  3006. }
  3007. for(change=-1; change<=1; change+=2){
  3008. int new_level= level + change;
  3009. int score, new_coeff, unquant_change;
  3010. score=0;
  3011. if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3012. continue;
  3013. if(new_level){
  3014. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3015. else new_coeff= qmul*new_level + qadd;
  3016. if(new_coeff >= 2048 || new_coeff <= -2048)
  3017. continue;
  3018. //FIXME check for overflow
  3019. if(level){
  3020. if(level < 63 && level > -63){
  3021. if(i < last_non_zero)
  3022. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3023. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3024. else
  3025. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3026. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3027. }
  3028. }else{
  3029. assert(FFABS(new_level)==1);
  3030. if(analyze_gradient){
  3031. int g= d1[ scantable[i] ];
  3032. if(g && (g^new_level) >= 0)
  3033. continue;
  3034. }
  3035. if(i < last_non_zero){
  3036. int next_i= i + run2 + 1;
  3037. int next_level= block[ perm_scantable[next_i] ] + 64;
  3038. if(next_level&(~127))
  3039. next_level= 0;
  3040. if(next_i < last_non_zero)
  3041. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3042. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3043. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3044. else
  3045. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3046. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3047. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3048. }else{
  3049. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3050. if(prev_level){
  3051. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3052. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3053. }
  3054. }
  3055. }
  3056. }else{
  3057. new_coeff=0;
  3058. assert(FFABS(level)==1);
  3059. if(i < last_non_zero){
  3060. int next_i= i + run2 + 1;
  3061. int next_level= block[ perm_scantable[next_i] ] + 64;
  3062. if(next_level&(~127))
  3063. next_level= 0;
  3064. if(next_i < last_non_zero)
  3065. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3066. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3067. - length[UNI_AC_ENC_INDEX(run, 65)];
  3068. else
  3069. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3070. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3071. - length[UNI_AC_ENC_INDEX(run, 65)];
  3072. }else{
  3073. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3074. if(prev_level){
  3075. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3076. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3077. }
  3078. }
  3079. }
  3080. score *= lambda;
  3081. unquant_change= new_coeff - old_coeff;
  3082. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3083. score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
  3084. if(score<best_score){
  3085. best_score= score;
  3086. best_coeff= i;
  3087. best_change= change;
  3088. best_unquant_change= unquant_change;
  3089. }
  3090. }
  3091. if(level){
  3092. prev_level= level + 64;
  3093. if(prev_level&(~127))
  3094. prev_level= 0;
  3095. prev_run= run;
  3096. run=0;
  3097. }else{
  3098. run++;
  3099. }
  3100. }
  3101. #ifdef REFINE_STATS
  3102. STOP_TIMER("iterative step")}
  3103. #endif
  3104. if(best_change){
  3105. int j= perm_scantable[ best_coeff ];
  3106. block[j] += best_change;
  3107. if(best_coeff > last_non_zero){
  3108. last_non_zero= best_coeff;
  3109. assert(block[j]);
  3110. #ifdef REFINE_STATS
  3111. after_last++;
  3112. #endif
  3113. }else{
  3114. #ifdef REFINE_STATS
  3115. if(block[j]){
  3116. if(block[j] - best_change){
  3117. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3118. raise++;
  3119. }else{
  3120. lower++;
  3121. }
  3122. }else{
  3123. from_zero++;
  3124. }
  3125. }else{
  3126. to_zero++;
  3127. }
  3128. #endif
  3129. for(; last_non_zero>=start_i; last_non_zero--){
  3130. if(block[perm_scantable[last_non_zero]])
  3131. break;
  3132. }
  3133. }
  3134. #ifdef REFINE_STATS
  3135. count++;
  3136. if(256*256*256*64 % count == 0){
  3137. 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);
  3138. }
  3139. #endif
  3140. run=0;
  3141. rle_index=0;
  3142. for(i=start_i; i<=last_non_zero; i++){
  3143. int j= perm_scantable[i];
  3144. const int level= block[j];
  3145. if(level){
  3146. run_tab[rle_index++]=run;
  3147. run=0;
  3148. }else{
  3149. run++;
  3150. }
  3151. }
  3152. s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3153. }else{
  3154. break;
  3155. }
  3156. }
  3157. #ifdef REFINE_STATS
  3158. if(last_non_zero>0){
  3159. STOP_TIMER("iterative search")
  3160. }
  3161. }
  3162. #endif
  3163. return last_non_zero;
  3164. }
  3165. int dct_quantize_c(MpegEncContext *s,
  3166. DCTELEM *block, int n,
  3167. int qscale, int *overflow)
  3168. {
  3169. int i, j, level, last_non_zero, q, start_i;
  3170. const int *qmat;
  3171. const uint8_t *scantable= s->intra_scantable.scantable;
  3172. int bias;
  3173. int max=0;
  3174. unsigned int threshold1, threshold2;
  3175. s->dsp.fdct (block);
  3176. if(s->dct_error_sum)
  3177. s->denoise_dct(s, block);
  3178. if (s->mb_intra) {
  3179. if (!s->h263_aic) {
  3180. if (n < 4)
  3181. q = s->y_dc_scale;
  3182. else
  3183. q = s->c_dc_scale;
  3184. q = q << 3;
  3185. } else
  3186. /* For AIC we skip quant/dequant of INTRADC */
  3187. q = 1 << 3;
  3188. /* note: block[0] is assumed to be positive */
  3189. block[0] = (block[0] + (q >> 1)) / q;
  3190. start_i = 1;
  3191. last_non_zero = 0;
  3192. qmat = s->q_intra_matrix[qscale];
  3193. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3194. } else {
  3195. start_i = 0;
  3196. last_non_zero = -1;
  3197. qmat = s->q_inter_matrix[qscale];
  3198. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3199. }
  3200. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3201. threshold2= (threshold1<<1);
  3202. for(i=63;i>=start_i;i--) {
  3203. j = scantable[i];
  3204. level = block[j] * qmat[j];
  3205. if(((unsigned)(level+threshold1))>threshold2){
  3206. last_non_zero = i;
  3207. break;
  3208. }else{
  3209. block[j]=0;
  3210. }
  3211. }
  3212. for(i=start_i; i<=last_non_zero; i++) {
  3213. j = scantable[i];
  3214. level = block[j] * qmat[j];
  3215. // if( bias+level >= (1<<QMAT_SHIFT)
  3216. // || bias-level >= (1<<QMAT_SHIFT)){
  3217. if(((unsigned)(level+threshold1))>threshold2){
  3218. if(level>0){
  3219. level= (bias + level)>>QMAT_SHIFT;
  3220. block[j]= level;
  3221. }else{
  3222. level= (bias - level)>>QMAT_SHIFT;
  3223. block[j]= -level;
  3224. }
  3225. max |=level;
  3226. }else{
  3227. block[j]=0;
  3228. }
  3229. }
  3230. *overflow= s->max_qcoeff < max; //overflow might have happened
  3231. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3232. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3233. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3234. return last_non_zero;
  3235. }
  3236. AVCodec h263_encoder = {
  3237. "h263",
  3238. CODEC_TYPE_VIDEO,
  3239. CODEC_ID_H263,
  3240. sizeof(MpegEncContext),
  3241. MPV_encode_init,
  3242. MPV_encode_picture,
  3243. MPV_encode_end,
  3244. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3245. .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3246. };
  3247. AVCodec h263p_encoder = {
  3248. "h263p",
  3249. CODEC_TYPE_VIDEO,
  3250. CODEC_ID_H263P,
  3251. sizeof(MpegEncContext),
  3252. MPV_encode_init,
  3253. MPV_encode_picture,
  3254. MPV_encode_end,
  3255. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3256. .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  3257. };
  3258. AVCodec flv_encoder = {
  3259. "flv",
  3260. CODEC_TYPE_VIDEO,
  3261. CODEC_ID_FLV1,
  3262. sizeof(MpegEncContext),
  3263. MPV_encode_init,
  3264. MPV_encode_picture,
  3265. MPV_encode_end,
  3266. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3267. .long_name= NULL_IF_CONFIG_SMALL("Flash Video (FLV)"),
  3268. };
  3269. AVCodec mpeg4_encoder = {
  3270. "mpeg4",
  3271. CODEC_TYPE_VIDEO,
  3272. CODEC_ID_MPEG4,
  3273. sizeof(MpegEncContext),
  3274. MPV_encode_init,
  3275. MPV_encode_picture,
  3276. MPV_encode_end,
  3277. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3278. .capabilities= CODEC_CAP_DELAY,
  3279. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
  3280. };
  3281. AVCodec msmpeg4v1_encoder = {
  3282. "msmpeg4v1",
  3283. CODEC_TYPE_VIDEO,
  3284. CODEC_ID_MSMPEG4V1,
  3285. sizeof(MpegEncContext),
  3286. MPV_encode_init,
  3287. MPV_encode_picture,
  3288. MPV_encode_end,
  3289. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3290. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 1"),
  3291. };
  3292. AVCodec msmpeg4v2_encoder = {
  3293. "msmpeg4v2",
  3294. CODEC_TYPE_VIDEO,
  3295. CODEC_ID_MSMPEG4V2,
  3296. sizeof(MpegEncContext),
  3297. MPV_encode_init,
  3298. MPV_encode_picture,
  3299. MPV_encode_end,
  3300. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3301. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  3302. };
  3303. AVCodec msmpeg4v3_encoder = {
  3304. "msmpeg4",
  3305. CODEC_TYPE_VIDEO,
  3306. CODEC_ID_MSMPEG4V3,
  3307. sizeof(MpegEncContext),
  3308. MPV_encode_init,
  3309. MPV_encode_picture,
  3310. MPV_encode_end,
  3311. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3312. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  3313. };
  3314. AVCodec wmv1_encoder = {
  3315. "wmv1",
  3316. CODEC_TYPE_VIDEO,
  3317. CODEC_ID_WMV1,
  3318. sizeof(MpegEncContext),
  3319. MPV_encode_init,
  3320. MPV_encode_picture,
  3321. MPV_encode_end,
  3322. .pix_fmts= (enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3323. .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  3324. };