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.

2004 lines
76KB

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