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.

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