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.

2008 lines
76KB

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