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.

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