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.

1927 lines
73KB

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