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.

2031 lines
77KB

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