You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1966 lines
75KB

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