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.

1940 lines
74KB

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