snowenc.c 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149
  1. /*
  2. * Copyright (C) 2004 Michael Niedermayer <michaelni@gmx.at>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "libavutil/emms.h"
  21. #include "libavutil/intmath.h"
  22. #include "libavutil/libm.h"
  23. #include "libavutil/log.h"
  24. #include "libavutil/mem.h"
  25. #include "libavutil/opt.h"
  26. #include "libavutil/pixdesc.h"
  27. #include "avcodec.h"
  28. #include "codec_internal.h"
  29. #include "encode.h"
  30. #include "internal.h" //For AVCodecInternal.recon_frame
  31. #include "me_cmp.h"
  32. #include "packet_internal.h"
  33. #include "qpeldsp.h"
  34. #include "snow_dwt.h"
  35. #include "snow.h"
  36. #include "rangecoder.h"
  37. #include "mathops.h"
  38. #include "mpegvideo.h"
  39. #include "h263enc.h"
  40. #define FF_ME_ITER 3
  41. typedef struct SnowEncContext {
  42. SnowContext com;
  43. QpelDSPContext qdsp;
  44. MpegvideoEncDSPContext mpvencdsp;
  45. int lambda;
  46. int lambda2;
  47. int pass1_rc;
  48. int pred;
  49. int memc_only;
  50. int no_bitstream;
  51. int intra_penalty;
  52. int motion_est;
  53. int iterative_dia_size;
  54. int scenechange_threshold;
  55. MECmpContext mecc;
  56. MpegEncContext m; // needed for motion estimation, should not be used for anything else, the idea is to eventually make the motion estimation independent of MpegEncContext, so this will be removed then (FIXME/XXX)
  57. MPVPicture cur_pic, last_pic;
  58. #define ME_CACHE_SIZE 1024
  59. unsigned me_cache[ME_CACHE_SIZE];
  60. unsigned me_cache_generation;
  61. uint64_t encoding_error[SNOW_MAX_PLANES];
  62. } SnowEncContext;
  63. static void init_ref(MotionEstContext *c, const uint8_t *const src[3],
  64. uint8_t *const ref[3], uint8_t *const ref2[3],
  65. int x, int y, int ref_index)
  66. {
  67. SnowContext *s = c->avctx->priv_data;
  68. const int offset[3] = {
  69. y*c-> stride + x,
  70. ((y*c->uvstride + x) >> s->chroma_h_shift),
  71. ((y*c->uvstride + x) >> s->chroma_h_shift),
  72. };
  73. for (int i = 0; i < 3; i++) {
  74. c->src[0][i] = src [i];
  75. c->ref[0][i] = ref [i] + offset[i];
  76. }
  77. av_assert2(!ref_index);
  78. }
  79. static inline void put_symbol(RangeCoder *c, uint8_t *state, int v, int is_signed)
  80. {
  81. if (v) {
  82. const int a = FFABS(v);
  83. const int e = av_log2(a);
  84. const int el = FFMIN(e, 10);
  85. int i;
  86. put_rac(c, state + 0, 0);
  87. for (i = 0; i < el; i++)
  88. put_rac(c, state + 1 + i, 1); //1..10
  89. for(; i < e; i++)
  90. put_rac(c, state + 1 + 9, 1); //1..10
  91. put_rac(c, state + 1 + FFMIN(i, 9), 0);
  92. for (i = e - 1; i >= el; i--)
  93. put_rac(c, state + 22 + 9, (a >> i) & 1); //22..31
  94. for(; i >= 0; i--)
  95. put_rac(c, state + 22 + i, (a >> i) & 1); //22..31
  96. if (is_signed)
  97. put_rac(c, state + 11 + el, v < 0); //11..21
  98. } else {
  99. put_rac(c, state + 0, 1);
  100. }
  101. }
  102. static inline void put_symbol2(RangeCoder *c, uint8_t *state, int v, int log2)
  103. {
  104. int r = log2 >= 0 ? 1<<log2 : 1;
  105. av_assert2(v >= 0);
  106. av_assert2(log2 >= -4);
  107. while (v >= r) {
  108. put_rac(c, state + 4 + log2, 1);
  109. v -= r;
  110. log2++;
  111. if (log2 > 0) r += r;
  112. }
  113. put_rac(c, state + 4 + log2, 0);
  114. for (int i = log2 - 1; i >= 0; i--)
  115. put_rac(c, state + 31 - i, (v >> i) & 1);
  116. }
  117. static int get_encode_buffer(SnowContext *s, AVFrame *frame)
  118. {
  119. int ret;
  120. frame->width = s->avctx->width + 2 * EDGE_WIDTH;
  121. frame->height = s->avctx->height + 2 * EDGE_WIDTH;
  122. ret = ff_encode_alloc_frame(s->avctx, frame);
  123. if (ret < 0)
  124. return ret;
  125. for (int i = 0; frame->data[i]; i++) {
  126. int offset = (EDGE_WIDTH >> (i ? s->chroma_v_shift : 0)) *
  127. frame->linesize[i] +
  128. (EDGE_WIDTH >> (i ? s->chroma_h_shift : 0));
  129. frame->data[i] += offset;
  130. }
  131. frame->width = s->avctx->width;
  132. frame->height = s->avctx->height;
  133. return 0;
  134. }
  135. static av_cold int encode_init(AVCodecContext *avctx)
  136. {
  137. SnowEncContext *const enc = avctx->priv_data;
  138. SnowContext *const s = &enc->com;
  139. MpegEncContext *const mpv = &enc->m;
  140. int plane_index, ret;
  141. int i;
  142. if (enc->pred == DWT_97
  143. && (avctx->flags & AV_CODEC_FLAG_QSCALE)
  144. && avctx->global_quality == 0){
  145. av_log(avctx, AV_LOG_ERROR, "The 9/7 wavelet is incompatible with lossless mode.\n");
  146. return AVERROR(EINVAL);
  147. }
  148. s->spatial_decomposition_type = enc->pred; //FIXME add decorrelator type r transform_type
  149. s->mv_scale = (avctx->flags & AV_CODEC_FLAG_QPEL) ? 2 : 4;
  150. s->block_max_depth= (avctx->flags & AV_CODEC_FLAG_4MV ) ? 1 : 0;
  151. for(plane_index=0; plane_index<3; plane_index++){
  152. s->plane[plane_index].diag_mc= 1;
  153. s->plane[plane_index].htaps= 6;
  154. s->plane[plane_index].hcoeff[0]= 40;
  155. s->plane[plane_index].hcoeff[1]= -10;
  156. s->plane[plane_index].hcoeff[2]= 2;
  157. s->plane[plane_index].fast_mc= 1;
  158. }
  159. // Must be before ff_snow_common_init()
  160. ff_hpeldsp_init(&s->hdsp, avctx->flags);
  161. if ((ret = ff_snow_common_init(avctx)) < 0) {
  162. return ret;
  163. }
  164. #define mcf(dx,dy)\
  165. enc->qdsp.put_qpel_pixels_tab [0][dy+dx/4]=\
  166. enc->qdsp.put_no_rnd_qpel_pixels_tab[0][dy+dx/4]=\
  167. s->h264qpel.put_h264_qpel_pixels_tab[0][dy+dx/4];\
  168. enc->qdsp.put_qpel_pixels_tab [1][dy+dx/4]=\
  169. enc->qdsp.put_no_rnd_qpel_pixels_tab[1][dy+dx/4]=\
  170. s->h264qpel.put_h264_qpel_pixels_tab[1][dy+dx/4];
  171. mcf( 0, 0)
  172. mcf( 4, 0)
  173. mcf( 8, 0)
  174. mcf(12, 0)
  175. mcf( 0, 4)
  176. mcf( 4, 4)
  177. mcf( 8, 4)
  178. mcf(12, 4)
  179. mcf( 0, 8)
  180. mcf( 4, 8)
  181. mcf( 8, 8)
  182. mcf(12, 8)
  183. mcf( 0,12)
  184. mcf( 4,12)
  185. mcf( 8,12)
  186. mcf(12,12)
  187. ff_me_cmp_init(&enc->mecc, avctx);
  188. ret = ff_me_init(&enc->m.me, avctx, &enc->mecc, 0);
  189. if (ret < 0)
  190. return ret;
  191. ff_mpegvideoencdsp_init(&enc->mpvencdsp, avctx);
  192. ff_snow_alloc_blocks(s);
  193. s->version=0;
  194. mpv->avctx = avctx;
  195. mpv->bit_rate= avctx->bit_rate;
  196. mpv->lmin = avctx->mb_lmin;
  197. mpv->lmax = avctx->mb_lmax;
  198. mpv->mb_num = (avctx->width * avctx->height + 255) / 256; // For ratecontrol
  199. mpv->me.temp =
  200. mpv->me.scratchpad = av_calloc(avctx->width + 64, 2*16*2*sizeof(uint8_t));
  201. mpv->sc.obmc_scratchpad= av_mallocz(MB_SIZE*MB_SIZE*12*sizeof(uint32_t));
  202. mpv->me.map = av_mallocz(2 * ME_MAP_SIZE * sizeof(*mpv->me.map));
  203. if (!mpv->me.scratchpad || !mpv->me.map || !mpv->sc.obmc_scratchpad)
  204. return AVERROR(ENOMEM);
  205. mpv->me.score_map = mpv->me.map + ME_MAP_SIZE;
  206. mpv->me.mv_penalty = ff_h263_get_mv_penalty();
  207. s->max_ref_frames = av_clip(avctx->refs, 1, MAX_REF_FRAMES);
  208. if(avctx->flags&AV_CODEC_FLAG_PASS1){
  209. if(!avctx->stats_out)
  210. avctx->stats_out = av_mallocz(256);
  211. if (!avctx->stats_out)
  212. return AVERROR(ENOMEM);
  213. }
  214. if((avctx->flags&AV_CODEC_FLAG_PASS2) || !(avctx->flags&AV_CODEC_FLAG_QSCALE)){
  215. ret = ff_rate_control_init(mpv);
  216. if(ret < 0)
  217. return ret;
  218. }
  219. enc->pass1_rc = !(avctx->flags & (AV_CODEC_FLAG_QSCALE|AV_CODEC_FLAG_PASS2));
  220. switch(avctx->pix_fmt){
  221. case AV_PIX_FMT_YUV444P:
  222. // case AV_PIX_FMT_YUV422P:
  223. case AV_PIX_FMT_YUV420P:
  224. // case AV_PIX_FMT_YUV411P:
  225. case AV_PIX_FMT_YUV410P:
  226. s->nb_planes = 3;
  227. s->colorspace_type= 0;
  228. break;
  229. case AV_PIX_FMT_GRAY8:
  230. s->nb_planes = 1;
  231. s->colorspace_type = 1;
  232. break;
  233. /* case AV_PIX_FMT_RGB32:
  234. s->colorspace= 1;
  235. break;*/
  236. }
  237. ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift,
  238. &s->chroma_v_shift);
  239. if (ret)
  240. return ret;
  241. s->input_picture = av_frame_alloc();
  242. if (!s->input_picture)
  243. return AVERROR(ENOMEM);
  244. if ((ret = get_encode_buffer(s, s->input_picture)) < 0)
  245. return ret;
  246. if (enc->motion_est == FF_ME_ITER) {
  247. int size= s->b_width * s->b_height << 2*s->block_max_depth;
  248. for(i=0; i<s->max_ref_frames; i++){
  249. s->ref_mvs[i] = av_calloc(size, sizeof(*s->ref_mvs[i]));
  250. s->ref_scores[i] = av_calloc(size, sizeof(*s->ref_scores[i]));
  251. if (!s->ref_mvs[i] || !s->ref_scores[i])
  252. return AVERROR(ENOMEM);
  253. }
  254. }
  255. return 0;
  256. }
  257. //near copy & paste from dsputil, FIXME
  258. static int pix_sum(const uint8_t * pix, int line_size, int w, int h)
  259. {
  260. int s, i, j;
  261. s = 0;
  262. for (i = 0; i < h; i++) {
  263. for (j = 0; j < w; j++) {
  264. s += pix[0];
  265. pix ++;
  266. }
  267. pix += line_size - w;
  268. }
  269. return s;
  270. }
  271. //near copy & paste from dsputil, FIXME
  272. static int pix_norm1(const uint8_t * pix, int line_size, int w)
  273. {
  274. int s, i, j;
  275. const uint32_t *sq = ff_square_tab + 256;
  276. s = 0;
  277. for (i = 0; i < w; i++) {
  278. for (j = 0; j < w; j ++) {
  279. s += sq[pix[0]];
  280. pix ++;
  281. }
  282. pix += line_size - w;
  283. }
  284. return s;
  285. }
  286. static inline int get_penalty_factor(int lambda, int lambda2, int type){
  287. switch(type&0xFF){
  288. default:
  289. case FF_CMP_SAD:
  290. return lambda>>FF_LAMBDA_SHIFT;
  291. case FF_CMP_DCT:
  292. return (3*lambda)>>(FF_LAMBDA_SHIFT+1);
  293. case FF_CMP_W53:
  294. return (4*lambda)>>(FF_LAMBDA_SHIFT);
  295. case FF_CMP_W97:
  296. return (2*lambda)>>(FF_LAMBDA_SHIFT);
  297. case FF_CMP_SATD:
  298. case FF_CMP_DCT264:
  299. return (2*lambda)>>FF_LAMBDA_SHIFT;
  300. case FF_CMP_RD:
  301. case FF_CMP_PSNR:
  302. case FF_CMP_SSE:
  303. case FF_CMP_NSSE:
  304. return lambda2>>FF_LAMBDA_SHIFT;
  305. case FF_CMP_BIT:
  306. return 1;
  307. }
  308. }
  309. //FIXME copy&paste
  310. #define P_LEFT P[1]
  311. #define P_TOP P[2]
  312. #define P_TOPRIGHT P[3]
  313. #define P_MEDIAN P[4]
  314. #define P_MV1 P[9]
  315. #define FLAG_QPEL 1 //must be 1
  316. static int encode_q_branch(SnowEncContext *enc, int level, int x, int y)
  317. {
  318. SnowContext *const s = &enc->com;
  319. MotionEstContext *const c = &enc->m.me;
  320. uint8_t p_buffer[1024];
  321. uint8_t i_buffer[1024];
  322. uint8_t p_state[sizeof(s->block_state)];
  323. uint8_t i_state[sizeof(s->block_state)];
  324. RangeCoder pc, ic;
  325. uint8_t *pbbak= s->c.bytestream;
  326. uint8_t *pbbak_start= s->c.bytestream_start;
  327. int score, score2, iscore, i_len, p_len, block_s, sum, base_bits;
  328. const int w= s->b_width << s->block_max_depth;
  329. const int h= s->b_height << s->block_max_depth;
  330. const int rem_depth= s->block_max_depth - level;
  331. const int index= (x + y*w) << rem_depth;
  332. const int block_w= 1<<(LOG2_MB_SIZE - level);
  333. int trx= (x+1)<<rem_depth;
  334. int try= (y+1)<<rem_depth;
  335. const BlockNode *left = x ? &s->block[index-1] : &null_block;
  336. const BlockNode *top = y ? &s->block[index-w] : &null_block;
  337. const BlockNode *right = trx<w ? &s->block[index+1] : &null_block;
  338. const BlockNode *bottom= try<h ? &s->block[index+w] : &null_block;
  339. const BlockNode *tl = y && x ? &s->block[index-w-1] : left;
  340. const BlockNode *tr = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
  341. int pl = left->color[0];
  342. int pcb= left->color[1];
  343. int pcr= left->color[2];
  344. int pmx, pmy;
  345. int mx=0, my=0;
  346. int l,cr,cb;
  347. const int stride= s->current_picture->linesize[0];
  348. const int uvstride= s->current_picture->linesize[1];
  349. const uint8_t *const current_data[3] = { s->input_picture->data[0] + (x + y* stride)*block_w,
  350. s->input_picture->data[1] + ((x*block_w)>>s->chroma_h_shift) + ((y*uvstride*block_w)>>s->chroma_v_shift),
  351. s->input_picture->data[2] + ((x*block_w)>>s->chroma_h_shift) + ((y*uvstride*block_w)>>s->chroma_v_shift)};
  352. int P[10][2];
  353. int16_t last_mv[3][2];
  354. int qpel= !!(s->avctx->flags & AV_CODEC_FLAG_QPEL); //unused
  355. const int shift= 1+qpel;
  356. int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
  357. int mx_context= av_log2(2*FFABS(left->mx - top->mx));
  358. int my_context= av_log2(2*FFABS(left->my - top->my));
  359. int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
  360. int ref, best_ref, ref_score, ref_mx, ref_my;
  361. int range = MAX_MV >> (1 + qpel);
  362. av_assert0(sizeof(s->block_state) >= 256);
  363. if(s->keyframe){
  364. set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
  365. return 0;
  366. }
  367. // clip predictors / edge ?
  368. P_LEFT[0]= left->mx;
  369. P_LEFT[1]= left->my;
  370. P_TOP [0]= top->mx;
  371. P_TOP [1]= top->my;
  372. P_TOPRIGHT[0]= tr->mx;
  373. P_TOPRIGHT[1]= tr->my;
  374. last_mv[0][0]= s->block[index].mx;
  375. last_mv[0][1]= s->block[index].my;
  376. last_mv[1][0]= right->mx;
  377. last_mv[1][1]= right->my;
  378. last_mv[2][0]= bottom->mx;
  379. last_mv[2][1]= bottom->my;
  380. enc->m.mb_stride = 2;
  381. enc->m.mb_x =
  382. enc->m.mb_y = 0;
  383. c->skip= 0;
  384. av_assert1(c-> stride == stride);
  385. av_assert1(c->uvstride == uvstride);
  386. c->penalty_factor = get_penalty_factor(enc->lambda, enc->lambda2, c->avctx->me_cmp);
  387. c->sub_penalty_factor= get_penalty_factor(enc->lambda, enc->lambda2, c->avctx->me_sub_cmp);
  388. c->mb_penalty_factor = get_penalty_factor(enc->lambda, enc->lambda2, c->avctx->mb_cmp);
  389. c->current_mv_penalty = c->mv_penalty[enc->m.f_code=1] + MAX_DMV;
  390. c->xmin = - x*block_w - 16+3;
  391. c->ymin = - y*block_w - 16+3;
  392. c->xmax = - (x+1)*block_w + (w<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
  393. c->ymax = - (y+1)*block_w + (h<<(LOG2_MB_SIZE - s->block_max_depth)) + 16-3;
  394. c->xmin = FFMAX(c->xmin,-range);
  395. c->xmax = FFMIN(c->xmax, range);
  396. c->ymin = FFMAX(c->ymin,-range);
  397. c->ymax = FFMIN(c->ymax, range);
  398. if(P_LEFT[0] > (c->xmax<<shift)) P_LEFT[0] = (c->xmax<<shift);
  399. if(P_LEFT[1] > (c->ymax<<shift)) P_LEFT[1] = (c->ymax<<shift);
  400. if(P_TOP[0] > (c->xmax<<shift)) P_TOP[0] = (c->xmax<<shift);
  401. if(P_TOP[1] > (c->ymax<<shift)) P_TOP[1] = (c->ymax<<shift);
  402. if(P_TOPRIGHT[0] < (c->xmin * (1<<shift))) P_TOPRIGHT[0]= (c->xmin * (1<<shift));
  403. if(P_TOPRIGHT[0] > (c->xmax<<shift)) P_TOPRIGHT[0]= (c->xmax<<shift); //due to pmx no clip
  404. if(P_TOPRIGHT[1] > (c->ymax<<shift)) P_TOPRIGHT[1]= (c->ymax<<shift);
  405. P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);
  406. P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);
  407. if (!y) {
  408. c->pred_x= P_LEFT[0];
  409. c->pred_y= P_LEFT[1];
  410. } else {
  411. c->pred_x = P_MEDIAN[0];
  412. c->pred_y = P_MEDIAN[1];
  413. }
  414. score= INT_MAX;
  415. best_ref= 0;
  416. for(ref=0; ref<s->ref_frames; ref++){
  417. init_ref(c, current_data, s->last_picture[ref]->data, NULL, block_w*x, block_w*y, 0);
  418. ref_score= ff_epzs_motion_search(&enc->m, &ref_mx, &ref_my, P, 0, /*ref_index*/ 0, last_mv,
  419. (1<<16)>>shift, level-LOG2_MB_SIZE+4, block_w);
  420. av_assert2(ref_mx >= c->xmin);
  421. av_assert2(ref_mx <= c->xmax);
  422. av_assert2(ref_my >= c->ymin);
  423. av_assert2(ref_my <= c->ymax);
  424. ref_score= c->sub_motion_search(&enc->m, &ref_mx, &ref_my, ref_score, 0, 0, level-LOG2_MB_SIZE+4, block_w);
  425. ref_score= ff_get_mb_score(&enc->m, ref_mx, ref_my, 0, 0, level-LOG2_MB_SIZE+4, block_w, 0);
  426. ref_score+= 2*av_log2(2*ref)*c->penalty_factor;
  427. if(s->ref_mvs[ref]){
  428. s->ref_mvs[ref][index][0]= ref_mx;
  429. s->ref_mvs[ref][index][1]= ref_my;
  430. s->ref_scores[ref][index]= ref_score;
  431. }
  432. if(score > ref_score){
  433. score= ref_score;
  434. best_ref= ref;
  435. mx= ref_mx;
  436. my= ref_my;
  437. }
  438. }
  439. //FIXME if mb_cmp != SSE then intra cannot be compared currently and mb_penalty vs. lambda2
  440. // subpel search
  441. base_bits= get_rac_count(&s->c) - 8*(s->c.bytestream - s->c.bytestream_start);
  442. pc= s->c;
  443. pc.bytestream_start=
  444. pc.bytestream= p_buffer; //FIXME end/start? and at the other stoo
  445. memcpy(p_state, s->block_state, sizeof(s->block_state));
  446. if(level!=s->block_max_depth)
  447. put_rac(&pc, &p_state[4 + s_context], 1);
  448. put_rac(&pc, &p_state[1 + left->type + top->type], 0);
  449. if(s->ref_frames > 1)
  450. put_symbol(&pc, &p_state[128 + 1024 + 32*ref_context], best_ref, 0);
  451. pred_mv(s, &pmx, &pmy, best_ref, left, top, tr);
  452. put_symbol(&pc, &p_state[128 + 32*(mx_context + 16*!!best_ref)], mx - pmx, 1);
  453. put_symbol(&pc, &p_state[128 + 32*(my_context + 16*!!best_ref)], my - pmy, 1);
  454. p_len= pc.bytestream - pc.bytestream_start;
  455. score += (enc->lambda2*(get_rac_count(&pc)-base_bits))>>FF_LAMBDA_SHIFT;
  456. block_s= block_w*block_w;
  457. sum = pix_sum(current_data[0], stride, block_w, block_w);
  458. l= (sum + block_s/2)/block_s;
  459. iscore = pix_norm1(current_data[0], stride, block_w) - 2*l*sum + l*l*block_s;
  460. if (s->nb_planes > 2) {
  461. block_s= block_w*block_w>>(s->chroma_h_shift + s->chroma_v_shift);
  462. sum = pix_sum(current_data[1], uvstride, block_w>>s->chroma_h_shift, block_w>>s->chroma_v_shift);
  463. cb= (sum + block_s/2)/block_s;
  464. // iscore += pix_norm1(&current_mb[1][0], uvstride, block_w>>1) - 2*cb*sum + cb*cb*block_s;
  465. sum = pix_sum(current_data[2], uvstride, block_w>>s->chroma_h_shift, block_w>>s->chroma_v_shift);
  466. cr= (sum + block_s/2)/block_s;
  467. // iscore += pix_norm1(&current_mb[2][0], uvstride, block_w>>1) - 2*cr*sum + cr*cr*block_s;
  468. }else
  469. cb = cr = 0;
  470. ic= s->c;
  471. ic.bytestream_start=
  472. ic.bytestream= i_buffer; //FIXME end/start? and at the other stoo
  473. memcpy(i_state, s->block_state, sizeof(s->block_state));
  474. if(level!=s->block_max_depth)
  475. put_rac(&ic, &i_state[4 + s_context], 1);
  476. put_rac(&ic, &i_state[1 + left->type + top->type], 1);
  477. put_symbol(&ic, &i_state[32], l-pl , 1);
  478. if (s->nb_planes > 2) {
  479. put_symbol(&ic, &i_state[64], cb-pcb, 1);
  480. put_symbol(&ic, &i_state[96], cr-pcr, 1);
  481. }
  482. i_len= ic.bytestream - ic.bytestream_start;
  483. iscore += (enc->lambda2*(get_rac_count(&ic)-base_bits))>>FF_LAMBDA_SHIFT;
  484. av_assert1(iscore < 255*255*256 + enc->lambda2*10);
  485. av_assert1(iscore >= 0);
  486. av_assert1(l>=0 && l<=255);
  487. av_assert1(pl>=0 && pl<=255);
  488. if(level==0){
  489. int varc= iscore >> 8;
  490. int vard= score >> 8;
  491. if (vard <= 64 || vard < varc)
  492. c->scene_change_score+= ff_sqrt(vard) - ff_sqrt(varc);
  493. else
  494. c->scene_change_score += enc->m.qscale;
  495. }
  496. if(level!=s->block_max_depth){
  497. put_rac(&s->c, &s->block_state[4 + s_context], 0);
  498. score2 = encode_q_branch(enc, level+1, 2*x+0, 2*y+0);
  499. score2+= encode_q_branch(enc, level+1, 2*x+1, 2*y+0);
  500. score2+= encode_q_branch(enc, level+1, 2*x+0, 2*y+1);
  501. score2+= encode_q_branch(enc, level+1, 2*x+1, 2*y+1);
  502. score2+= enc->lambda2>>FF_LAMBDA_SHIFT; //FIXME exact split overhead
  503. if(score2 < score && score2 < iscore)
  504. return score2;
  505. }
  506. if(iscore < score){
  507. pred_mv(s, &pmx, &pmy, 0, left, top, tr);
  508. memcpy(pbbak, i_buffer, i_len);
  509. s->c= ic;
  510. s->c.bytestream_start= pbbak_start;
  511. s->c.bytestream= pbbak + i_len;
  512. set_blocks(s, level, x, y, l, cb, cr, pmx, pmy, 0, BLOCK_INTRA);
  513. memcpy(s->block_state, i_state, sizeof(s->block_state));
  514. return iscore;
  515. }else{
  516. memcpy(pbbak, p_buffer, p_len);
  517. s->c= pc;
  518. s->c.bytestream_start= pbbak_start;
  519. s->c.bytestream= pbbak + p_len;
  520. set_blocks(s, level, x, y, pl, pcb, pcr, mx, my, best_ref, 0);
  521. memcpy(s->block_state, p_state, sizeof(s->block_state));
  522. return score;
  523. }
  524. }
  525. static void encode_q_branch2(SnowContext *s, int level, int x, int y){
  526. const int w= s->b_width << s->block_max_depth;
  527. const int rem_depth= s->block_max_depth - level;
  528. const int index= (x + y*w) << rem_depth;
  529. int trx= (x+1)<<rem_depth;
  530. BlockNode *b= &s->block[index];
  531. const BlockNode *left = x ? &s->block[index-1] : &null_block;
  532. const BlockNode *top = y ? &s->block[index-w] : &null_block;
  533. const BlockNode *tl = y && x ? &s->block[index-w-1] : left;
  534. const BlockNode *tr = y && trx<w && ((x&1)==0 || level==0) ? &s->block[index-w+(1<<rem_depth)] : tl; //FIXME use lt
  535. int pl = left->color[0];
  536. int pcb= left->color[1];
  537. int pcr= left->color[2];
  538. int pmx, pmy;
  539. int ref_context= av_log2(2*left->ref) + av_log2(2*top->ref);
  540. int mx_context= av_log2(2*FFABS(left->mx - top->mx)) + 16*!!b->ref;
  541. int my_context= av_log2(2*FFABS(left->my - top->my)) + 16*!!b->ref;
  542. int s_context= 2*left->level + 2*top->level + tl->level + tr->level;
  543. if(s->keyframe){
  544. set_blocks(s, level, x, y, pl, pcb, pcr, 0, 0, 0, BLOCK_INTRA);
  545. return;
  546. }
  547. if(level!=s->block_max_depth){
  548. if(same_block(b,b+1) && same_block(b,b+w) && same_block(b,b+w+1)){
  549. put_rac(&s->c, &s->block_state[4 + s_context], 1);
  550. }else{
  551. put_rac(&s->c, &s->block_state[4 + s_context], 0);
  552. encode_q_branch2(s, level+1, 2*x+0, 2*y+0);
  553. encode_q_branch2(s, level+1, 2*x+1, 2*y+0);
  554. encode_q_branch2(s, level+1, 2*x+0, 2*y+1);
  555. encode_q_branch2(s, level+1, 2*x+1, 2*y+1);
  556. return;
  557. }
  558. }
  559. if(b->type & BLOCK_INTRA){
  560. pred_mv(s, &pmx, &pmy, 0, left, top, tr);
  561. put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 1);
  562. put_symbol(&s->c, &s->block_state[32], b->color[0]-pl , 1);
  563. if (s->nb_planes > 2) {
  564. put_symbol(&s->c, &s->block_state[64], b->color[1]-pcb, 1);
  565. put_symbol(&s->c, &s->block_state[96], b->color[2]-pcr, 1);
  566. }
  567. set_blocks(s, level, x, y, b->color[0], b->color[1], b->color[2], pmx, pmy, 0, BLOCK_INTRA);
  568. }else{
  569. pred_mv(s, &pmx, &pmy, b->ref, left, top, tr);
  570. put_rac(&s->c, &s->block_state[1 + (left->type&1) + (top->type&1)], 0);
  571. if(s->ref_frames > 1)
  572. put_symbol(&s->c, &s->block_state[128 + 1024 + 32*ref_context], b->ref, 0);
  573. put_symbol(&s->c, &s->block_state[128 + 32*mx_context], b->mx - pmx, 1);
  574. put_symbol(&s->c, &s->block_state[128 + 32*my_context], b->my - pmy, 1);
  575. set_blocks(s, level, x, y, pl, pcb, pcr, b->mx, b->my, b->ref, 0);
  576. }
  577. }
  578. static int get_dc(SnowEncContext *enc, int mb_x, int mb_y, int plane_index)
  579. {
  580. SnowContext *const s = &enc->com;
  581. int i, x2, y2;
  582. Plane *p= &s->plane[plane_index];
  583. const int block_size = MB_SIZE >> s->block_max_depth;
  584. const int block_w = plane_index ? block_size>>s->chroma_h_shift : block_size;
  585. const int block_h = plane_index ? block_size>>s->chroma_v_shift : block_size;
  586. const uint8_t *obmc = plane_index ? ff_obmc_tab[s->block_max_depth+s->chroma_h_shift] : ff_obmc_tab[s->block_max_depth];
  587. const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
  588. const int ref_stride= s->current_picture->linesize[plane_index];
  589. const uint8_t *src = s->input_picture->data[plane_index];
  590. IDWTELEM *dst= (IDWTELEM*)enc->m.sc.obmc_scratchpad + plane_index*block_size*block_size*4; //FIXME change to unsigned
  591. const int b_stride = s->b_width << s->block_max_depth;
  592. const int w= p->width;
  593. const int h= p->height;
  594. int index= mb_x + mb_y*b_stride;
  595. BlockNode *b= &s->block[index];
  596. BlockNode backup= *b;
  597. int ab=0;
  598. int aa=0;
  599. av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc stuff above
  600. b->type|= BLOCK_INTRA;
  601. b->color[plane_index]= 0;
  602. memset(dst, 0, obmc_stride*obmc_stride*sizeof(IDWTELEM));
  603. for(i=0; i<4; i++){
  604. int mb_x2= mb_x + (i &1) - 1;
  605. int mb_y2= mb_y + (i>>1) - 1;
  606. int x= block_w*mb_x2 + block_w/2;
  607. int y= block_h*mb_y2 + block_h/2;
  608. add_yblock(s, 0, NULL, dst + (i&1)*block_w + (i>>1)*obmc_stride*block_h, NULL, obmc,
  609. x, y, block_w, block_h, w, h, obmc_stride, ref_stride, obmc_stride, mb_x2, mb_y2, 0, 0, plane_index);
  610. for(y2= FFMAX(y, 0); y2<FFMIN(h, y+block_h); y2++){
  611. for(x2= FFMAX(x, 0); x2<FFMIN(w, x+block_w); x2++){
  612. int index= x2-(block_w*mb_x - block_w/2) + (y2-(block_h*mb_y - block_h/2))*obmc_stride;
  613. int obmc_v= obmc[index];
  614. int d;
  615. if(y<0) obmc_v += obmc[index + block_h*obmc_stride];
  616. if(x<0) obmc_v += obmc[index + block_w];
  617. if(y+block_h>h) obmc_v += obmc[index - block_h*obmc_stride];
  618. if(x+block_w>w) obmc_v += obmc[index - block_w];
  619. //FIXME precalculate this or simplify it somehow else
  620. d = -dst[index] + (1<<(FRAC_BITS-1));
  621. dst[index] = d;
  622. ab += (src[x2 + y2*ref_stride] - (d>>FRAC_BITS)) * obmc_v;
  623. aa += obmc_v * obmc_v; //FIXME precalculate this
  624. }
  625. }
  626. }
  627. *b= backup;
  628. return av_clip_uint8( ROUNDED_DIV((int64_t)ab<<LOG2_OBMC_MAX, aa) ); //FIXME we should not need clipping
  629. }
  630. static inline int get_block_bits(SnowContext *s, int x, int y, int w){
  631. const int b_stride = s->b_width << s->block_max_depth;
  632. const int b_height = s->b_height<< s->block_max_depth;
  633. int index= x + y*b_stride;
  634. const BlockNode *b = &s->block[index];
  635. const BlockNode *left = x ? &s->block[index-1] : &null_block;
  636. const BlockNode *top = y ? &s->block[index-b_stride] : &null_block;
  637. const BlockNode *tl = y && x ? &s->block[index-b_stride-1] : left;
  638. const BlockNode *tr = y && x+w<b_stride ? &s->block[index-b_stride+w] : tl;
  639. int dmx, dmy;
  640. // int mx_context= av_log2(2*FFABS(left->mx - top->mx));
  641. // int my_context= av_log2(2*FFABS(left->my - top->my));
  642. if(x<0 || x>=b_stride || y>=b_height)
  643. return 0;
  644. /*
  645. 1 0 0
  646. 01X 1-2 1
  647. 001XX 3-6 2-3
  648. 0001XXX 7-14 4-7
  649. 00001XXXX 15-30 8-15
  650. */
  651. //FIXME try accurate rate
  652. //FIXME intra and inter predictors if surrounding blocks are not the same type
  653. if(b->type & BLOCK_INTRA){
  654. return 3+2*( av_log2(2*FFABS(left->color[0] - b->color[0]))
  655. + av_log2(2*FFABS(left->color[1] - b->color[1]))
  656. + av_log2(2*FFABS(left->color[2] - b->color[2])));
  657. }else{
  658. pred_mv(s, &dmx, &dmy, b->ref, left, top, tr);
  659. dmx-= b->mx;
  660. dmy-= b->my;
  661. return 2*(1 + av_log2(2*FFABS(dmx)) //FIXME kill the 2* can be merged in lambda
  662. + av_log2(2*FFABS(dmy))
  663. + av_log2(2*b->ref));
  664. }
  665. }
  666. static int get_block_rd(SnowEncContext *enc, int mb_x, int mb_y,
  667. int plane_index, uint8_t (*obmc_edged)[MB_SIZE * 2])
  668. {
  669. SnowContext *const s = &enc->com;
  670. Plane *p= &s->plane[plane_index];
  671. const int block_size = MB_SIZE >> s->block_max_depth;
  672. const int block_w = plane_index ? block_size>>s->chroma_h_shift : block_size;
  673. const int block_h = plane_index ? block_size>>s->chroma_v_shift : block_size;
  674. const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
  675. const int ref_stride= s->current_picture->linesize[plane_index];
  676. uint8_t *dst= s->current_picture->data[plane_index];
  677. const uint8_t *src = s->input_picture->data[plane_index];
  678. IDWTELEM *pred= (IDWTELEM*)enc->m.sc.obmc_scratchpad + plane_index*block_size*block_size*4;
  679. uint8_t *cur = s->scratchbuf;
  680. uint8_t *tmp = s->emu_edge_buffer;
  681. const int b_stride = s->b_width << s->block_max_depth;
  682. const int b_height = s->b_height<< s->block_max_depth;
  683. const int w= p->width;
  684. const int h= p->height;
  685. int distortion;
  686. int rate= 0;
  687. const int penalty_factor = get_penalty_factor(enc->lambda, enc->lambda2, s->avctx->me_cmp);
  688. int sx= block_w*mb_x - block_w/2;
  689. int sy= block_h*mb_y - block_h/2;
  690. int x0= FFMAX(0,-sx);
  691. int y0= FFMAX(0,-sy);
  692. int x1= FFMIN(block_w*2, w-sx);
  693. int y1= FFMIN(block_h*2, h-sy);
  694. int i,x,y;
  695. av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc and square assumtions below chckinhg only block_w
  696. ff_snow_pred_block(s, cur, tmp, ref_stride, sx, sy, block_w*2, block_h*2, &s->block[mb_x + mb_y*b_stride], plane_index, w, h);
  697. for(y=y0; y<y1; y++){
  698. const uint8_t *obmc1= obmc_edged[y];
  699. const IDWTELEM *pred1 = pred + y*obmc_stride;
  700. uint8_t *cur1 = cur + y*ref_stride;
  701. uint8_t *dst1 = dst + sx + (sy+y)*ref_stride;
  702. for(x=x0; x<x1; x++){
  703. #if FRAC_BITS >= LOG2_OBMC_MAX
  704. int v = (cur1[x] * obmc1[x]) << (FRAC_BITS - LOG2_OBMC_MAX);
  705. #else
  706. int v = (cur1[x] * obmc1[x] + (1<<(LOG2_OBMC_MAX - FRAC_BITS-1))) >> (LOG2_OBMC_MAX - FRAC_BITS);
  707. #endif
  708. v = (v + pred1[x]) >> FRAC_BITS;
  709. if(v&(~255)) v= ~(v>>31);
  710. dst1[x] = v;
  711. }
  712. }
  713. /* copy the regions where obmc[] = (uint8_t)256 */
  714. if(LOG2_OBMC_MAX == 8
  715. && (mb_x == 0 || mb_x == b_stride-1)
  716. && (mb_y == 0 || mb_y == b_height-1)){
  717. if(mb_x == 0)
  718. x1 = block_w;
  719. else
  720. x0 = block_w;
  721. if(mb_y == 0)
  722. y1 = block_h;
  723. else
  724. y0 = block_h;
  725. for(y=y0; y<y1; y++)
  726. memcpy(dst + sx+x0 + (sy+y)*ref_stride, cur + x0 + y*ref_stride, x1-x0);
  727. }
  728. if(block_w==16){
  729. /* FIXME rearrange dsputil to fit 32x32 cmp functions */
  730. /* FIXME check alignment of the cmp wavelet vs the encoding wavelet */
  731. /* FIXME cmps overlap but do not cover the wavelet's whole support.
  732. * So improving the score of one block is not strictly guaranteed
  733. * to improve the score of the whole frame, thus iterative motion
  734. * estimation does not always converge. */
  735. if(s->avctx->me_cmp == FF_CMP_W97)
  736. distortion = ff_w97_32_c(&enc->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
  737. else if(s->avctx->me_cmp == FF_CMP_W53)
  738. distortion = ff_w53_32_c(&enc->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, 32);
  739. else{
  740. distortion = 0;
  741. for(i=0; i<4; i++){
  742. int off = sx+16*(i&1) + (sy+16*(i>>1))*ref_stride;
  743. distortion += enc->m.me.me_cmp[0](&enc->m, src + off, dst + off, ref_stride, 16);
  744. }
  745. }
  746. }else{
  747. av_assert2(block_w==8);
  748. distortion = enc->m.me.me_cmp[0](&enc->m, src + sx + sy*ref_stride, dst + sx + sy*ref_stride, ref_stride, block_w*2);
  749. }
  750. if(plane_index==0){
  751. for(i=0; i<4; i++){
  752. /* ..RRr
  753. * .RXx.
  754. * rxx..
  755. */
  756. rate += get_block_bits(s, mb_x + (i&1) - (i>>1), mb_y + (i>>1), 1);
  757. }
  758. if(mb_x == b_stride-2)
  759. rate += get_block_bits(s, mb_x + 1, mb_y + 1, 1);
  760. }
  761. return distortion + rate*penalty_factor;
  762. }
  763. static int get_4block_rd(SnowEncContext *enc, int mb_x, int mb_y, int plane_index)
  764. {
  765. SnowContext *const s = &enc->com;
  766. int i, y2;
  767. Plane *p= &s->plane[plane_index];
  768. const int block_size = MB_SIZE >> s->block_max_depth;
  769. const int block_w = plane_index ? block_size>>s->chroma_h_shift : block_size;
  770. const int block_h = plane_index ? block_size>>s->chroma_v_shift : block_size;
  771. const uint8_t *obmc = plane_index ? ff_obmc_tab[s->block_max_depth+s->chroma_h_shift] : ff_obmc_tab[s->block_max_depth];
  772. const int obmc_stride= plane_index ? (2*block_size)>>s->chroma_h_shift : 2*block_size;
  773. const int ref_stride= s->current_picture->linesize[plane_index];
  774. uint8_t *dst= s->current_picture->data[plane_index];
  775. const uint8_t *src = s->input_picture->data[plane_index];
  776. //FIXME zero_dst is const but add_yblock changes dst if add is 0 (this is never the case for dst=zero_dst
  777. // const has only been removed from zero_dst to suppress a warning
  778. static IDWTELEM zero_dst[4096]; //FIXME
  779. const int b_stride = s->b_width << s->block_max_depth;
  780. const int w= p->width;
  781. const int h= p->height;
  782. int distortion= 0;
  783. int rate= 0;
  784. const int penalty_factor= get_penalty_factor(enc->lambda, enc->lambda2, s->avctx->me_cmp);
  785. av_assert2(s->chroma_h_shift == s->chroma_v_shift); //obmc and square assumtions below
  786. for(i=0; i<9; i++){
  787. int mb_x2= mb_x + (i%3) - 1;
  788. int mb_y2= mb_y + (i/3) - 1;
  789. int x= block_w*mb_x2 + block_w/2;
  790. int y= block_h*mb_y2 + block_h/2;
  791. add_yblock(s, 0, NULL, zero_dst, dst, obmc,
  792. x, y, block_w, block_h, w, h, /*dst_stride*/0, ref_stride, obmc_stride, mb_x2, mb_y2, 1, 1, plane_index);
  793. //FIXME find a cleaner/simpler way to skip the outside stuff
  794. for(y2= y; y2<0; y2++)
  795. memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
  796. for(y2= h; y2<y+block_h; y2++)
  797. memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, block_w);
  798. if(x<0){
  799. for(y2= y; y2<y+block_h; y2++)
  800. memcpy(dst + x + y2*ref_stride, src + x + y2*ref_stride, -x);
  801. }
  802. if(x+block_w > w){
  803. for(y2= y; y2<y+block_h; y2++)
  804. memcpy(dst + w + y2*ref_stride, src + w + y2*ref_stride, x+block_w - w);
  805. }
  806. av_assert1(block_w== 8 || block_w==16);
  807. distortion += enc->m.me.me_cmp[block_w==8](&enc->m, src + x + y*ref_stride, dst + x + y*ref_stride, ref_stride, block_h);
  808. }
  809. if(plane_index==0){
  810. BlockNode *b= &s->block[mb_x+mb_y*b_stride];
  811. int merged= same_block(b,b+1) && same_block(b,b+b_stride) && same_block(b,b+b_stride+1);
  812. /* ..RRRr
  813. * .RXXx.
  814. * .RXXx.
  815. * rxxx.
  816. */
  817. if(merged)
  818. rate = get_block_bits(s, mb_x, mb_y, 2);
  819. for(i=merged?4:0; i<9; i++){
  820. static const int dxy[9][2] = {{0,0},{1,0},{0,1},{1,1},{2,0},{2,1},{-1,2},{0,2},{1,2}};
  821. rate += get_block_bits(s, mb_x + dxy[i][0], mb_y + dxy[i][1], 1);
  822. }
  823. }
  824. return distortion + rate*penalty_factor;
  825. }
  826. static int encode_subband_c0run(SnowContext *s, SubBand *b, const IDWTELEM *src, const IDWTELEM *parent, int stride, int orientation){
  827. const int w= b->width;
  828. const int h= b->height;
  829. int x, y;
  830. if(1){
  831. int run=0;
  832. int *runs = s->run_buffer;
  833. int run_index=0;
  834. int max_index;
  835. for(y=0; y<h; y++){
  836. for(x=0; x<w; x++){
  837. int v, p=0;
  838. int /*ll=0, */l=0, lt=0, t=0, rt=0;
  839. v= src[x + y*stride];
  840. if(y){
  841. t= src[x + (y-1)*stride];
  842. if(x){
  843. lt= src[x - 1 + (y-1)*stride];
  844. }
  845. if(x + 1 < w){
  846. rt= src[x + 1 + (y-1)*stride];
  847. }
  848. }
  849. if(x){
  850. l= src[x - 1 + y*stride];
  851. /*if(x > 1){
  852. if(orientation==1) ll= src[y + (x-2)*stride];
  853. else ll= src[x - 2 + y*stride];
  854. }*/
  855. }
  856. if(parent){
  857. int px= x>>1;
  858. int py= y>>1;
  859. if(px<b->parent->width && py<b->parent->height)
  860. p= parent[px + py*2*stride];
  861. }
  862. if(!(/*ll|*/l|lt|t|rt|p)){
  863. if(v){
  864. runs[run_index++]= run;
  865. run=0;
  866. }else{
  867. run++;
  868. }
  869. }
  870. }
  871. }
  872. max_index= run_index;
  873. runs[run_index++]= run;
  874. run_index=0;
  875. run= runs[run_index++];
  876. put_symbol2(&s->c, b->state[30], max_index, 0);
  877. if(run_index <= max_index)
  878. put_symbol2(&s->c, b->state[1], run, 3);
  879. for(y=0; y<h; y++){
  880. if(s->c.bytestream_end - s->c.bytestream < w*40){
  881. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  882. return AVERROR(ENOMEM);
  883. }
  884. for(x=0; x<w; x++){
  885. int v, p=0;
  886. int /*ll=0, */l=0, lt=0, t=0, rt=0;
  887. v= src[x + y*stride];
  888. if(y){
  889. t= src[x + (y-1)*stride];
  890. if(x){
  891. lt= src[x - 1 + (y-1)*stride];
  892. }
  893. if(x + 1 < w){
  894. rt= src[x + 1 + (y-1)*stride];
  895. }
  896. }
  897. if(x){
  898. l= src[x - 1 + y*stride];
  899. /*if(x > 1){
  900. if(orientation==1) ll= src[y + (x-2)*stride];
  901. else ll= src[x - 2 + y*stride];
  902. }*/
  903. }
  904. if(parent){
  905. int px= x>>1;
  906. int py= y>>1;
  907. if(px<b->parent->width && py<b->parent->height)
  908. p= parent[px + py*2*stride];
  909. }
  910. if(/*ll|*/l|lt|t|rt|p){
  911. int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
  912. put_rac(&s->c, &b->state[0][context], !!v);
  913. }else{
  914. if(!run){
  915. run= runs[run_index++];
  916. if(run_index <= max_index)
  917. put_symbol2(&s->c, b->state[1], run, 3);
  918. av_assert2(v);
  919. }else{
  920. run--;
  921. av_assert2(!v);
  922. }
  923. }
  924. if(v){
  925. int context= av_log2(/*FFABS(ll) + */3*FFABS(l) + FFABS(lt) + 2*FFABS(t) + FFABS(rt) + FFABS(p));
  926. int l2= 2*FFABS(l) + (l<0);
  927. int t2= 2*FFABS(t) + (t<0);
  928. put_symbol2(&s->c, b->state[context + 2], FFABS(v)-1, context-4);
  929. put_rac(&s->c, &b->state[0][16 + 1 + 3 + ff_quant3bA[l2&0xFF] + 3*ff_quant3bA[t2&0xFF]], v<0);
  930. }
  931. }
  932. }
  933. }
  934. return 0;
  935. }
  936. static int encode_subband(SnowContext *s, SubBand *b, const IDWTELEM *src, const IDWTELEM *parent, int stride, int orientation){
  937. // encode_subband_qtree(s, b, src, parent, stride, orientation);
  938. // encode_subband_z0run(s, b, src, parent, stride, orientation);
  939. return encode_subband_c0run(s, b, src, parent, stride, orientation);
  940. // encode_subband_dzr(s, b, src, parent, stride, orientation);
  941. }
  942. static av_always_inline int check_block_intra(SnowEncContext *enc, int mb_x, int mb_y, int p[3],
  943. uint8_t (*obmc_edged)[MB_SIZE * 2], int *best_rd)
  944. {
  945. SnowContext *const s = &enc->com;
  946. const int b_stride= s->b_width << s->block_max_depth;
  947. BlockNode *block= &s->block[mb_x + mb_y * b_stride];
  948. BlockNode backup= *block;
  949. int rd;
  950. av_assert2(mb_x>=0 && mb_y>=0);
  951. av_assert2(mb_x<b_stride);
  952. block->color[0] = p[0];
  953. block->color[1] = p[1];
  954. block->color[2] = p[2];
  955. block->type |= BLOCK_INTRA;
  956. rd = get_block_rd(enc, mb_x, mb_y, 0, obmc_edged) + enc->intra_penalty;
  957. //FIXME chroma
  958. if(rd < *best_rd){
  959. *best_rd= rd;
  960. return 1;
  961. }else{
  962. *block= backup;
  963. return 0;
  964. }
  965. }
  966. /* special case for int[2] args we discard afterwards,
  967. * fixes compilation problem with gcc 2.95 */
  968. static av_always_inline int check_block_inter(SnowEncContext *enc,
  969. int mb_x, int mb_y, int p0, int p1,
  970. uint8_t (*obmc_edged)[MB_SIZE * 2], int *best_rd)
  971. {
  972. SnowContext *const s = &enc->com;
  973. const int b_stride = s->b_width << s->block_max_depth;
  974. BlockNode *block = &s->block[mb_x + mb_y * b_stride];
  975. BlockNode backup = *block;
  976. unsigned value;
  977. int rd, index;
  978. av_assert2(mb_x >= 0 && mb_y >= 0);
  979. av_assert2(mb_x < b_stride);
  980. index = (p0 + 31 * p1) & (ME_CACHE_SIZE-1);
  981. value = enc->me_cache_generation + (p0 >> 10) + p1 * (1 << 6) + (block->ref << 12);
  982. if (enc->me_cache[index] == value)
  983. return 0;
  984. enc->me_cache[index] = value;
  985. block->mx = p0;
  986. block->my = p1;
  987. block->type &= ~BLOCK_INTRA;
  988. rd = get_block_rd(enc, mb_x, mb_y, 0, obmc_edged);
  989. //FIXME chroma
  990. if (rd < *best_rd) {
  991. *best_rd = rd;
  992. return 1;
  993. } else {
  994. *block = backup;
  995. return 0;
  996. }
  997. }
  998. static av_always_inline int check_4block_inter(SnowEncContext *enc, int mb_x, int mb_y,
  999. int p0, int p1, int ref, int *best_rd)
  1000. {
  1001. SnowContext *const s = &enc->com;
  1002. const int b_stride= s->b_width << s->block_max_depth;
  1003. BlockNode *block= &s->block[mb_x + mb_y * b_stride];
  1004. BlockNode backup[4];
  1005. unsigned value;
  1006. int rd, index;
  1007. /* We don't initialize backup[] during variable declaration, because
  1008. * that fails to compile on MSVC: "cannot convert from 'BlockNode' to
  1009. * 'int16_t'". */
  1010. backup[0] = block[0];
  1011. backup[1] = block[1];
  1012. backup[2] = block[b_stride];
  1013. backup[3] = block[b_stride + 1];
  1014. av_assert2(mb_x>=0 && mb_y>=0);
  1015. av_assert2(mb_x<b_stride);
  1016. av_assert2(((mb_x|mb_y)&1) == 0);
  1017. index= (p0 + 31*p1) & (ME_CACHE_SIZE-1);
  1018. value = enc->me_cache_generation + (p0>>10) + (p1<<6) + (block->ref<<12);
  1019. if (enc->me_cache[index] == value)
  1020. return 0;
  1021. enc->me_cache[index] = value;
  1022. block->mx= p0;
  1023. block->my= p1;
  1024. block->ref= ref;
  1025. block->type &= ~BLOCK_INTRA;
  1026. block[1]= block[b_stride]= block[b_stride+1]= *block;
  1027. rd = get_4block_rd(enc, mb_x, mb_y, 0);
  1028. //FIXME chroma
  1029. if(rd < *best_rd){
  1030. *best_rd= rd;
  1031. return 1;
  1032. }else{
  1033. block[0]= backup[0];
  1034. block[1]= backup[1];
  1035. block[b_stride]= backup[2];
  1036. block[b_stride+1]= backup[3];
  1037. return 0;
  1038. }
  1039. }
  1040. static void iterative_me(SnowEncContext *enc)
  1041. {
  1042. SnowContext *const s = &enc->com;
  1043. int pass, mb_x, mb_y;
  1044. const int b_width = s->b_width << s->block_max_depth;
  1045. const int b_height= s->b_height << s->block_max_depth;
  1046. const int b_stride= b_width;
  1047. int color[3];
  1048. {
  1049. RangeCoder r = s->c;
  1050. uint8_t state[sizeof(s->block_state)];
  1051. memcpy(state, s->block_state, sizeof(s->block_state));
  1052. for(mb_y= 0; mb_y<s->b_height; mb_y++)
  1053. for(mb_x= 0; mb_x<s->b_width; mb_x++)
  1054. encode_q_branch(enc, 0, mb_x, mb_y);
  1055. s->c = r;
  1056. memcpy(s->block_state, state, sizeof(s->block_state));
  1057. }
  1058. for(pass=0; pass<25; pass++){
  1059. int change= 0;
  1060. for(mb_y= 0; mb_y<b_height; mb_y++){
  1061. for(mb_x= 0; mb_x<b_width; mb_x++){
  1062. int dia_change, i, j, ref;
  1063. int best_rd= INT_MAX, ref_rd;
  1064. BlockNode backup, ref_b;
  1065. const int index= mb_x + mb_y * b_stride;
  1066. BlockNode *block= &s->block[index];
  1067. BlockNode *tb = mb_y ? &s->block[index-b_stride ] : NULL;
  1068. BlockNode *lb = mb_x ? &s->block[index -1] : NULL;
  1069. BlockNode *rb = mb_x+1<b_width ? &s->block[index +1] : NULL;
  1070. BlockNode *bb = mb_y+1<b_height ? &s->block[index+b_stride ] : NULL;
  1071. BlockNode *tlb= mb_x && mb_y ? &s->block[index-b_stride-1] : NULL;
  1072. BlockNode *trb= mb_x+1<b_width && mb_y ? &s->block[index-b_stride+1] : NULL;
  1073. BlockNode *blb= mb_x && mb_y+1<b_height ? &s->block[index+b_stride-1] : NULL;
  1074. BlockNode *brb= mb_x+1<b_width && mb_y+1<b_height ? &s->block[index+b_stride+1] : NULL;
  1075. const int b_w= (MB_SIZE >> s->block_max_depth);
  1076. uint8_t obmc_edged[MB_SIZE * 2][MB_SIZE * 2];
  1077. if(pass && (block->type & BLOCK_OPT))
  1078. continue;
  1079. block->type |= BLOCK_OPT;
  1080. backup= *block;
  1081. if (!enc->me_cache_generation)
  1082. memset(enc->me_cache, 0, sizeof(enc->me_cache));
  1083. enc->me_cache_generation += 1<<22;
  1084. //FIXME precalculate
  1085. {
  1086. int x, y;
  1087. for (y = 0; y < b_w * 2; y++)
  1088. memcpy(obmc_edged[y], ff_obmc_tab[s->block_max_depth] + y * b_w * 2, b_w * 2);
  1089. if(mb_x==0)
  1090. for(y=0; y<b_w*2; y++)
  1091. memset(obmc_edged[y], obmc_edged[y][0] + obmc_edged[y][b_w-1], b_w);
  1092. if(mb_x==b_stride-1)
  1093. for(y=0; y<b_w*2; y++)
  1094. memset(obmc_edged[y]+b_w, obmc_edged[y][b_w] + obmc_edged[y][b_w*2-1], b_w);
  1095. if(mb_y==0){
  1096. for(x=0; x<b_w*2; x++)
  1097. obmc_edged[0][x] += obmc_edged[b_w-1][x];
  1098. for(y=1; y<b_w; y++)
  1099. memcpy(obmc_edged[y], obmc_edged[0], b_w*2);
  1100. }
  1101. if(mb_y==b_height-1){
  1102. for(x=0; x<b_w*2; x++)
  1103. obmc_edged[b_w*2-1][x] += obmc_edged[b_w][x];
  1104. for(y=b_w; y<b_w*2-1; y++)
  1105. memcpy(obmc_edged[y], obmc_edged[b_w*2-1], b_w*2);
  1106. }
  1107. }
  1108. //skip stuff outside the picture
  1109. if(mb_x==0 || mb_y==0 || mb_x==b_width-1 || mb_y==b_height-1){
  1110. const uint8_t *src = s->input_picture->data[0];
  1111. uint8_t *dst= s->current_picture->data[0];
  1112. const int stride= s->current_picture->linesize[0];
  1113. const int block_w= MB_SIZE >> s->block_max_depth;
  1114. const int block_h= MB_SIZE >> s->block_max_depth;
  1115. const int sx= block_w*mb_x - block_w/2;
  1116. const int sy= block_h*mb_y - block_h/2;
  1117. const int w= s->plane[0].width;
  1118. const int h= s->plane[0].height;
  1119. int y;
  1120. for(y=sy; y<0; y++)
  1121. memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
  1122. for(y=h; y<sy+block_h*2; y++)
  1123. memcpy(dst + sx + y*stride, src + sx + y*stride, block_w*2);
  1124. if(sx<0){
  1125. for(y=sy; y<sy+block_h*2; y++)
  1126. memcpy(dst + sx + y*stride, src + sx + y*stride, -sx);
  1127. }
  1128. if(sx+block_w*2 > w){
  1129. for(y=sy; y<sy+block_h*2; y++)
  1130. memcpy(dst + w + y*stride, src + w + y*stride, sx+block_w*2 - w);
  1131. }
  1132. }
  1133. // intra(black) = neighbors' contribution to the current block
  1134. for(i=0; i < s->nb_planes; i++)
  1135. color[i]= get_dc(enc, mb_x, mb_y, i);
  1136. // get previous score (cannot be cached due to OBMC)
  1137. if(pass > 0 && (block->type&BLOCK_INTRA)){
  1138. int color0[3]= {block->color[0], block->color[1], block->color[2]};
  1139. check_block_intra(enc, mb_x, mb_y, color0, obmc_edged, &best_rd);
  1140. }else
  1141. check_block_inter(enc, mb_x, mb_y, block->mx, block->my, obmc_edged, &best_rd);
  1142. ref_b= *block;
  1143. ref_rd= best_rd;
  1144. for(ref=0; ref < s->ref_frames; ref++){
  1145. int16_t (*mvr)[2]= &s->ref_mvs[ref][index];
  1146. if(s->ref_scores[ref][index] > s->ref_scores[ref_b.ref][index]*3/2) //FIXME tune threshold
  1147. continue;
  1148. block->ref= ref;
  1149. best_rd= INT_MAX;
  1150. check_block_inter(enc, mb_x, mb_y, mvr[0][0], mvr[0][1], obmc_edged, &best_rd);
  1151. check_block_inter(enc, mb_x, mb_y, 0, 0, obmc_edged, &best_rd);
  1152. if(tb)
  1153. check_block_inter(enc, mb_x, mb_y, mvr[-b_stride][0], mvr[-b_stride][1], obmc_edged, &best_rd);
  1154. if(lb)
  1155. check_block_inter(enc, mb_x, mb_y, mvr[-1][0], mvr[-1][1], obmc_edged, &best_rd);
  1156. if(rb)
  1157. check_block_inter(enc, mb_x, mb_y, mvr[1][0], mvr[1][1], obmc_edged, &best_rd);
  1158. if(bb)
  1159. check_block_inter(enc, mb_x, mb_y, mvr[b_stride][0], mvr[b_stride][1], obmc_edged, &best_rd);
  1160. /* fullpel ME */
  1161. //FIXME avoid subpel interpolation / round to nearest integer
  1162. do{
  1163. int newx = block->mx;
  1164. int newy = block->my;
  1165. int dia_size = enc->iterative_dia_size ? enc->iterative_dia_size : FFMAX(s->avctx->dia_size, 1);
  1166. dia_change=0;
  1167. for(i=0; i < dia_size; i++){
  1168. for(j=0; j<i; j++){
  1169. dia_change |= check_block_inter(enc, mb_x, mb_y, newx+4*(i-j), newy+(4*j), obmc_edged, &best_rd);
  1170. dia_change |= check_block_inter(enc, mb_x, mb_y, newx-4*(i-j), newy-(4*j), obmc_edged, &best_rd);
  1171. dia_change |= check_block_inter(enc, mb_x, mb_y, newx-(4*j), newy+4*(i-j), obmc_edged, &best_rd);
  1172. dia_change |= check_block_inter(enc, mb_x, mb_y, newx+(4*j), newy-4*(i-j), obmc_edged, &best_rd);
  1173. }
  1174. }
  1175. }while(dia_change);
  1176. /* subpel ME */
  1177. do{
  1178. static const int square[8][2]= {{+1, 0},{-1, 0},{ 0,+1},{ 0,-1},{+1,+1},{-1,-1},{+1,-1},{-1,+1},};
  1179. dia_change=0;
  1180. for(i=0; i<8; i++)
  1181. dia_change |= check_block_inter(enc, mb_x, mb_y, block->mx+square[i][0], block->my+square[i][1], obmc_edged, &best_rd);
  1182. }while(dia_change);
  1183. //FIXME or try the standard 2 pass qpel or similar
  1184. mvr[0][0]= block->mx;
  1185. mvr[0][1]= block->my;
  1186. if(ref_rd > best_rd){
  1187. ref_rd= best_rd;
  1188. ref_b= *block;
  1189. }
  1190. }
  1191. best_rd= ref_rd;
  1192. *block= ref_b;
  1193. check_block_intra(enc, mb_x, mb_y, color, obmc_edged, &best_rd);
  1194. //FIXME RD style color selection
  1195. if(!same_block(block, &backup)){
  1196. if(tb ) tb ->type &= ~BLOCK_OPT;
  1197. if(lb ) lb ->type &= ~BLOCK_OPT;
  1198. if(rb ) rb ->type &= ~BLOCK_OPT;
  1199. if(bb ) bb ->type &= ~BLOCK_OPT;
  1200. if(tlb) tlb->type &= ~BLOCK_OPT;
  1201. if(trb) trb->type &= ~BLOCK_OPT;
  1202. if(blb) blb->type &= ~BLOCK_OPT;
  1203. if(brb) brb->type &= ~BLOCK_OPT;
  1204. change ++;
  1205. }
  1206. }
  1207. }
  1208. av_log(s->avctx, AV_LOG_DEBUG, "pass:%d changed:%d\n", pass, change);
  1209. if(!change)
  1210. break;
  1211. }
  1212. if(s->block_max_depth == 1){
  1213. int change= 0;
  1214. for(mb_y= 0; mb_y<b_height; mb_y+=2){
  1215. for(mb_x= 0; mb_x<b_width; mb_x+=2){
  1216. int i;
  1217. int best_rd, init_rd;
  1218. const int index= mb_x + mb_y * b_stride;
  1219. BlockNode *b[4];
  1220. b[0]= &s->block[index];
  1221. b[1]= b[0]+1;
  1222. b[2]= b[0]+b_stride;
  1223. b[3]= b[2]+1;
  1224. if(same_block(b[0], b[1]) &&
  1225. same_block(b[0], b[2]) &&
  1226. same_block(b[0], b[3]))
  1227. continue;
  1228. if (!enc->me_cache_generation)
  1229. memset(enc->me_cache, 0, sizeof(enc->me_cache));
  1230. enc->me_cache_generation += 1<<22;
  1231. init_rd = best_rd = get_4block_rd(enc, mb_x, mb_y, 0);
  1232. //FIXME more multiref search?
  1233. check_4block_inter(enc, mb_x, mb_y,
  1234. (b[0]->mx + b[1]->mx + b[2]->mx + b[3]->mx + 2) >> 2,
  1235. (b[0]->my + b[1]->my + b[2]->my + b[3]->my + 2) >> 2, 0, &best_rd);
  1236. for(i=0; i<4; i++)
  1237. if(!(b[i]->type&BLOCK_INTRA))
  1238. check_4block_inter(enc, mb_x, mb_y, b[i]->mx, b[i]->my, b[i]->ref, &best_rd);
  1239. if(init_rd != best_rd)
  1240. change++;
  1241. }
  1242. }
  1243. av_log(s->avctx, AV_LOG_ERROR, "pass:4mv changed:%d\n", change*4);
  1244. }
  1245. }
  1246. static void encode_blocks(SnowEncContext *enc, int search)
  1247. {
  1248. SnowContext *const s = &enc->com;
  1249. int x, y;
  1250. int w= s->b_width;
  1251. int h= s->b_height;
  1252. if (enc->motion_est == FF_ME_ITER && !s->keyframe && search)
  1253. iterative_me(enc);
  1254. for(y=0; y<h; y++){
  1255. if(s->c.bytestream_end - s->c.bytestream < w*MB_SIZE*MB_SIZE*3){ //FIXME nicer limit
  1256. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1257. return;
  1258. }
  1259. for(x=0; x<w; x++){
  1260. if (enc->motion_est == FF_ME_ITER || !search)
  1261. encode_q_branch2(s, 0, x, y);
  1262. else
  1263. encode_q_branch (enc, 0, x, y);
  1264. }
  1265. }
  1266. }
  1267. static void quantize(SnowContext *s, SubBand *b, IDWTELEM *dst, DWTELEM *src, int stride, int bias){
  1268. const int w= b->width;
  1269. const int h= b->height;
  1270. const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
  1271. const int qmul= ff_qexp[qlog&(QROOT-1)]<<((qlog>>QSHIFT) + ENCODER_EXTRA_BITS);
  1272. int x,y, thres1, thres2;
  1273. if(s->qlog == LOSSLESS_QLOG){
  1274. for(y=0; y<h; y++)
  1275. for(x=0; x<w; x++)
  1276. dst[x + y*stride]= src[x + y*stride];
  1277. return;
  1278. }
  1279. bias= bias ? 0 : (3*qmul)>>3;
  1280. thres1= ((qmul - bias)>>QEXPSHIFT) - 1;
  1281. thres2= 2*thres1;
  1282. if(!bias){
  1283. for(y=0; y<h; y++){
  1284. for(x=0; x<w; x++){
  1285. int i= src[x + y*stride];
  1286. if((unsigned)(i+thres1) > thres2){
  1287. if(i>=0){
  1288. i<<= QEXPSHIFT;
  1289. i/= qmul; //FIXME optimize
  1290. dst[x + y*stride]= i;
  1291. }else{
  1292. i= -i;
  1293. i<<= QEXPSHIFT;
  1294. i/= qmul; //FIXME optimize
  1295. dst[x + y*stride]= -i;
  1296. }
  1297. }else
  1298. dst[x + y*stride]= 0;
  1299. }
  1300. }
  1301. }else{
  1302. for(y=0; y<h; y++){
  1303. for(x=0; x<w; x++){
  1304. int i= src[x + y*stride];
  1305. if((unsigned)(i+thres1) > thres2){
  1306. if(i>=0){
  1307. i<<= QEXPSHIFT;
  1308. i= (i + bias) / qmul; //FIXME optimize
  1309. dst[x + y*stride]= i;
  1310. }else{
  1311. i= -i;
  1312. i<<= QEXPSHIFT;
  1313. i= (i + bias) / qmul; //FIXME optimize
  1314. dst[x + y*stride]= -i;
  1315. }
  1316. }else
  1317. dst[x + y*stride]= 0;
  1318. }
  1319. }
  1320. }
  1321. }
  1322. static void dequantize(SnowContext *s, SubBand *b, IDWTELEM *src, int stride){
  1323. const int w= b->width;
  1324. const int h= b->height;
  1325. const int qlog= av_clip(s->qlog + b->qlog, 0, QROOT*16);
  1326. const int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
  1327. const int qadd= (s->qbias*qmul)>>QBIAS_SHIFT;
  1328. int x,y;
  1329. if(s->qlog == LOSSLESS_QLOG) return;
  1330. for(y=0; y<h; y++){
  1331. for(x=0; x<w; x++){
  1332. int i= src[x + y*stride];
  1333. if(i<0){
  1334. src[x + y*stride]= -((-i*qmul + qadd)>>(QEXPSHIFT)); //FIXME try different bias
  1335. }else if(i>0){
  1336. src[x + y*stride]= (( i*qmul + qadd)>>(QEXPSHIFT));
  1337. }
  1338. }
  1339. }
  1340. }
  1341. static void decorrelate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
  1342. const int w= b->width;
  1343. const int h= b->height;
  1344. int x,y;
  1345. for(y=h-1; y>=0; y--){
  1346. for(x=w-1; x>=0; x--){
  1347. int i= x + y*stride;
  1348. if(x){
  1349. if(use_median){
  1350. if(y && x+1<w) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
  1351. else src[i] -= src[i - 1];
  1352. }else{
  1353. if(y) src[i] -= mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
  1354. else src[i] -= src[i - 1];
  1355. }
  1356. }else{
  1357. if(y) src[i] -= src[i - stride];
  1358. }
  1359. }
  1360. }
  1361. }
  1362. static void correlate(SnowContext *s, SubBand *b, IDWTELEM *src, int stride, int inverse, int use_median){
  1363. const int w= b->width;
  1364. const int h= b->height;
  1365. int x,y;
  1366. for(y=0; y<h; y++){
  1367. for(x=0; x<w; x++){
  1368. int i= x + y*stride;
  1369. if(x){
  1370. if(use_median){
  1371. if(y && x+1<w) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - stride + 1]);
  1372. else src[i] += src[i - 1];
  1373. }else{
  1374. if(y) src[i] += mid_pred(src[i - 1], src[i - stride], src[i - 1] + src[i - stride] - src[i - 1 - stride]);
  1375. else src[i] += src[i - 1];
  1376. }
  1377. }else{
  1378. if(y) src[i] += src[i - stride];
  1379. }
  1380. }
  1381. }
  1382. }
  1383. static void encode_qlogs(SnowContext *s){
  1384. int plane_index, level, orientation;
  1385. for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
  1386. for(level=0; level<s->spatial_decomposition_count; level++){
  1387. for(orientation=level ? 1:0; orientation<4; orientation++){
  1388. if(orientation==2) continue;
  1389. put_symbol(&s->c, s->header_state, s->plane[plane_index].band[level][orientation].qlog, 1);
  1390. }
  1391. }
  1392. }
  1393. }
  1394. static void encode_header(SnowContext *s){
  1395. int plane_index, i;
  1396. uint8_t kstate[32];
  1397. memset(kstate, MID_STATE, sizeof(kstate));
  1398. put_rac(&s->c, kstate, s->keyframe);
  1399. if(s->keyframe || s->always_reset){
  1400. ff_snow_reset_contexts(s);
  1401. s->last_spatial_decomposition_type=
  1402. s->last_qlog=
  1403. s->last_qbias=
  1404. s->last_mv_scale=
  1405. s->last_block_max_depth= 0;
  1406. for(plane_index=0; plane_index<2; plane_index++){
  1407. Plane *p= &s->plane[plane_index];
  1408. p->last_htaps=0;
  1409. p->last_diag_mc=0;
  1410. memset(p->last_hcoeff, 0, sizeof(p->last_hcoeff));
  1411. }
  1412. }
  1413. if(s->keyframe){
  1414. put_symbol(&s->c, s->header_state, s->version, 0);
  1415. put_rac(&s->c, s->header_state, s->always_reset);
  1416. put_symbol(&s->c, s->header_state, s->temporal_decomposition_type, 0);
  1417. put_symbol(&s->c, s->header_state, s->temporal_decomposition_count, 0);
  1418. put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
  1419. put_symbol(&s->c, s->header_state, s->colorspace_type, 0);
  1420. if (s->nb_planes > 2) {
  1421. put_symbol(&s->c, s->header_state, s->chroma_h_shift, 0);
  1422. put_symbol(&s->c, s->header_state, s->chroma_v_shift, 0);
  1423. }
  1424. put_rac(&s->c, s->header_state, s->spatial_scalability);
  1425. // put_rac(&s->c, s->header_state, s->rate_scalability);
  1426. put_symbol(&s->c, s->header_state, s->max_ref_frames-1, 0);
  1427. encode_qlogs(s);
  1428. }
  1429. if(!s->keyframe){
  1430. int update_mc=0;
  1431. for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
  1432. Plane *p= &s->plane[plane_index];
  1433. update_mc |= p->last_htaps != p->htaps;
  1434. update_mc |= p->last_diag_mc != p->diag_mc;
  1435. update_mc |= !!memcmp(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
  1436. }
  1437. put_rac(&s->c, s->header_state, update_mc);
  1438. if(update_mc){
  1439. for(plane_index=0; plane_index<FFMIN(s->nb_planes, 2); plane_index++){
  1440. Plane *p= &s->plane[plane_index];
  1441. put_rac(&s->c, s->header_state, p->diag_mc);
  1442. put_symbol(&s->c, s->header_state, p->htaps/2-1, 0);
  1443. for(i= p->htaps/2; i; i--)
  1444. put_symbol(&s->c, s->header_state, FFABS(p->hcoeff[i]), 0);
  1445. }
  1446. }
  1447. if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
  1448. put_rac(&s->c, s->header_state, 1);
  1449. put_symbol(&s->c, s->header_state, s->spatial_decomposition_count, 0);
  1450. encode_qlogs(s);
  1451. }else
  1452. put_rac(&s->c, s->header_state, 0);
  1453. }
  1454. put_symbol(&s->c, s->header_state, s->spatial_decomposition_type - s->last_spatial_decomposition_type, 1);
  1455. put_symbol(&s->c, s->header_state, s->qlog - s->last_qlog , 1);
  1456. put_symbol(&s->c, s->header_state, s->mv_scale - s->last_mv_scale, 1);
  1457. put_symbol(&s->c, s->header_state, s->qbias - s->last_qbias , 1);
  1458. put_symbol(&s->c, s->header_state, s->block_max_depth - s->last_block_max_depth, 1);
  1459. }
  1460. static void update_last_header_values(SnowContext *s){
  1461. int plane_index;
  1462. if(!s->keyframe){
  1463. for(plane_index=0; plane_index<2; plane_index++){
  1464. Plane *p= &s->plane[plane_index];
  1465. p->last_diag_mc= p->diag_mc;
  1466. p->last_htaps = p->htaps;
  1467. memcpy(p->last_hcoeff, p->hcoeff, sizeof(p->hcoeff));
  1468. }
  1469. }
  1470. s->last_spatial_decomposition_type = s->spatial_decomposition_type;
  1471. s->last_qlog = s->qlog;
  1472. s->last_qbias = s->qbias;
  1473. s->last_mv_scale = s->mv_scale;
  1474. s->last_block_max_depth = s->block_max_depth;
  1475. s->last_spatial_decomposition_count = s->spatial_decomposition_count;
  1476. }
  1477. static int qscale2qlog(int qscale){
  1478. return lrint(QROOT*log2(qscale / (float)FF_QP2LAMBDA))
  1479. + 61*QROOT/8; ///< 64 > 60
  1480. }
  1481. static int ratecontrol_1pass(SnowEncContext *enc, AVFrame *pict)
  1482. {
  1483. SnowContext *const s = &enc->com;
  1484. /* Estimate the frame's complexity as a sum of weighted dwt coefficients.
  1485. * FIXME we know exact mv bits at this point,
  1486. * but ratecontrol isn't set up to include them. */
  1487. uint32_t coef_sum= 0;
  1488. int level, orientation, delta_qlog;
  1489. for(level=0; level<s->spatial_decomposition_count; level++){
  1490. for(orientation=level ? 1 : 0; orientation<4; orientation++){
  1491. SubBand *b= &s->plane[0].band[level][orientation];
  1492. IDWTELEM *buf= b->ibuf;
  1493. const int w= b->width;
  1494. const int h= b->height;
  1495. const int stride= b->stride;
  1496. const int qlog= av_clip(2*QROOT + b->qlog, 0, QROOT*16);
  1497. const int qmul= ff_qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);
  1498. const int qdiv= (1<<16)/qmul;
  1499. int x, y;
  1500. //FIXME this is ugly
  1501. for(y=0; y<h; y++)
  1502. for(x=0; x<w; x++)
  1503. buf[x+y*stride]= b->buf[x+y*stride];
  1504. if(orientation==0)
  1505. decorrelate(s, b, buf, stride, 1, 0);
  1506. for(y=0; y<h; y++)
  1507. for(x=0; x<w; x++)
  1508. coef_sum+= abs(buf[x+y*stride]) * qdiv >> 16;
  1509. }
  1510. }
  1511. /* ugly, ratecontrol just takes a sqrt again */
  1512. av_assert0(coef_sum < INT_MAX);
  1513. coef_sum = (uint64_t)coef_sum * coef_sum >> 16;
  1514. if(pict->pict_type == AV_PICTURE_TYPE_I){
  1515. enc->m.mb_var_sum = coef_sum;
  1516. enc->m.mc_mb_var_sum = 0;
  1517. }else{
  1518. enc->m.mc_mb_var_sum = coef_sum;
  1519. enc->m.mb_var_sum = 0;
  1520. }
  1521. pict->quality= ff_rate_estimate_qscale(&enc->m, 1);
  1522. if (pict->quality < 0)
  1523. return INT_MIN;
  1524. enc->lambda= pict->quality * 3/2;
  1525. delta_qlog= qscale2qlog(pict->quality) - s->qlog;
  1526. s->qlog+= delta_qlog;
  1527. return delta_qlog;
  1528. }
  1529. static void calculate_visual_weight(SnowContext *s, Plane *p){
  1530. int width = p->width;
  1531. int height= p->height;
  1532. int level, orientation, x, y;
  1533. for(level=0; level<s->spatial_decomposition_count; level++){
  1534. int64_t error=0;
  1535. for(orientation=level ? 1 : 0; orientation<4; orientation++){
  1536. SubBand *b= &p->band[level][orientation];
  1537. IDWTELEM *ibuf= b->ibuf;
  1538. memset(s->spatial_idwt_buffer, 0, sizeof(*s->spatial_idwt_buffer)*width*height);
  1539. ibuf[b->width/2 + b->height/2*b->stride]= 256*16;
  1540. ff_spatial_idwt(s->spatial_idwt_buffer, s->temp_idwt_buffer, width, height, width, s->spatial_decomposition_type, s->spatial_decomposition_count);
  1541. for(y=0; y<height; y++){
  1542. for(x=0; x<width; x++){
  1543. int64_t d= s->spatial_idwt_buffer[x + y*width]*16;
  1544. error += d*d;
  1545. }
  1546. }
  1547. if (orientation == 2)
  1548. error /= 2;
  1549. b->qlog= (int)(QROOT * log2(352256.0/sqrt(error)) + 0.5);
  1550. if (orientation != 1)
  1551. error = 0;
  1552. }
  1553. p->band[level][1].qlog = p->band[level][2].qlog;
  1554. }
  1555. }
  1556. static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1557. const AVFrame *pict, int *got_packet)
  1558. {
  1559. SnowEncContext *const enc = avctx->priv_data;
  1560. SnowContext *const s = &enc->com;
  1561. MpegEncContext *const mpv = &enc->m;
  1562. RangeCoder * const c= &s->c;
  1563. AVCodecInternal *avci = avctx->internal;
  1564. AVFrame *pic;
  1565. const int width= s->avctx->width;
  1566. const int height= s->avctx->height;
  1567. int level, orientation, plane_index, i, y, ret;
  1568. uint8_t rc_header_bak[sizeof(s->header_state)];
  1569. uint8_t rc_block_bak[sizeof(s->block_state)];
  1570. if ((ret = ff_alloc_packet(avctx, pkt, s->b_width*s->b_height*MB_SIZE*MB_SIZE*3 + FF_INPUT_BUFFER_MIN_SIZE)) < 0)
  1571. return ret;
  1572. ff_init_range_encoder(c, pkt->data, pkt->size);
  1573. ff_build_rac_states(c, (1LL<<32)/20, 256-8);
  1574. for(i=0; i < s->nb_planes; i++){
  1575. int hshift= i ? s->chroma_h_shift : 0;
  1576. int vshift= i ? s->chroma_v_shift : 0;
  1577. for(y=0; y<AV_CEIL_RSHIFT(height, vshift); y++)
  1578. memcpy(&s->input_picture->data[i][y * s->input_picture->linesize[i]],
  1579. &pict->data[i][y * pict->linesize[i]],
  1580. AV_CEIL_RSHIFT(width, hshift));
  1581. enc->mpvencdsp.draw_edges(s->input_picture->data[i], s->input_picture->linesize[i],
  1582. AV_CEIL_RSHIFT(width, hshift), AV_CEIL_RSHIFT(height, vshift),
  1583. EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
  1584. EDGE_TOP | EDGE_BOTTOM);
  1585. }
  1586. emms_c();
  1587. pic = s->input_picture;
  1588. pic->pict_type = pict->pict_type;
  1589. pic->quality = pict->quality;
  1590. mpv->picture_number = avctx->frame_num;
  1591. if(avctx->flags&AV_CODEC_FLAG_PASS2){
  1592. mpv->pict_type = pic->pict_type = mpv->rc_context.entry[avctx->frame_num].new_pict_type;
  1593. s->keyframe = pic->pict_type == AV_PICTURE_TYPE_I;
  1594. if(!(avctx->flags&AV_CODEC_FLAG_QSCALE)) {
  1595. pic->quality = ff_rate_estimate_qscale(mpv, 0);
  1596. if (pic->quality < 0)
  1597. return -1;
  1598. }
  1599. }else{
  1600. s->keyframe= avctx->gop_size==0 || avctx->frame_num % avctx->gop_size == 0;
  1601. mpv->pict_type = pic->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
  1602. }
  1603. if (enc->pass1_rc && avctx->frame_num == 0)
  1604. pic->quality = 2*FF_QP2LAMBDA;
  1605. if (pic->quality) {
  1606. s->qlog = qscale2qlog(pic->quality);
  1607. enc->lambda = pic->quality * 3/2;
  1608. }
  1609. if (s->qlog < 0 || (!pic->quality && (avctx->flags & AV_CODEC_FLAG_QSCALE))) {
  1610. s->qlog= LOSSLESS_QLOG;
  1611. enc->lambda = 0;
  1612. }//else keep previous frame's qlog until after motion estimation
  1613. if (s->current_picture->data[0]) {
  1614. int w = s->avctx->width;
  1615. int h = s->avctx->height;
  1616. enc->mpvencdsp.draw_edges(s->current_picture->data[0],
  1617. s->current_picture->linesize[0], w , h ,
  1618. EDGE_WIDTH , EDGE_WIDTH , EDGE_TOP | EDGE_BOTTOM);
  1619. if (s->current_picture->data[2]) {
  1620. enc->mpvencdsp.draw_edges(s->current_picture->data[1],
  1621. s->current_picture->linesize[1], w>>s->chroma_h_shift, h>>s->chroma_v_shift,
  1622. EDGE_WIDTH>>s->chroma_h_shift, EDGE_WIDTH>>s->chroma_v_shift, EDGE_TOP | EDGE_BOTTOM);
  1623. enc->mpvencdsp.draw_edges(s->current_picture->data[2],
  1624. s->current_picture->linesize[2], w>>s->chroma_h_shift, h>>s->chroma_v_shift,
  1625. EDGE_WIDTH>>s->chroma_h_shift, EDGE_WIDTH>>s->chroma_v_shift, EDGE_TOP | EDGE_BOTTOM);
  1626. }
  1627. emms_c();
  1628. }
  1629. ff_snow_frames_prepare(s);
  1630. ret = get_encode_buffer(s, s->current_picture);
  1631. if (ret < 0)
  1632. return ret;
  1633. mpv->cur_pic.ptr = &enc->cur_pic;
  1634. mpv->cur_pic.ptr->f = s->current_picture;
  1635. mpv->cur_pic.ptr->f->pts = pict->pts;
  1636. if(pic->pict_type == AV_PICTURE_TYPE_P){
  1637. int block_width = (width +15)>>4;
  1638. int block_height= (height+15)>>4;
  1639. int stride= s->current_picture->linesize[0];
  1640. av_assert0(s->current_picture->data[0]);
  1641. av_assert0(s->last_picture[0]->data[0]);
  1642. mpv->avctx = s->avctx;
  1643. mpv->last_pic.ptr = &enc->last_pic;
  1644. mpv->last_pic.ptr->f = s->last_picture[0];
  1645. mpv-> new_pic = s->input_picture;
  1646. mpv->linesize = stride;
  1647. mpv->uvlinesize = s->current_picture->linesize[1];
  1648. mpv->width = width;
  1649. mpv->height = height;
  1650. mpv->mb_width = block_width;
  1651. mpv->mb_height = block_height;
  1652. mpv->mb_stride = mpv->mb_width + 1;
  1653. mpv->b8_stride = 2 * mpv->mb_width + 1;
  1654. mpv->f_code = 1;
  1655. mpv->pict_type = pic->pict_type;
  1656. mpv->motion_est = enc->motion_est;
  1657. mpv->me.scene_change_score = 0;
  1658. mpv->me.dia_size = avctx->dia_size;
  1659. mpv->quarter_sample = (s->avctx->flags & AV_CODEC_FLAG_QPEL)!=0;
  1660. mpv->out_format = FMT_H263;
  1661. mpv->unrestricted_mv = 1;
  1662. mpv->lambda = enc->lambda;
  1663. mpv->qscale = (mpv->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  1664. enc->lambda2 = mpv->lambda2 = (mpv->lambda*mpv->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
  1665. mpv->qdsp = enc->qdsp; //move
  1666. mpv->hdsp = s->hdsp;
  1667. ff_me_init_pic(&enc->m);
  1668. s->hdsp = mpv->hdsp;
  1669. }
  1670. if (enc->pass1_rc) {
  1671. memcpy(rc_header_bak, s->header_state, sizeof(s->header_state));
  1672. memcpy(rc_block_bak, s->block_state, sizeof(s->block_state));
  1673. }
  1674. redo_frame:
  1675. s->spatial_decomposition_count= 5;
  1676. while( !(width >>(s->chroma_h_shift + s->spatial_decomposition_count))
  1677. || !(height>>(s->chroma_v_shift + s->spatial_decomposition_count)))
  1678. s->spatial_decomposition_count--;
  1679. if (s->spatial_decomposition_count <= 0) {
  1680. av_log(avctx, AV_LOG_ERROR, "Resolution too low\n");
  1681. return AVERROR(EINVAL);
  1682. }
  1683. mpv->pict_type = pic->pict_type;
  1684. s->qbias = pic->pict_type == AV_PICTURE_TYPE_P ? 2 : 0;
  1685. ff_snow_common_init_after_header(avctx);
  1686. if(s->last_spatial_decomposition_count != s->spatial_decomposition_count){
  1687. for(plane_index=0; plane_index < s->nb_planes; plane_index++){
  1688. calculate_visual_weight(s, &s->plane[plane_index]);
  1689. }
  1690. }
  1691. encode_header(s);
  1692. mpv->misc_bits = 8 * (s->c.bytestream - s->c.bytestream_start);
  1693. encode_blocks(enc, 1);
  1694. mpv->mv_bits = 8 * (s->c.bytestream - s->c.bytestream_start) - mpv->misc_bits;
  1695. for(plane_index=0; plane_index < s->nb_planes; plane_index++){
  1696. Plane *p= &s->plane[plane_index];
  1697. int w= p->width;
  1698. int h= p->height;
  1699. int x, y;
  1700. // int bits= put_bits_count(&s->c.pb);
  1701. if (!enc->memc_only) {
  1702. //FIXME optimize
  1703. if(pict->data[plane_index]) //FIXME gray hack
  1704. for(y=0; y<h; y++){
  1705. for(x=0; x<w; x++){
  1706. s->spatial_idwt_buffer[y*w + x]= pict->data[plane_index][y*pict->linesize[plane_index] + x]<<FRAC_BITS;
  1707. }
  1708. }
  1709. predict_plane(s, s->spatial_idwt_buffer, plane_index, 0);
  1710. if( plane_index==0
  1711. && pic->pict_type == AV_PICTURE_TYPE_P
  1712. && !(avctx->flags&AV_CODEC_FLAG_PASS2)
  1713. && mpv->me.scene_change_score > enc->scenechange_threshold) {
  1714. ff_init_range_encoder(c, pkt->data, pkt->size);
  1715. ff_build_rac_states(c, (1LL<<32)/20, 256-8);
  1716. pic->pict_type= AV_PICTURE_TYPE_I;
  1717. s->keyframe=1;
  1718. s->current_picture->flags |= AV_FRAME_FLAG_KEY;
  1719. goto redo_frame;
  1720. }
  1721. if(s->qlog == LOSSLESS_QLOG){
  1722. for(y=0; y<h; y++){
  1723. for(x=0; x<w; x++){
  1724. s->spatial_dwt_buffer[y*w + x]= (s->spatial_idwt_buffer[y*w + x] + (1<<(FRAC_BITS-1))-1)>>FRAC_BITS;
  1725. }
  1726. }
  1727. }else{
  1728. for(y=0; y<h; y++){
  1729. for(x=0; x<w; x++){
  1730. s->spatial_dwt_buffer[y*w + x]= s->spatial_idwt_buffer[y*w + x] * (1 << ENCODER_EXTRA_BITS);
  1731. }
  1732. }
  1733. }
  1734. ff_spatial_dwt(s->spatial_dwt_buffer, s->temp_dwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
  1735. if (enc->pass1_rc && plane_index==0) {
  1736. int delta_qlog = ratecontrol_1pass(enc, pic);
  1737. if (delta_qlog <= INT_MIN)
  1738. return -1;
  1739. if(delta_qlog){
  1740. //reordering qlog in the bitstream would eliminate this reset
  1741. ff_init_range_encoder(c, pkt->data, pkt->size);
  1742. memcpy(s->header_state, rc_header_bak, sizeof(s->header_state));
  1743. memcpy(s->block_state, rc_block_bak, sizeof(s->block_state));
  1744. encode_header(s);
  1745. encode_blocks(enc, 0);
  1746. }
  1747. }
  1748. for(level=0; level<s->spatial_decomposition_count; level++){
  1749. for(orientation=level ? 1 : 0; orientation<4; orientation++){
  1750. SubBand *b= &p->band[level][orientation];
  1751. quantize(s, b, b->ibuf, b->buf, b->stride, s->qbias);
  1752. if(orientation==0)
  1753. decorrelate(s, b, b->ibuf, b->stride, pic->pict_type == AV_PICTURE_TYPE_P, 0);
  1754. if (!enc->no_bitstream)
  1755. encode_subband(s, b, b->ibuf, b->parent ? b->parent->ibuf : NULL, b->stride, orientation);
  1756. av_assert0(b->parent==NULL || b->parent->stride == b->stride*2);
  1757. if(orientation==0)
  1758. correlate(s, b, b->ibuf, b->stride, 1, 0);
  1759. }
  1760. }
  1761. for(level=0; level<s->spatial_decomposition_count; level++){
  1762. for(orientation=level ? 1 : 0; orientation<4; orientation++){
  1763. SubBand *b= &p->band[level][orientation];
  1764. dequantize(s, b, b->ibuf, b->stride);
  1765. }
  1766. }
  1767. ff_spatial_idwt(s->spatial_idwt_buffer, s->temp_idwt_buffer, w, h, w, s->spatial_decomposition_type, s->spatial_decomposition_count);
  1768. if(s->qlog == LOSSLESS_QLOG){
  1769. for(y=0; y<h; y++){
  1770. for(x=0; x<w; x++){
  1771. s->spatial_idwt_buffer[y*w + x] *= 1 << FRAC_BITS;
  1772. }
  1773. }
  1774. }
  1775. predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
  1776. }else{
  1777. //ME/MC only
  1778. if(pic->pict_type == AV_PICTURE_TYPE_I){
  1779. for(y=0; y<h; y++){
  1780. for(x=0; x<w; x++){
  1781. s->current_picture->data[plane_index][y*s->current_picture->linesize[plane_index] + x]=
  1782. pict->data[plane_index][y*pict->linesize[plane_index] + x];
  1783. }
  1784. }
  1785. }else{
  1786. memset(s->spatial_idwt_buffer, 0, sizeof(IDWTELEM)*w*h);
  1787. predict_plane(s, s->spatial_idwt_buffer, plane_index, 1);
  1788. }
  1789. }
  1790. if(s->avctx->flags&AV_CODEC_FLAG_PSNR){
  1791. int64_t error= 0;
  1792. if(pict->data[plane_index]) //FIXME gray hack
  1793. for(y=0; y<h; y++){
  1794. for(x=0; x<w; x++){
  1795. int d= s->current_picture->data[plane_index][y*s->current_picture->linesize[plane_index] + x] - pict->data[plane_index][y*pict->linesize[plane_index] + x];
  1796. error += d*d;
  1797. }
  1798. }
  1799. s->avctx->error[plane_index] += error;
  1800. enc->encoding_error[plane_index] = error;
  1801. }
  1802. }
  1803. emms_c();
  1804. update_last_header_values(s);
  1805. av_frame_unref(s->last_picture[s->max_ref_frames - 1]);
  1806. s->current_picture->pict_type = pic->pict_type;
  1807. s->current_picture->quality = pic->quality;
  1808. mpv->frame_bits = 8 * (s->c.bytestream - s->c.bytestream_start);
  1809. mpv->p_tex_bits = mpv->frame_bits - mpv->misc_bits - mpv->mv_bits;
  1810. mpv->total_bits += 8*(s->c.bytestream - s->c.bytestream_start);
  1811. enc->cur_pic.display_picture_number =
  1812. enc->cur_pic.coded_picture_number = avctx->frame_num;
  1813. enc->cur_pic.f->quality = pic->quality;
  1814. if (enc->pass1_rc)
  1815. if (ff_rate_estimate_qscale(mpv, 0) < 0)
  1816. return -1;
  1817. if(avctx->flags&AV_CODEC_FLAG_PASS1)
  1818. ff_write_pass1_stats(mpv);
  1819. mpv->last_pict_type = mpv->pict_type;
  1820. emms_c();
  1821. ff_side_data_set_encoder_stats(pkt, s->current_picture->quality,
  1822. enc->encoding_error,
  1823. (s->avctx->flags&AV_CODEC_FLAG_PSNR) ? SNOW_MAX_PLANES : 0,
  1824. s->current_picture->pict_type);
  1825. if (s->avctx->flags & AV_CODEC_FLAG_RECON_FRAME) {
  1826. av_frame_replace(avci->recon_frame, s->current_picture);
  1827. }
  1828. pkt->size = ff_rac_terminate(c, 0);
  1829. if (s->current_picture->flags & AV_FRAME_FLAG_KEY)
  1830. pkt->flags |= AV_PKT_FLAG_KEY;
  1831. *got_packet = 1;
  1832. return 0;
  1833. }
  1834. static av_cold int encode_end(AVCodecContext *avctx)
  1835. {
  1836. SnowEncContext *const enc = avctx->priv_data;
  1837. SnowContext *const s = &enc->com;
  1838. ff_snow_common_end(s);
  1839. ff_rate_control_uninit(&enc->m.rc_context);
  1840. av_frame_free(&s->input_picture);
  1841. for (int i = 0; i < MAX_REF_FRAMES; i++) {
  1842. av_freep(&s->ref_mvs[i]);
  1843. av_freep(&s->ref_scores[i]);
  1844. }
  1845. enc->m.me.temp = NULL;
  1846. av_freep(&enc->m.me.scratchpad);
  1847. av_freep(&enc->m.me.map);
  1848. av_freep(&enc->m.sc.obmc_scratchpad);
  1849. av_freep(&avctx->stats_out);
  1850. return 0;
  1851. }
  1852. #define OFFSET(x) offsetof(SnowEncContext, x)
  1853. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  1854. static const AVOption options[] = {
  1855. {"motion_est", "motion estimation algorithm", OFFSET(motion_est), AV_OPT_TYPE_INT, {.i64 = FF_ME_EPZS }, FF_ME_ZERO, FF_ME_ITER, VE, .unit = "motion_est" },
  1856. { "zero", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_ME_ZERO }, 0, 0, VE, .unit = "motion_est" },
  1857. { "epzs", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_ME_EPZS }, 0, 0, VE, .unit = "motion_est" },
  1858. { "xone", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_ME_XONE }, 0, 0, VE, .unit = "motion_est" },
  1859. { "iter", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FF_ME_ITER }, 0, 0, VE, .unit = "motion_est" },
  1860. { "memc_only", "Only do ME/MC (I frames -> ref, P frame -> ME+MC).", OFFSET(memc_only), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  1861. { "no_bitstream", "Skip final bitstream writeout.", OFFSET(no_bitstream), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  1862. { "intra_penalty", "Penalty for intra blocks in block decission", OFFSET(intra_penalty), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  1863. { "iterative_dia_size", "Dia size for the iterative ME", OFFSET(iterative_dia_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  1864. { "sc_threshold", "Scene change threshold", OFFSET(scenechange_threshold), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, VE },
  1865. { "pred", "Spatial decomposition type", OFFSET(pred), AV_OPT_TYPE_INT, { .i64 = 0 }, DWT_97, DWT_53, VE, .unit = "pred" },
  1866. { "dwt97", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, .unit = "pred" },
  1867. { "dwt53", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, .unit = "pred" },
  1868. { "rc_eq", "Set rate control equation. When computing the expression, besides the standard functions "
  1869. "defined in the section 'Expression Evaluation', the following functions are available: "
  1870. "bits2qp(bits), qp2bits(qp). Also the following constants are available: iTex pTex tex mv "
  1871. "fCode iCount mcVar var isI isP isB avgQP qComp avgIITex avgPITex avgPPTex avgBPTex avgTex.",
  1872. OFFSET(m.rc_context.rc_eq), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
  1873. { NULL },
  1874. };
  1875. static const AVClass snowenc_class = {
  1876. .class_name = "snow encoder",
  1877. .item_name = av_default_item_name,
  1878. .option = options,
  1879. .version = LIBAVUTIL_VERSION_INT,
  1880. };
  1881. const FFCodec ff_snow_encoder = {
  1882. .p.name = "snow",
  1883. CODEC_LONG_NAME("Snow"),
  1884. .p.type = AVMEDIA_TYPE_VIDEO,
  1885. .p.id = AV_CODEC_ID_SNOW,
  1886. .p.capabilities = AV_CODEC_CAP_DR1 |
  1887. AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE |
  1888. AV_CODEC_CAP_ENCODER_RECON_FRAME,
  1889. .priv_data_size = sizeof(SnowEncContext),
  1890. .init = encode_init,
  1891. FF_CODEC_ENCODE_CB(encode_frame),
  1892. .close = encode_end,
  1893. CODEC_PIXFMTS(AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV444P,
  1894. AV_PIX_FMT_GRAY8),
  1895. .color_ranges = AVCOL_RANGE_MPEG,
  1896. .p.priv_class = &snowenc_class,
  1897. .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
  1898. };