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.

3833 lines
139KB

  1. /*
  2. * The simplest mpeg encoder (well, it was the simplest!)
  3. * Copyright (c) 2000,2001 Fabrice Bellard
  4. * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  5. *
  6. * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  7. *
  8. * This file is part of FFmpeg.
  9. *
  10. * FFmpeg is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * FFmpeg is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with FFmpeg; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. /**
  25. * @file libavcodec/mpegvideo_enc.c
  26. * The simplest mpeg encoder (well, it was the simplest!).
  27. */
  28. #include "avcodec.h"
  29. #include "dsputil.h"
  30. #include "mpegvideo.h"
  31. #include "mpegvideo_common.h"
  32. #include "h263.h"
  33. #include "mjpegenc.h"
  34. #include "msmpeg4.h"
  35. #include "faandct.h"
  36. #include "aandcttab.h"
  37. #include "flv.h"
  38. #include "mpeg4video.h"
  39. #include <limits.h>
  40. //#undef NDEBUG
  41. //#include <assert.h>
  42. static int encode_picture(MpegEncContext *s, int picture_number);
  43. static int dct_quantize_refine(MpegEncContext *s, DCTELEM *block, int16_t *weight, DCTELEM *orig, int n, int qscale);
  44. static int sse_mb(MpegEncContext *s);
  45. /* enable all paranoid tests for rounding, overflows, etc... */
  46. //#define PARANOID
  47. //#define DEBUG
  48. static uint8_t default_mv_penalty[MAX_FCODE+1][MAX_MV*2+1];
  49. static uint8_t default_fcode_tab[MAX_MV*2+1];
  50. void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
  51. const uint16_t *quant_matrix, int bias, int qmin, int qmax, int intra)
  52. {
  53. int qscale;
  54. int shift=0;
  55. for(qscale=qmin; qscale<=qmax; qscale++){
  56. int i;
  57. if (dsp->fdct == ff_jpeg_fdct_islow
  58. #ifdef FAAN_POSTSCALE
  59. || dsp->fdct == ff_faandct
  60. #endif
  61. ) {
  62. for(i=0;i<64;i++) {
  63. const int j= dsp->idct_permutation[i];
  64. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  65. /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  66. /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1 << 36) / 249205026 */
  67. /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  68. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
  69. (qscale * quant_matrix[j]));
  70. }
  71. } else if (dsp->fdct == fdct_ifast
  72. #ifndef FAAN_POSTSCALE
  73. || dsp->fdct == ff_faandct
  74. #endif
  75. ) {
  76. for(i=0;i<64;i++) {
  77. const int j= dsp->idct_permutation[i];
  78. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  79. /* 19952 <= ff_aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  80. /* (1 << 36) / 19952 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
  81. /* 3444240 >= (1 << 36) / (ff_aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  82. qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
  83. (ff_aanscales[i] * qscale * quant_matrix[j]));
  84. }
  85. } else {
  86. for(i=0;i<64;i++) {
  87. const int j= dsp->idct_permutation[i];
  88. /* We can safely suppose that 16 <= quant_matrix[i] <= 255
  89. So 16 <= qscale * quant_matrix[i] <= 7905
  90. so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
  91. so 32768 >= (1<<19) / (qscale * quant_matrix[i]) >= 67
  92. */
  93. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
  94. // qmat [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
  95. qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
  96. if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
  97. qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
  98. }
  99. }
  100. for(i=intra; i<64; i++){
  101. int64_t max= 8191;
  102. if (dsp->fdct == fdct_ifast
  103. #ifndef FAAN_POSTSCALE
  104. || dsp->fdct == ff_faandct
  105. #endif
  106. ) {
  107. max = (8191LL*ff_aanscales[i]) >> 14;
  108. }
  109. while(((max * qmat[qscale][i]) >> shift) > INT_MAX){
  110. shift++;
  111. }
  112. }
  113. }
  114. if(shift){
  115. av_log(NULL, AV_LOG_INFO, "Warning, QMAT_SHIFT is larger than %d, overflows possible\n", QMAT_SHIFT - shift);
  116. }
  117. }
  118. static inline void update_qscale(MpegEncContext *s){
  119. s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  120. s->qscale= av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
  121. s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
  122. }
  123. void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix){
  124. int i;
  125. if(matrix){
  126. put_bits(pb, 1, 1);
  127. for(i=0;i<64;i++) {
  128. put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
  129. }
  130. }else
  131. put_bits(pb, 1, 0);
  132. }
  133. /**
  134. * init s->current_picture.qscale_table from s->lambda_table
  135. */
  136. void ff_init_qscale_tab(MpegEncContext *s){
  137. int8_t * const qscale_table= s->current_picture.qscale_table;
  138. int i;
  139. for(i=0; i<s->mb_num; i++){
  140. unsigned int lam= s->lambda_table[ s->mb_index2xy[i] ];
  141. int qp= (lam*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  142. qscale_table[ s->mb_index2xy[i] ]= av_clip(qp, s->avctx->qmin, s->avctx->qmax);
  143. }
  144. }
  145. static void copy_picture_attributes(MpegEncContext *s, AVFrame *dst, AVFrame *src){
  146. int i;
  147. dst->pict_type = src->pict_type;
  148. dst->quality = src->quality;
  149. dst->coded_picture_number = src->coded_picture_number;
  150. dst->display_picture_number = src->display_picture_number;
  151. // dst->reference = src->reference;
  152. dst->pts = src->pts;
  153. dst->interlaced_frame = src->interlaced_frame;
  154. dst->top_field_first = src->top_field_first;
  155. if(s->avctx->me_threshold){
  156. if(!src->motion_val[0])
  157. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_val not set!\n");
  158. if(!src->mb_type)
  159. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.mb_type not set!\n");
  160. if(!src->ref_index[0])
  161. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.ref_index not set!\n");
  162. if(src->motion_subsample_log2 != dst->motion_subsample_log2)
  163. av_log(s->avctx, AV_LOG_ERROR, "AVFrame.motion_subsample_log2 doesn't match! (%d!=%d)\n",
  164. src->motion_subsample_log2, dst->motion_subsample_log2);
  165. memcpy(dst->mb_type, src->mb_type, s->mb_stride * s->mb_height * sizeof(dst->mb_type[0]));
  166. for(i=0; i<2; i++){
  167. int stride= ((16*s->mb_width )>>src->motion_subsample_log2) + 1;
  168. int height= ((16*s->mb_height)>>src->motion_subsample_log2);
  169. if(src->motion_val[i] && src->motion_val[i] != dst->motion_val[i]){
  170. memcpy(dst->motion_val[i], src->motion_val[i], 2*stride*height*sizeof(int16_t));
  171. }
  172. if(src->ref_index[i] && src->ref_index[i] != dst->ref_index[i]){
  173. memcpy(dst->ref_index[i], src->ref_index[i], s->b8_stride*2*s->mb_height*sizeof(int8_t));
  174. }
  175. }
  176. }
  177. }
  178. static void update_duplicate_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  179. #define COPY(a) dst->a= src->a
  180. COPY(pict_type);
  181. COPY(current_picture);
  182. COPY(f_code);
  183. COPY(b_code);
  184. COPY(qscale);
  185. COPY(lambda);
  186. COPY(lambda2);
  187. COPY(picture_in_gop_number);
  188. COPY(gop_picture_number);
  189. COPY(frame_pred_frame_dct); //FIXME don't set in encode_header
  190. COPY(progressive_frame); //FIXME don't set in encode_header
  191. COPY(partitioned_frame); //FIXME don't set in encode_header
  192. #undef COPY
  193. }
  194. /**
  195. * sets the given MpegEncContext to defaults for encoding.
  196. * the changed fields will not depend upon the prior state of the MpegEncContext.
  197. */
  198. static void MPV_encode_defaults(MpegEncContext *s){
  199. int i;
  200. MPV_common_defaults(s);
  201. for(i=-16; i<16; i++){
  202. default_fcode_tab[i + MAX_MV]= 1;
  203. }
  204. s->me.mv_penalty= default_mv_penalty;
  205. s->fcode_tab= default_fcode_tab;
  206. }
  207. /* init video encoder */
  208. av_cold int MPV_encode_init(AVCodecContext *avctx)
  209. {
  210. MpegEncContext *s = avctx->priv_data;
  211. int i;
  212. int chroma_h_shift, chroma_v_shift;
  213. MPV_encode_defaults(s);
  214. switch (avctx->codec_id) {
  215. case CODEC_ID_MPEG2VIDEO:
  216. if(avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P){
  217. av_log(avctx, AV_LOG_ERROR, "only YUV420 and YUV422 are supported\n");
  218. return -1;
  219. }
  220. break;
  221. case CODEC_ID_LJPEG:
  222. case CODEC_ID_MJPEG:
  223. if(avctx->pix_fmt != PIX_FMT_YUVJ420P && avctx->pix_fmt != PIX_FMT_YUVJ422P && avctx->pix_fmt != PIX_FMT_RGB32 &&
  224. ((avctx->pix_fmt != PIX_FMT_YUV420P && avctx->pix_fmt != PIX_FMT_YUV422P) || avctx->strict_std_compliance>FF_COMPLIANCE_INOFFICIAL)){
  225. av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
  226. return -1;
  227. }
  228. break;
  229. default:
  230. if(avctx->pix_fmt != PIX_FMT_YUV420P){
  231. av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
  232. return -1;
  233. }
  234. }
  235. switch (avctx->pix_fmt) {
  236. case PIX_FMT_YUVJ422P:
  237. case PIX_FMT_YUV422P:
  238. s->chroma_format = CHROMA_422;
  239. break;
  240. case PIX_FMT_YUVJ420P:
  241. case PIX_FMT_YUV420P:
  242. default:
  243. s->chroma_format = CHROMA_420;
  244. break;
  245. }
  246. s->bit_rate = avctx->bit_rate;
  247. s->width = avctx->width;
  248. s->height = avctx->height;
  249. if(avctx->gop_size > 600 && avctx->strict_std_compliance>FF_COMPLIANCE_EXPERIMENTAL){
  250. av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
  251. avctx->gop_size=600;
  252. }
  253. s->gop_size = avctx->gop_size;
  254. s->avctx = avctx;
  255. s->flags= avctx->flags;
  256. s->flags2= avctx->flags2;
  257. s->max_b_frames= avctx->max_b_frames;
  258. s->codec_id= avctx->codec->id;
  259. s->luma_elim_threshold = avctx->luma_elim_threshold;
  260. s->chroma_elim_threshold= avctx->chroma_elim_threshold;
  261. s->strict_std_compliance= avctx->strict_std_compliance;
  262. s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
  263. s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
  264. s->mpeg_quant= avctx->mpeg_quant;
  265. s->rtp_mode= !!avctx->rtp_payload_size;
  266. s->intra_dc_precision= avctx->intra_dc_precision;
  267. s->user_specified_pts = AV_NOPTS_VALUE;
  268. if (s->gop_size <= 1) {
  269. s->intra_only = 1;
  270. s->gop_size = 12;
  271. } else {
  272. s->intra_only = 0;
  273. }
  274. s->me_method = avctx->me_method;
  275. /* Fixed QSCALE */
  276. s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
  277. s->adaptive_quant= ( s->avctx->lumi_masking
  278. || s->avctx->dark_masking
  279. || s->avctx->temporal_cplx_masking
  280. || s->avctx->spatial_cplx_masking
  281. || s->avctx->p_masking
  282. || s->avctx->border_masking
  283. || (s->flags&CODEC_FLAG_QP_RD))
  284. && !s->fixed_qscale;
  285. s->obmc= !!(s->flags & CODEC_FLAG_OBMC);
  286. s->loop_filter= !!(s->flags & CODEC_FLAG_LOOP_FILTER);
  287. s->alternate_scan= !!(s->flags & CODEC_FLAG_ALT_SCAN);
  288. s->intra_vlc_format= !!(s->flags2 & CODEC_FLAG2_INTRA_VLC);
  289. s->q_scale_type= !!(s->flags2 & CODEC_FLAG2_NON_LINEAR_QUANT);
  290. if(avctx->rc_max_rate && !avctx->rc_buffer_size){
  291. av_log(avctx, AV_LOG_ERROR, "a vbv buffer size is needed, for encoding with a maximum bitrate\n");
  292. return -1;
  293. }
  294. if(avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate){
  295. av_log(avctx, AV_LOG_INFO, "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
  296. }
  297. if(avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate){
  298. av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
  299. return -1;
  300. }
  301. if(avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate){
  302. av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
  303. return -1;
  304. }
  305. if(avctx->rc_max_rate && avctx->rc_max_rate == avctx->bit_rate && avctx->rc_max_rate != avctx->rc_min_rate){
  306. av_log(avctx, AV_LOG_INFO, "impossible bitrate constraints, this will fail\n");
  307. }
  308. if(avctx->rc_buffer_size && avctx->bit_rate*av_q2d(avctx->time_base) > avctx->rc_buffer_size){
  309. av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
  310. return -1;
  311. }
  312. if(avctx->bit_rate*av_q2d(avctx->time_base) > avctx->bit_rate_tolerance){
  313. av_log(avctx, AV_LOG_ERROR, "bitrate tolerance too small for bitrate\n");
  314. return -1;
  315. }
  316. if( s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate
  317. && (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO)
  318. && 90000LL * (avctx->rc_buffer_size-1) > s->avctx->rc_max_rate*0xFFFFLL){
  319. av_log(avctx, AV_LOG_INFO, "Warning vbv_delay will be set to 0xFFFF (=VBR) as the specified vbv buffer is too large for the given bitrate!\n");
  320. }
  321. if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4
  322. && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P && s->codec_id != CODEC_ID_FLV1){
  323. av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
  324. return -1;
  325. }
  326. if(s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE){
  327. av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with simple mb decision\n");
  328. return -1;
  329. }
  330. if(s->obmc && s->codec_id != CODEC_ID_H263 && s->codec_id != CODEC_ID_H263P){
  331. av_log(avctx, AV_LOG_ERROR, "OBMC is only supported with H263(+)\n");
  332. return -1;
  333. }
  334. if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
  335. av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
  336. return -1;
  337. }
  338. if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
  339. av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
  340. return -1;
  341. }
  342. if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
  343. av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
  344. return -1;
  345. }
  346. if ((s->codec_id == CODEC_ID_MPEG4 || s->codec_id == CODEC_ID_H263 ||
  347. s->codec_id == CODEC_ID_H263P) &&
  348. (avctx->sample_aspect_ratio.num > 255 || avctx->sample_aspect_ratio.den > 255)) {
  349. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
  350. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  351. return -1;
  352. }
  353. if((s->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN))
  354. && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG2VIDEO){
  355. av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
  356. return -1;
  357. }
  358. if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
  359. av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supported by codec\n");
  360. return -1;
  361. }
  362. if((s->flags & CODEC_FLAG_CBP_RD) && !avctx->trellis){
  363. av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
  364. return -1;
  365. }
  366. if((s->flags & CODEC_FLAG_QP_RD) && s->avctx->mb_decision != FF_MB_DECISION_RD){
  367. av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
  368. return -1;
  369. }
  370. if(s->avctx->scenechange_threshold < 1000000000 && (s->flags & CODEC_FLAG_CLOSED_GOP)){
  371. av_log(avctx, AV_LOG_ERROR, "closed gop with scene change detection are not supported yet, set threshold to 1000000000\n");
  372. return -1;
  373. }
  374. if((s->flags2 & CODEC_FLAG2_INTRA_VLC) && s->codec_id != CODEC_ID_MPEG2VIDEO){
  375. av_log(avctx, AV_LOG_ERROR, "intra vlc table not supported by codec\n");
  376. return -1;
  377. }
  378. if(s->flags & CODEC_FLAG_LOW_DELAY){
  379. if (s->codec_id != CODEC_ID_MPEG2VIDEO){
  380. av_log(avctx, AV_LOG_ERROR, "low delay forcing is only available for mpeg2\n");
  381. return -1;
  382. }
  383. if (s->max_b_frames != 0){
  384. av_log(avctx, AV_LOG_ERROR, "b frames cannot be used with low delay\n");
  385. return -1;
  386. }
  387. }
  388. if(s->q_scale_type == 1){
  389. if(s->codec_id != CODEC_ID_MPEG2VIDEO){
  390. av_log(avctx, AV_LOG_ERROR, "non linear quant is only available for mpeg2\n");
  391. return -1;
  392. }
  393. if(avctx->qmax > 12){
  394. av_log(avctx, AV_LOG_ERROR, "non linear quant only supports qmax <= 12 currently\n");
  395. return -1;
  396. }
  397. }
  398. if(s->avctx->thread_count > 1 && s->codec_id != CODEC_ID_MPEG4
  399. && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO
  400. && (s->codec_id != CODEC_ID_H263P || !(s->flags & CODEC_FLAG_H263P_SLICE_STRUCT))){
  401. av_log(avctx, AV_LOG_ERROR, "multi threaded encoding not supported by codec\n");
  402. return -1;
  403. }
  404. if(s->avctx->thread_count < 1){
  405. av_log(avctx, AV_LOG_ERROR, "automatic thread number detection not supported by codec, patch welcome\n");
  406. return -1;
  407. }
  408. if(s->avctx->thread_count > 1)
  409. s->rtp_mode= 1;
  410. if(!avctx->time_base.den || !avctx->time_base.num){
  411. av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
  412. return -1;
  413. }
  414. i= (INT_MAX/2+128)>>8;
  415. if(avctx->me_threshold >= i){
  416. av_log(avctx, AV_LOG_ERROR, "me_threshold too large, max is %d\n", i - 1);
  417. return -1;
  418. }
  419. if(avctx->mb_threshold >= i){
  420. av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n", i - 1);
  421. return -1;
  422. }
  423. if(avctx->b_frame_strategy && (avctx->flags&CODEC_FLAG_PASS2)){
  424. av_log(avctx, AV_LOG_INFO, "notice: b_frame_strategy only affects the first pass\n");
  425. avctx->b_frame_strategy = 0;
  426. }
  427. i= av_gcd(avctx->time_base.den, avctx->time_base.num);
  428. if(i > 1){
  429. av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
  430. avctx->time_base.den /= i;
  431. avctx->time_base.num /= i;
  432. // return -1;
  433. }
  434. if(s->codec_id==CODEC_ID_MJPEG){
  435. s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x
  436. s->inter_quant_bias= 0;
  437. }else if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO){
  438. s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
  439. s->inter_quant_bias= 0;
  440. }else{
  441. s->intra_quant_bias=0;
  442. s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
  443. }
  444. if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
  445. s->intra_quant_bias= avctx->intra_quant_bias;
  446. if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
  447. s->inter_quant_bias= avctx->inter_quant_bias;
  448. avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
  449. if(avctx->codec_id == CODEC_ID_MPEG4 && s->avctx->time_base.den > (1<<16)-1){
  450. av_log(avctx, AV_LOG_ERROR, "timebase not supported by mpeg 4 standard\n");
  451. return -1;
  452. }
  453. s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
  454. switch(avctx->codec->id) {
  455. case CODEC_ID_MPEG1VIDEO:
  456. s->out_format = FMT_MPEG1;
  457. s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
  458. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  459. break;
  460. case CODEC_ID_MPEG2VIDEO:
  461. s->out_format = FMT_MPEG1;
  462. s->low_delay= !!(s->flags & CODEC_FLAG_LOW_DELAY);
  463. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  464. s->rtp_mode= 1;
  465. break;
  466. case CODEC_ID_LJPEG:
  467. case CODEC_ID_MJPEG:
  468. s->out_format = FMT_MJPEG;
  469. s->intra_only = 1; /* force intra only for jpeg */
  470. if(avctx->codec->id == CODEC_ID_LJPEG && avctx->pix_fmt == PIX_FMT_BGRA){
  471. s->mjpeg_vsample[0] = s->mjpeg_hsample[0] =
  472. s->mjpeg_vsample[1] = s->mjpeg_hsample[1] =
  473. s->mjpeg_vsample[2] = s->mjpeg_hsample[2] = 1;
  474. }else{
  475. s->mjpeg_vsample[0] = 2;
  476. s->mjpeg_vsample[1] = 2>>chroma_v_shift;
  477. s->mjpeg_vsample[2] = 2>>chroma_v_shift;
  478. s->mjpeg_hsample[0] = 2;
  479. s->mjpeg_hsample[1] = 2>>chroma_h_shift;
  480. s->mjpeg_hsample[2] = 2>>chroma_h_shift;
  481. }
  482. if (!(CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER)
  483. || ff_mjpeg_encode_init(s) < 0)
  484. return -1;
  485. avctx->delay=0;
  486. s->low_delay=1;
  487. break;
  488. case CODEC_ID_H261:
  489. if (!CONFIG_H261_ENCODER) return -1;
  490. if (ff_h261_get_picture_format(s->width, s->height) < 0) {
  491. av_log(avctx, AV_LOG_ERROR, "The specified picture size of %dx%d is not valid for the H.261 codec.\nValid sizes are 176x144, 352x288\n", s->width, s->height);
  492. return -1;
  493. }
  494. s->out_format = FMT_H261;
  495. avctx->delay=0;
  496. s->low_delay=1;
  497. break;
  498. case CODEC_ID_H263:
  499. if (!CONFIG_H263_ENCODER) return -1;
  500. if (ff_match_2uint16(h263_format, FF_ARRAY_ELEMS(h263_format), s->width, s->height) == 7) {
  501. av_log(avctx, AV_LOG_INFO, "The specified picture size of %dx%d is not valid for the H.263 codec.\nValid sizes are 128x96, 176x144, 352x288, 704x576, and 1408x1152. Try H.263+.\n", s->width, s->height);
  502. return -1;
  503. }
  504. s->out_format = FMT_H263;
  505. s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
  506. avctx->delay=0;
  507. s->low_delay=1;
  508. break;
  509. case CODEC_ID_H263P:
  510. s->out_format = FMT_H263;
  511. s->h263_plus = 1;
  512. /* Fx */
  513. s->umvplus = (avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
  514. s->h263_aic= (avctx->flags & CODEC_FLAG_AC_PRED) ? 1:0;
  515. s->modified_quant= s->h263_aic;
  516. s->alt_inter_vlc= (avctx->flags & CODEC_FLAG_H263P_AIV) ? 1:0;
  517. s->obmc= (avctx->flags & CODEC_FLAG_OBMC) ? 1:0;
  518. s->loop_filter= (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1:0;
  519. s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
  520. s->h263_slice_structured= (s->flags & CODEC_FLAG_H263P_SLICE_STRUCT) ? 1:0;
  521. /* /Fx */
  522. /* These are just to be sure */
  523. avctx->delay=0;
  524. s->low_delay=1;
  525. break;
  526. case CODEC_ID_FLV1:
  527. s->out_format = FMT_H263;
  528. s->h263_flv = 2; /* format = 1; 11-bit codes */
  529. s->unrestricted_mv = 1;
  530. s->rtp_mode=0; /* don't allow GOB */
  531. avctx->delay=0;
  532. s->low_delay=1;
  533. break;
  534. case CODEC_ID_RV10:
  535. s->out_format = FMT_H263;
  536. avctx->delay=0;
  537. s->low_delay=1;
  538. break;
  539. case CODEC_ID_RV20:
  540. s->out_format = FMT_H263;
  541. avctx->delay=0;
  542. s->low_delay=1;
  543. s->modified_quant=1;
  544. s->h263_aic=1;
  545. s->h263_plus=1;
  546. s->loop_filter=1;
  547. s->unrestricted_mv= s->obmc || s->loop_filter || s->umvplus;
  548. break;
  549. case CODEC_ID_MPEG4:
  550. s->out_format = FMT_H263;
  551. s->h263_pred = 1;
  552. s->unrestricted_mv = 1;
  553. s->low_delay= s->max_b_frames ? 0 : 1;
  554. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  555. break;
  556. case CODEC_ID_MSMPEG4V1:
  557. s->out_format = FMT_H263;
  558. s->h263_msmpeg4 = 1;
  559. s->h263_pred = 1;
  560. s->unrestricted_mv = 1;
  561. s->msmpeg4_version= 1;
  562. avctx->delay=0;
  563. s->low_delay=1;
  564. break;
  565. case CODEC_ID_MSMPEG4V2:
  566. s->out_format = FMT_H263;
  567. s->h263_msmpeg4 = 1;
  568. s->h263_pred = 1;
  569. s->unrestricted_mv = 1;
  570. s->msmpeg4_version= 2;
  571. avctx->delay=0;
  572. s->low_delay=1;
  573. break;
  574. case CODEC_ID_MSMPEG4V3:
  575. s->out_format = FMT_H263;
  576. s->h263_msmpeg4 = 1;
  577. s->h263_pred = 1;
  578. s->unrestricted_mv = 1;
  579. s->msmpeg4_version= 3;
  580. s->flipflop_rounding=1;
  581. avctx->delay=0;
  582. s->low_delay=1;
  583. break;
  584. case CODEC_ID_WMV1:
  585. s->out_format = FMT_H263;
  586. s->h263_msmpeg4 = 1;
  587. s->h263_pred = 1;
  588. s->unrestricted_mv = 1;
  589. s->msmpeg4_version= 4;
  590. s->flipflop_rounding=1;
  591. avctx->delay=0;
  592. s->low_delay=1;
  593. break;
  594. case CODEC_ID_WMV2:
  595. s->out_format = FMT_H263;
  596. s->h263_msmpeg4 = 1;
  597. s->h263_pred = 1;
  598. s->unrestricted_mv = 1;
  599. s->msmpeg4_version= 5;
  600. s->flipflop_rounding=1;
  601. avctx->delay=0;
  602. s->low_delay=1;
  603. break;
  604. default:
  605. return -1;
  606. }
  607. avctx->has_b_frames= !s->low_delay;
  608. s->encoding = 1;
  609. s->progressive_frame=
  610. s->progressive_sequence= !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME|CODEC_FLAG_ALT_SCAN));
  611. /* init */
  612. if (MPV_common_init(s) < 0)
  613. return -1;
  614. if(!s->dct_quantize)
  615. s->dct_quantize = dct_quantize_c;
  616. if(!s->denoise_dct)
  617. s->denoise_dct = denoise_dct_c;
  618. s->fast_dct_quantize = s->dct_quantize;
  619. if(avctx->trellis)
  620. s->dct_quantize = dct_quantize_trellis_c;
  621. if((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
  622. s->chroma_qscale_table= ff_h263_chroma_qscale_table;
  623. s->quant_precision=5;
  624. ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
  625. ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
  626. if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
  627. ff_h261_encode_init(s);
  628. if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  629. h263_encode_init(s);
  630. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  631. ff_msmpeg4_encode_init(s);
  632. if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  633. && s->out_format == FMT_MPEG1)
  634. ff_mpeg1_encode_init(s);
  635. /* init q matrix */
  636. for(i=0;i<64;i++) {
  637. int j= s->dsp.idct_permutation[i];
  638. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
  639. s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
  640. s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
  641. }else if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  642. s->intra_matrix[j] =
  643. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  644. }else
  645. { /* mpeg1/2 */
  646. s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
  647. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  648. }
  649. if(s->avctx->intra_matrix)
  650. s->intra_matrix[j] = s->avctx->intra_matrix[i];
  651. if(s->avctx->inter_matrix)
  652. s->inter_matrix[j] = s->avctx->inter_matrix[i];
  653. }
  654. /* precompute matrix */
  655. /* for mjpeg, we do include qscale in the matrix */
  656. if (s->out_format != FMT_MJPEG) {
  657. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  658. s->intra_matrix, s->intra_quant_bias, avctx->qmin, 31, 1);
  659. ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
  660. s->inter_matrix, s->inter_quant_bias, avctx->qmin, 31, 0);
  661. }
  662. if(ff_rate_control_init(s) < 0)
  663. return -1;
  664. return 0;
  665. }
  666. av_cold int MPV_encode_end(AVCodecContext *avctx)
  667. {
  668. MpegEncContext *s = avctx->priv_data;
  669. ff_rate_control_uninit(s);
  670. MPV_common_end(s);
  671. if ((CONFIG_MJPEG_ENCODER || CONFIG_LJPEG_ENCODER) && s->out_format == FMT_MJPEG)
  672. ff_mjpeg_encode_close(s);
  673. av_freep(&avctx->extradata);
  674. return 0;
  675. }
  676. static int get_sae(uint8_t *src, int ref, int stride){
  677. int x,y;
  678. int acc=0;
  679. for(y=0; y<16; y++){
  680. for(x=0; x<16; x++){
  681. acc+= FFABS(src[x+y*stride] - ref);
  682. }
  683. }
  684. return acc;
  685. }
  686. static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
  687. int x, y, w, h;
  688. int acc=0;
  689. w= s->width &~15;
  690. h= s->height&~15;
  691. for(y=0; y<h; y+=16){
  692. for(x=0; x<w; x+=16){
  693. int offset= x + y*stride;
  694. int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride, 16);
  695. int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
  696. int sae = get_sae(src + offset, mean, stride);
  697. acc+= sae + 500 < sad;
  698. }
  699. }
  700. return acc;
  701. }
  702. static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
  703. AVFrame *pic=NULL;
  704. int64_t pts;
  705. int i;
  706. const int encoding_delay= s->max_b_frames;
  707. int direct=1;
  708. if(pic_arg){
  709. pts= pic_arg->pts;
  710. pic_arg->display_picture_number= s->input_picture_number++;
  711. if(pts != AV_NOPTS_VALUE){
  712. if(s->user_specified_pts != AV_NOPTS_VALUE){
  713. int64_t time= pts;
  714. int64_t last= s->user_specified_pts;
  715. if(time <= last){
  716. av_log(s->avctx, AV_LOG_ERROR, "Error, Invalid timestamp=%"PRId64", last=%"PRId64"\n", pts, s->user_specified_pts);
  717. return -1;
  718. }
  719. }
  720. s->user_specified_pts= pts;
  721. }else{
  722. if(s->user_specified_pts != AV_NOPTS_VALUE){
  723. s->user_specified_pts=
  724. pts= s->user_specified_pts + 1;
  725. av_log(s->avctx, AV_LOG_INFO, "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n", pts);
  726. }else{
  727. pts= pic_arg->display_picture_number;
  728. }
  729. }
  730. }
  731. if(pic_arg){
  732. if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
  733. if(pic_arg->linesize[0] != s->linesize) direct=0;
  734. if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
  735. if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
  736. // av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
  737. if(direct){
  738. i= ff_find_unused_picture(s, 1);
  739. pic= (AVFrame*)&s->picture[i];
  740. pic->reference= 3;
  741. for(i=0; i<4; i++){
  742. pic->data[i]= pic_arg->data[i];
  743. pic->linesize[i]= pic_arg->linesize[i];
  744. }
  745. ff_alloc_picture(s, (Picture*)pic, 1);
  746. }else{
  747. i= ff_find_unused_picture(s, 0);
  748. pic= (AVFrame*)&s->picture[i];
  749. pic->reference= 3;
  750. ff_alloc_picture(s, (Picture*)pic, 0);
  751. if( pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
  752. && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
  753. && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
  754. // empty
  755. }else{
  756. int h_chroma_shift, v_chroma_shift;
  757. avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  758. for(i=0; i<3; i++){
  759. int src_stride= pic_arg->linesize[i];
  760. int dst_stride= i ? s->uvlinesize : s->linesize;
  761. int h_shift= i ? h_chroma_shift : 0;
  762. int v_shift= i ? v_chroma_shift : 0;
  763. int w= s->width >>h_shift;
  764. int h= s->height>>v_shift;
  765. uint8_t *src= pic_arg->data[i];
  766. uint8_t *dst= pic->data[i];
  767. if(!s->avctx->rc_buffer_size)
  768. dst +=INPLACE_OFFSET;
  769. if(src_stride==dst_stride)
  770. memcpy(dst, src, src_stride*h);
  771. else{
  772. while(h--){
  773. memcpy(dst, src, w);
  774. dst += dst_stride;
  775. src += src_stride;
  776. }
  777. }
  778. }
  779. }
  780. }
  781. copy_picture_attributes(s, pic, pic_arg);
  782. pic->pts= pts; //we set this here to avoid modifiying pic_arg
  783. }
  784. /* shift buffer entries */
  785. for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
  786. s->input_picture[i-1]= s->input_picture[i];
  787. s->input_picture[encoding_delay]= (Picture*)pic;
  788. return 0;
  789. }
  790. static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
  791. int x, y, plane;
  792. int score=0;
  793. int64_t score64=0;
  794. for(plane=0; plane<3; plane++){
  795. const int stride= p->linesize[plane];
  796. const int bw= plane ? 1 : 2;
  797. for(y=0; y<s->mb_height*bw; y++){
  798. for(x=0; x<s->mb_width*bw; x++){
  799. int off= p->type == FF_BUFFER_TYPE_SHARED ? 0: 16;
  800. int v= s->dsp.frame_skip_cmp[1](s, p->data[plane] + 8*(x + y*stride)+off, ref->data[plane] + 8*(x + y*stride), stride, 8);
  801. switch(s->avctx->frame_skip_exp){
  802. case 0: score= FFMAX(score, v); break;
  803. case 1: score+= FFABS(v);break;
  804. case 2: score+= v*v;break;
  805. case 3: score64+= FFABS(v*v*(int64_t)v);break;
  806. case 4: score64+= v*v*(int64_t)(v*v);break;
  807. }
  808. }
  809. }
  810. }
  811. if(score) score64= score;
  812. if(score64 < s->avctx->frame_skip_threshold)
  813. return 1;
  814. if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
  815. return 1;
  816. return 0;
  817. }
  818. static int estimate_best_b_count(MpegEncContext *s){
  819. AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
  820. AVCodecContext *c= avcodec_alloc_context();
  821. AVFrame input[FF_MAX_B_FRAMES+2];
  822. const int scale= s->avctx->brd_scale;
  823. int i, j, out_size, p_lambda, b_lambda, lambda2;
  824. int outbuf_size= s->width * s->height; //FIXME
  825. uint8_t *outbuf= av_malloc(outbuf_size);
  826. int64_t best_rd= INT64_MAX;
  827. int best_b_count= -1;
  828. assert(scale>=0 && scale <=3);
  829. // emms_c();
  830. p_lambda= s->last_lambda_for[FF_P_TYPE]; //s->next_picture_ptr->quality;
  831. b_lambda= s->last_lambda_for[FF_B_TYPE]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  832. if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
  833. lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
  834. c->width = s->width >> scale;
  835. c->height= s->height>> scale;
  836. c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
  837. c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
  838. c->mb_decision= s->avctx->mb_decision;
  839. c->me_cmp= s->avctx->me_cmp;
  840. c->mb_cmp= s->avctx->mb_cmp;
  841. c->me_sub_cmp= s->avctx->me_sub_cmp;
  842. c->pix_fmt = PIX_FMT_YUV420P;
  843. c->time_base= s->avctx->time_base;
  844. c->max_b_frames= s->max_b_frames;
  845. if (avcodec_open(c, codec) < 0)
  846. return -1;
  847. for(i=0; i<s->max_b_frames+2; i++){
  848. int ysize= c->width*c->height;
  849. int csize= (c->width/2)*(c->height/2);
  850. Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
  851. avcodec_get_frame_defaults(&input[i]);
  852. input[i].data[0]= av_malloc(ysize + 2*csize);
  853. input[i].data[1]= input[i].data[0] + ysize;
  854. input[i].data[2]= input[i].data[1] + csize;
  855. input[i].linesize[0]= c->width;
  856. input[i].linesize[1]=
  857. input[i].linesize[2]= c->width/2;
  858. if(pre_input_ptr && (!i || s->input_picture[i-1])) {
  859. pre_input= *pre_input_ptr;
  860. if(pre_input.type != FF_BUFFER_TYPE_SHARED && i) {
  861. pre_input.data[0]+=INPLACE_OFFSET;
  862. pre_input.data[1]+=INPLACE_OFFSET;
  863. pre_input.data[2]+=INPLACE_OFFSET;
  864. }
  865. s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0], pre_input.data[0], pre_input.linesize[0], c->width, c->height);
  866. s->dsp.shrink[scale](input[i].data[1], input[i].linesize[1], pre_input.data[1], pre_input.linesize[1], c->width>>1, c->height>>1);
  867. s->dsp.shrink[scale](input[i].data[2], input[i].linesize[2], pre_input.data[2], pre_input.linesize[2], c->width>>1, c->height>>1);
  868. }
  869. }
  870. for(j=0; j<s->max_b_frames+1; j++){
  871. int64_t rd=0;
  872. if(!s->input_picture[j])
  873. break;
  874. c->error[0]= c->error[1]= c->error[2]= 0;
  875. input[0].pict_type= FF_I_TYPE;
  876. input[0].quality= 1 * FF_QP2LAMBDA;
  877. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
  878. // rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  879. for(i=0; i<s->max_b_frames+1; i++){
  880. int is_p= i % (j+1) == j || i==s->max_b_frames;
  881. input[i+1].pict_type= is_p ? FF_P_TYPE : FF_B_TYPE;
  882. input[i+1].quality= is_p ? p_lambda : b_lambda;
  883. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
  884. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  885. }
  886. /* get the delayed frames */
  887. while(out_size){
  888. out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
  889. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  890. }
  891. rd += c->error[0] + c->error[1] + c->error[2];
  892. if(rd < best_rd){
  893. best_rd= rd;
  894. best_b_count= j;
  895. }
  896. }
  897. av_freep(&outbuf);
  898. avcodec_close(c);
  899. av_freep(&c);
  900. for(i=0; i<s->max_b_frames+2; i++){
  901. av_freep(&input[i].data[0]);
  902. }
  903. return best_b_count;
  904. }
  905. static void select_input_picture(MpegEncContext *s){
  906. int i;
  907. for(i=1; i<MAX_PICTURE_COUNT; i++)
  908. s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
  909. s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
  910. /* set next picture type & ordering */
  911. if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
  912. if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
  913. s->reordered_input_picture[0]= s->input_picture[0];
  914. s->reordered_input_picture[0]->pict_type= FF_I_TYPE;
  915. s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
  916. }else{
  917. int b_frames;
  918. if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
  919. if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
  920. //FIXME check that te gop check above is +-1 correct
  921. //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->data[0], s->input_picture[0]->pts);
  922. if(s->input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
  923. for(i=0; i<4; i++)
  924. s->input_picture[0]->data[i]= NULL;
  925. s->input_picture[0]->type= 0;
  926. }else{
  927. assert( s->input_picture[0]->type==FF_BUFFER_TYPE_USER
  928. || s->input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
  929. s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
  930. }
  931. emms_c();
  932. ff_vbv_update(s, 0);
  933. goto no_output_pic;
  934. }
  935. }
  936. if(s->flags&CODEC_FLAG_PASS2){
  937. for(i=0; i<s->max_b_frames+1; i++){
  938. int pict_num= s->input_picture[0]->display_picture_number + i;
  939. if(pict_num >= s->rc_context.num_entries)
  940. break;
  941. if(!s->input_picture[i]){
  942. s->rc_context.entry[pict_num-1].new_pict_type = FF_P_TYPE;
  943. break;
  944. }
  945. s->input_picture[i]->pict_type=
  946. s->rc_context.entry[pict_num].new_pict_type;
  947. }
  948. }
  949. if(s->avctx->b_frame_strategy==0){
  950. b_frames= s->max_b_frames;
  951. while(b_frames && !s->input_picture[b_frames]) b_frames--;
  952. }else if(s->avctx->b_frame_strategy==1){
  953. for(i=1; i<s->max_b_frames+1; i++){
  954. if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
  955. s->input_picture[i]->b_frame_score=
  956. get_intra_count(s, s->input_picture[i ]->data[0],
  957. s->input_picture[i-1]->data[0], s->linesize) + 1;
  958. }
  959. }
  960. for(i=0; i<s->max_b_frames+1; i++){
  961. if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
  962. }
  963. b_frames= FFMAX(0, i-1);
  964. /* reset scores */
  965. for(i=0; i<b_frames+1; i++){
  966. s->input_picture[i]->b_frame_score=0;
  967. }
  968. }else if(s->avctx->b_frame_strategy==2){
  969. b_frames= estimate_best_b_count(s);
  970. }else{
  971. av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  972. b_frames=0;
  973. }
  974. emms_c();
  975. //static int b_count=0;
  976. //b_count+= b_frames;
  977. //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
  978. for(i= b_frames - 1; i>=0; i--){
  979. int type= s->input_picture[i]->pict_type;
  980. if(type && type != FF_B_TYPE)
  981. b_frames= i;
  982. }
  983. if(s->input_picture[b_frames]->pict_type == FF_B_TYPE && b_frames == s->max_b_frames){
  984. av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
  985. }
  986. if(s->picture_in_gop_number + b_frames >= s->gop_size){
  987. if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
  988. b_frames= s->gop_size - s->picture_in_gop_number - 1;
  989. }else{
  990. if(s->flags & CODEC_FLAG_CLOSED_GOP)
  991. b_frames=0;
  992. s->input_picture[b_frames]->pict_type= FF_I_TYPE;
  993. }
  994. }
  995. if( (s->flags & CODEC_FLAG_CLOSED_GOP)
  996. && b_frames
  997. && s->input_picture[b_frames]->pict_type== FF_I_TYPE)
  998. b_frames--;
  999. s->reordered_input_picture[0]= s->input_picture[b_frames];
  1000. if(s->reordered_input_picture[0]->pict_type != FF_I_TYPE)
  1001. s->reordered_input_picture[0]->pict_type= FF_P_TYPE;
  1002. s->reordered_input_picture[0]->coded_picture_number= s->coded_picture_number++;
  1003. for(i=0; i<b_frames; i++){
  1004. s->reordered_input_picture[i+1]= s->input_picture[i];
  1005. s->reordered_input_picture[i+1]->pict_type= FF_B_TYPE;
  1006. s->reordered_input_picture[i+1]->coded_picture_number= s->coded_picture_number++;
  1007. }
  1008. }
  1009. }
  1010. no_output_pic:
  1011. if(s->reordered_input_picture[0]){
  1012. s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=FF_B_TYPE ? 3 : 0;
  1013. ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
  1014. if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size){
  1015. // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
  1016. int i= ff_find_unused_picture(s, 0);
  1017. Picture *pic= &s->picture[i];
  1018. pic->reference = s->reordered_input_picture[0]->reference;
  1019. ff_alloc_picture(s, pic, 0);
  1020. /* mark us unused / free shared pic */
  1021. if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_INTERNAL)
  1022. s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
  1023. for(i=0; i<4; i++)
  1024. s->reordered_input_picture[0]->data[i]= NULL;
  1025. s->reordered_input_picture[0]->type= 0;
  1026. copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
  1027. s->current_picture_ptr= pic;
  1028. }else{
  1029. // input is not a shared pix -> reuse buffer for current_pix
  1030. assert( s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
  1031. || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
  1032. s->current_picture_ptr= s->reordered_input_picture[0];
  1033. for(i=0; i<4; i++){
  1034. s->new_picture.data[i]+= INPLACE_OFFSET;
  1035. }
  1036. }
  1037. ff_copy_picture(&s->current_picture, s->current_picture_ptr);
  1038. s->picture_number= s->new_picture.display_picture_number;
  1039. //printf("dpn:%d\n", s->picture_number);
  1040. }else{
  1041. memset(&s->new_picture, 0, sizeof(Picture));
  1042. }
  1043. }
  1044. int MPV_encode_picture(AVCodecContext *avctx,
  1045. unsigned char *buf, int buf_size, void *data)
  1046. {
  1047. MpegEncContext *s = avctx->priv_data;
  1048. AVFrame *pic_arg = data;
  1049. int i, stuffing_count;
  1050. for(i=0; i<avctx->thread_count; i++){
  1051. int start_y= s->thread_context[i]->start_mb_y;
  1052. int end_y= s->thread_context[i]-> end_mb_y;
  1053. int h= s->mb_height;
  1054. uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
  1055. uint8_t *end = buf + (size_t)(((int64_t) buf_size)* end_y/h);
  1056. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1057. }
  1058. s->picture_in_gop_number++;
  1059. if(load_input_picture(s, pic_arg) < 0)
  1060. return -1;
  1061. select_input_picture(s);
  1062. /* output? */
  1063. if(s->new_picture.data[0]){
  1064. s->pict_type= s->new_picture.pict_type;
  1065. //emms_c();
  1066. //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
  1067. MPV_frame_start(s, avctx);
  1068. vbv_retry:
  1069. if (encode_picture(s, s->picture_number) < 0)
  1070. return -1;
  1071. avctx->header_bits = s->header_bits;
  1072. avctx->mv_bits = s->mv_bits;
  1073. avctx->misc_bits = s->misc_bits;
  1074. avctx->i_tex_bits = s->i_tex_bits;
  1075. avctx->p_tex_bits = s->p_tex_bits;
  1076. avctx->i_count = s->i_count;
  1077. avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
  1078. avctx->skip_count = s->skip_count;
  1079. MPV_frame_end(s);
  1080. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1081. ff_mjpeg_encode_picture_trailer(s);
  1082. if(avctx->rc_buffer_size){
  1083. RateControlContext *rcc= &s->rc_context;
  1084. int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1085. if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
  1086. s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
  1087. if(s->adaptive_quant){
  1088. int i;
  1089. for(i=0; i<s->mb_height*s->mb_stride; i++)
  1090. s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
  1091. }
  1092. s->mb_skipped = 0; //done in MPV_frame_start()
  1093. if(s->pict_type==FF_P_TYPE){ //done in encode_picture() so we must undo it
  1094. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  1095. s->no_rounding ^= 1;
  1096. }
  1097. if(s->pict_type!=FF_B_TYPE){
  1098. s->time_base= s->last_time_base;
  1099. s->last_non_b_time= s->time - s->pp_time;
  1100. }
  1101. // av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
  1102. for(i=0; i<avctx->thread_count; i++){
  1103. PutBitContext *pb= &s->thread_context[i]->pb;
  1104. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1105. }
  1106. goto vbv_retry;
  1107. }
  1108. assert(s->avctx->rc_max_rate);
  1109. }
  1110. if(s->flags&CODEC_FLAG_PASS1)
  1111. ff_write_pass1_stats(s);
  1112. for(i=0; i<4; i++){
  1113. s->current_picture_ptr->error[i]= s->current_picture.error[i];
  1114. avctx->error[i] += s->current_picture_ptr->error[i];
  1115. }
  1116. if(s->flags&CODEC_FLAG_PASS1)
  1117. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
  1118. flush_put_bits(&s->pb);
  1119. s->frame_bits = put_bits_count(&s->pb);
  1120. stuffing_count= ff_vbv_update(s, s->frame_bits);
  1121. if(stuffing_count){
  1122. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
  1123. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1124. return -1;
  1125. }
  1126. switch(s->codec_id){
  1127. case CODEC_ID_MPEG1VIDEO:
  1128. case CODEC_ID_MPEG2VIDEO:
  1129. while(stuffing_count--){
  1130. put_bits(&s->pb, 8, 0);
  1131. }
  1132. break;
  1133. case CODEC_ID_MPEG4:
  1134. put_bits(&s->pb, 16, 0);
  1135. put_bits(&s->pb, 16, 0x1C3);
  1136. stuffing_count -= 4;
  1137. while(stuffing_count--){
  1138. put_bits(&s->pb, 8, 0xFF);
  1139. }
  1140. break;
  1141. default:
  1142. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1143. }
  1144. flush_put_bits(&s->pb);
  1145. s->frame_bits = put_bits_count(&s->pb);
  1146. }
  1147. /* update mpeg1/2 vbv_delay for CBR */
  1148. if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
  1149. && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
  1150. int vbv_delay, min_delay;
  1151. double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
  1152. int minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
  1153. double bits = s->rc_context.buffer_index + minbits - inbits;
  1154. if(bits<0)
  1155. av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
  1156. assert(s->repeat_first_field==0);
  1157. vbv_delay= bits * 90000 / s->avctx->rc_max_rate;
  1158. min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
  1159. vbv_delay= FFMAX(vbv_delay, min_delay);
  1160. assert(vbv_delay < 0xFFFF);
  1161. s->vbv_delay_ptr[0] &= 0xF8;
  1162. s->vbv_delay_ptr[0] |= vbv_delay>>13;
  1163. s->vbv_delay_ptr[1] = vbv_delay>>5;
  1164. s->vbv_delay_ptr[2] &= 0x07;
  1165. s->vbv_delay_ptr[2] |= vbv_delay<<3;
  1166. }
  1167. s->total_bits += s->frame_bits;
  1168. avctx->frame_bits = s->frame_bits;
  1169. }else{
  1170. assert((put_bits_ptr(&s->pb) == s->pb.buf));
  1171. s->frame_bits=0;
  1172. }
  1173. assert((s->frame_bits&7)==0);
  1174. return s->frame_bits/8;
  1175. }
  1176. static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
  1177. {
  1178. static const char tab[64]=
  1179. {3,2,2,1,1,1,1,1,
  1180. 1,1,1,1,1,1,1,1,
  1181. 1,1,1,1,1,1,1,1,
  1182. 0,0,0,0,0,0,0,0,
  1183. 0,0,0,0,0,0,0,0,
  1184. 0,0,0,0,0,0,0,0,
  1185. 0,0,0,0,0,0,0,0,
  1186. 0,0,0,0,0,0,0,0};
  1187. int score=0;
  1188. int run=0;
  1189. int i;
  1190. DCTELEM *block= s->block[n];
  1191. const int last_index= s->block_last_index[n];
  1192. int skip_dc;
  1193. if(threshold<0){
  1194. skip_dc=0;
  1195. threshold= -threshold;
  1196. }else
  1197. skip_dc=1;
  1198. /* Are all we could set to zero already zero? */
  1199. if(last_index<=skip_dc - 1) return;
  1200. for(i=0; i<=last_index; i++){
  1201. const int j = s->intra_scantable.permutated[i];
  1202. const int level = FFABS(block[j]);
  1203. if(level==1){
  1204. if(skip_dc && i==0) continue;
  1205. score+= tab[run];
  1206. run=0;
  1207. }else if(level>1){
  1208. return;
  1209. }else{
  1210. run++;
  1211. }
  1212. }
  1213. if(score >= threshold) return;
  1214. for(i=skip_dc; i<=last_index; i++){
  1215. const int j = s->intra_scantable.permutated[i];
  1216. block[j]=0;
  1217. }
  1218. if(block[0]) s->block_last_index[n]= 0;
  1219. else s->block_last_index[n]= -1;
  1220. }
  1221. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
  1222. {
  1223. int i;
  1224. const int maxlevel= s->max_qcoeff;
  1225. const int minlevel= s->min_qcoeff;
  1226. int overflow=0;
  1227. if(s->mb_intra){
  1228. i=1; //skip clipping of intra dc
  1229. }else
  1230. i=0;
  1231. for(;i<=last_index; i++){
  1232. const int j= s->intra_scantable.permutated[i];
  1233. int level = block[j];
  1234. if (level>maxlevel){
  1235. level=maxlevel;
  1236. overflow++;
  1237. }else if(level<minlevel){
  1238. level=minlevel;
  1239. overflow++;
  1240. }
  1241. block[j]= level;
  1242. }
  1243. if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1244. av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
  1245. }
  1246. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
  1247. int x, y;
  1248. //FIXME optimize
  1249. for(y=0; y<8; y++){
  1250. for(x=0; x<8; x++){
  1251. int x2, y2;
  1252. int sum=0;
  1253. int sqr=0;
  1254. int count=0;
  1255. for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
  1256. for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
  1257. int v= ptr[x2 + y2*stride];
  1258. sum += v;
  1259. sqr += v*v;
  1260. count++;
  1261. }
  1262. }
  1263. weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
  1264. }
  1265. }
  1266. }
  1267. static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
  1268. {
  1269. int16_t weight[8][64];
  1270. DCTELEM orig[8][64];
  1271. const int mb_x= s->mb_x;
  1272. const int mb_y= s->mb_y;
  1273. int i;
  1274. int skip_dct[8];
  1275. int dct_offset = s->linesize*8; //default for progressive frames
  1276. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1277. int wrap_y, wrap_c;
  1278. for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
  1279. if(s->adaptive_quant){
  1280. const int last_qp= s->qscale;
  1281. const int mb_xy= mb_x + mb_y*s->mb_stride;
  1282. s->lambda= s->lambda_table[mb_xy];
  1283. update_qscale(s);
  1284. if(!(s->flags&CODEC_FLAG_QP_RD)){
  1285. s->qscale= s->current_picture_ptr->qscale_table[mb_xy];
  1286. s->dquant= s->qscale - last_qp;
  1287. if(s->out_format==FMT_H263){
  1288. s->dquant= av_clip(s->dquant, -2, 2);
  1289. if(s->codec_id==CODEC_ID_MPEG4){
  1290. if(!s->mb_intra){
  1291. if(s->pict_type == FF_B_TYPE){
  1292. if(s->dquant&1 || s->mv_dir&MV_DIRECT)
  1293. s->dquant= 0;
  1294. }
  1295. if(s->mv_type==MV_TYPE_8X8)
  1296. s->dquant=0;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. ff_set_qscale(s, last_qp + s->dquant);
  1302. }else if(s->flags&CODEC_FLAG_QP_RD)
  1303. ff_set_qscale(s, s->qscale + s->dquant);
  1304. wrap_y = s->linesize;
  1305. wrap_c = s->uvlinesize;
  1306. ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  1307. ptr_cb = s->new_picture.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1308. ptr_cr = s->new_picture.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1309. if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
  1310. uint8_t *ebuf= s->edge_emu_buffer + 32;
  1311. ff_emulated_edge_mc(ebuf , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width , s->height);
  1312. ptr_y= ebuf;
  1313. ff_emulated_edge_mc(ebuf+18*wrap_y , ptr_cb, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  1314. ptr_cb= ebuf+18*wrap_y;
  1315. ff_emulated_edge_mc(ebuf+18*wrap_y+8, ptr_cr, wrap_c, 8, mb_block_height, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  1316. ptr_cr= ebuf+18*wrap_y+8;
  1317. }
  1318. if (s->mb_intra) {
  1319. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1320. int progressive_score, interlaced_score;
  1321. s->interlaced_dct=0;
  1322. progressive_score= s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y, 8)
  1323. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
  1324. if(progressive_score > 0){
  1325. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y*2, 8)
  1326. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y , NULL, wrap_y*2, 8);
  1327. if(progressive_score > interlaced_score){
  1328. s->interlaced_dct=1;
  1329. dct_offset= wrap_y;
  1330. wrap_y<<=1;
  1331. if (s->chroma_format == CHROMA_422)
  1332. wrap_c<<=1;
  1333. }
  1334. }
  1335. }
  1336. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1337. s->dsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
  1338. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1339. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  1340. if(s->flags&CODEC_FLAG_GRAY){
  1341. skip_dct[4]= 1;
  1342. skip_dct[5]= 1;
  1343. }else{
  1344. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1345. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1346. if(!s->chroma_y_shift){ /* 422 */
  1347. s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
  1348. s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
  1349. }
  1350. }
  1351. }else{
  1352. op_pixels_func (*op_pix)[4];
  1353. qpel_mc_func (*op_qpix)[16];
  1354. uint8_t *dest_y, *dest_cb, *dest_cr;
  1355. dest_y = s->dest[0];
  1356. dest_cb = s->dest[1];
  1357. dest_cr = s->dest[2];
  1358. if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){
  1359. op_pix = s->dsp.put_pixels_tab;
  1360. op_qpix= s->dsp.put_qpel_pixels_tab;
  1361. }else{
  1362. op_pix = s->dsp.put_no_rnd_pixels_tab;
  1363. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  1364. }
  1365. if (s->mv_dir & MV_DIR_FORWARD) {
  1366. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  1367. op_pix = s->dsp.avg_pixels_tab;
  1368. op_qpix= s->dsp.avg_qpel_pixels_tab;
  1369. }
  1370. if (s->mv_dir & MV_DIR_BACKWARD) {
  1371. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  1372. }
  1373. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1374. int progressive_score, interlaced_score;
  1375. s->interlaced_dct=0;
  1376. progressive_score= s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y, 8)
  1377. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
  1378. if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
  1379. if(progressive_score>0){
  1380. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y*2, 8)
  1381. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y , ptr_y + wrap_y , wrap_y*2, 8);
  1382. if(progressive_score > interlaced_score){
  1383. s->interlaced_dct=1;
  1384. dct_offset= wrap_y;
  1385. wrap_y<<=1;
  1386. if (s->chroma_format == CHROMA_422)
  1387. wrap_c<<=1;
  1388. }
  1389. }
  1390. }
  1391. s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
  1392. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1393. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
  1394. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
  1395. if(s->flags&CODEC_FLAG_GRAY){
  1396. skip_dct[4]= 1;
  1397. skip_dct[5]= 1;
  1398. }else{
  1399. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1400. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1401. if(!s->chroma_y_shift){ /* 422 */
  1402. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
  1403. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
  1404. }
  1405. }
  1406. /* pre quantization */
  1407. if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
  1408. //FIXME optimize
  1409. if(s->dsp.sad[1](NULL, ptr_y , dest_y , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
  1410. if(s->dsp.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
  1411. if(s->dsp.sad[1](NULL, ptr_y +dct_offset , dest_y +dct_offset , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
  1412. if(s->dsp.sad[1](NULL, ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y, 8) < 20*s->qscale) skip_dct[3]= 1;
  1413. if(s->dsp.sad[1](NULL, ptr_cb , dest_cb , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
  1414. if(s->dsp.sad[1](NULL, ptr_cr , dest_cr , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
  1415. if(!s->chroma_y_shift){ /* 422 */
  1416. if(s->dsp.sad[1](NULL, ptr_cb +(dct_offset>>1), dest_cb +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[6]= 1;
  1417. if(s->dsp.sad[1](NULL, ptr_cr +(dct_offset>>1), dest_cr +(dct_offset>>1), wrap_c, 8) < 20*s->qscale) skip_dct[7]= 1;
  1418. }
  1419. }
  1420. }
  1421. if(s->avctx->quantizer_noise_shaping){
  1422. if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y , wrap_y);
  1423. if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1424. if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1425. if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1426. if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb , wrap_c);
  1427. if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr , wrap_c);
  1428. if(!s->chroma_y_shift){ /* 422 */
  1429. if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
  1430. if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
  1431. }
  1432. memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
  1433. }
  1434. /* DCT & quantize */
  1435. assert(s->out_format!=FMT_MJPEG || s->qscale==8);
  1436. {
  1437. for(i=0;i<mb_block_count;i++) {
  1438. if(!skip_dct[i]){
  1439. int overflow;
  1440. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1441. // FIXME we could decide to change to quantizer instead of clipping
  1442. // JS: I don't think that would be a good idea it could lower quality instead
  1443. // of improve it. Just INTRADC clipping deserves changes in quantizer
  1444. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1445. }else
  1446. s->block_last_index[i]= -1;
  1447. }
  1448. if(s->avctx->quantizer_noise_shaping){
  1449. for(i=0;i<mb_block_count;i++) {
  1450. if(!skip_dct[i]){
  1451. s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
  1452. }
  1453. }
  1454. }
  1455. if(s->luma_elim_threshold && !s->mb_intra)
  1456. for(i=0; i<4; i++)
  1457. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1458. if(s->chroma_elim_threshold && !s->mb_intra)
  1459. for(i=4; i<mb_block_count; i++)
  1460. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1461. if(s->flags & CODEC_FLAG_CBP_RD){
  1462. for(i=0;i<mb_block_count;i++) {
  1463. if(s->block_last_index[i] == -1)
  1464. s->coded_score[i]= INT_MAX/256;
  1465. }
  1466. }
  1467. }
  1468. if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
  1469. s->block_last_index[4]=
  1470. s->block_last_index[5]= 0;
  1471. s->block[4][0]=
  1472. s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
  1473. }
  1474. //non c quantize code returns incorrect block_last_index FIXME
  1475. if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
  1476. for(i=0; i<mb_block_count; i++){
  1477. int j;
  1478. if(s->block_last_index[i]>0){
  1479. for(j=63; j>0; j--){
  1480. if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
  1481. }
  1482. s->block_last_index[i]= j;
  1483. }
  1484. }
  1485. }
  1486. /* huffman encode */
  1487. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1488. case CODEC_ID_MPEG1VIDEO:
  1489. case CODEC_ID_MPEG2VIDEO:
  1490. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1491. mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1492. break;
  1493. case CODEC_ID_MPEG4:
  1494. if (CONFIG_MPEG4_ENCODER)
  1495. mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1496. break;
  1497. case CODEC_ID_MSMPEG4V2:
  1498. case CODEC_ID_MSMPEG4V3:
  1499. case CODEC_ID_WMV1:
  1500. if (CONFIG_MSMPEG4_ENCODER)
  1501. msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1502. break;
  1503. case CODEC_ID_WMV2:
  1504. if (CONFIG_WMV2_ENCODER)
  1505. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1506. break;
  1507. case CODEC_ID_H261:
  1508. if (CONFIG_H261_ENCODER)
  1509. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1510. break;
  1511. case CODEC_ID_H263:
  1512. case CODEC_ID_H263P:
  1513. case CODEC_ID_FLV1:
  1514. case CODEC_ID_RV10:
  1515. case CODEC_ID_RV20:
  1516. if (CONFIG_H263_ENCODER)
  1517. h263_encode_mb(s, s->block, motion_x, motion_y);
  1518. break;
  1519. case CODEC_ID_MJPEG:
  1520. if (CONFIG_MJPEG_ENCODER)
  1521. ff_mjpeg_encode_mb(s, s->block);
  1522. break;
  1523. default:
  1524. assert(0);
  1525. }
  1526. }
  1527. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1528. {
  1529. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1530. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1531. }
  1532. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1533. int i;
  1534. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1535. /* mpeg1 */
  1536. d->mb_skip_run= s->mb_skip_run;
  1537. for(i=0; i<3; i++)
  1538. d->last_dc[i]= s->last_dc[i];
  1539. /* statistics */
  1540. d->mv_bits= s->mv_bits;
  1541. d->i_tex_bits= s->i_tex_bits;
  1542. d->p_tex_bits= s->p_tex_bits;
  1543. d->i_count= s->i_count;
  1544. d->f_count= s->f_count;
  1545. d->b_count= s->b_count;
  1546. d->skip_count= s->skip_count;
  1547. d->misc_bits= s->misc_bits;
  1548. d->last_bits= 0;
  1549. d->mb_skipped= 0;
  1550. d->qscale= s->qscale;
  1551. d->dquant= s->dquant;
  1552. d->esc3_level_length= s->esc3_level_length;
  1553. }
  1554. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1555. int i;
  1556. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1557. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  1558. /* mpeg1 */
  1559. d->mb_skip_run= s->mb_skip_run;
  1560. for(i=0; i<3; i++)
  1561. d->last_dc[i]= s->last_dc[i];
  1562. /* statistics */
  1563. d->mv_bits= s->mv_bits;
  1564. d->i_tex_bits= s->i_tex_bits;
  1565. d->p_tex_bits= s->p_tex_bits;
  1566. d->i_count= s->i_count;
  1567. d->f_count= s->f_count;
  1568. d->b_count= s->b_count;
  1569. d->skip_count= s->skip_count;
  1570. d->misc_bits= s->misc_bits;
  1571. d->mb_intra= s->mb_intra;
  1572. d->mb_skipped= s->mb_skipped;
  1573. d->mv_type= s->mv_type;
  1574. d->mv_dir= s->mv_dir;
  1575. d->pb= s->pb;
  1576. if(s->data_partitioning){
  1577. d->pb2= s->pb2;
  1578. d->tex_pb= s->tex_pb;
  1579. }
  1580. d->block= s->block;
  1581. for(i=0; i<8; i++)
  1582. d->block_last_index[i]= s->block_last_index[i];
  1583. d->interlaced_dct= s->interlaced_dct;
  1584. d->qscale= s->qscale;
  1585. d->esc3_level_length= s->esc3_level_length;
  1586. }
  1587. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1588. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1589. int *dmin, int *next_block, int motion_x, int motion_y)
  1590. {
  1591. int score;
  1592. uint8_t *dest_backup[3];
  1593. copy_context_before_encode(s, backup, type);
  1594. s->block= s->blocks[*next_block];
  1595. s->pb= pb[*next_block];
  1596. if(s->data_partitioning){
  1597. s->pb2 = pb2 [*next_block];
  1598. s->tex_pb= tex_pb[*next_block];
  1599. }
  1600. if(*next_block){
  1601. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1602. s->dest[0] = s->rd_scratchpad;
  1603. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1604. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1605. assert(s->linesize >= 32); //FIXME
  1606. }
  1607. encode_mb(s, motion_x, motion_y);
  1608. score= put_bits_count(&s->pb);
  1609. if(s->data_partitioning){
  1610. score+= put_bits_count(&s->pb2);
  1611. score+= put_bits_count(&s->tex_pb);
  1612. }
  1613. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1614. MPV_decode_mb(s, s->block);
  1615. score *= s->lambda2;
  1616. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1617. }
  1618. if(*next_block){
  1619. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1620. }
  1621. if(score<*dmin){
  1622. *dmin= score;
  1623. *next_block^=1;
  1624. copy_context_after_encode(best, s, type);
  1625. }
  1626. }
  1627. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1628. uint32_t *sq = ff_squareTbl + 256;
  1629. int acc=0;
  1630. int x,y;
  1631. if(w==16 && h==16)
  1632. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  1633. else if(w==8 && h==8)
  1634. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  1635. for(y=0; y<h; y++){
  1636. for(x=0; x<w; x++){
  1637. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  1638. }
  1639. }
  1640. assert(acc>=0);
  1641. return acc;
  1642. }
  1643. static int sse_mb(MpegEncContext *s){
  1644. int w= 16;
  1645. int h= 16;
  1646. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  1647. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  1648. if(w==16 && h==16)
  1649. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  1650. return s->dsp.nsse[0](s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
  1651. +s->dsp.nsse[1](s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
  1652. +s->dsp.nsse[1](s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
  1653. }else{
  1654. return s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)
  1655. +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)
  1656. +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);
  1657. }
  1658. else
  1659. return sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
  1660. +sse(s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
  1661. +sse(s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
  1662. }
  1663. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  1664. MpegEncContext *s= *(void**)arg;
  1665. s->me.pre_pass=1;
  1666. s->me.dia_size= s->avctx->pre_dia_size;
  1667. s->first_slice_line=1;
  1668. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  1669. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  1670. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1671. }
  1672. s->first_slice_line=0;
  1673. }
  1674. s->me.pre_pass=0;
  1675. return 0;
  1676. }
  1677. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  1678. MpegEncContext *s= *(void**)arg;
  1679. ff_check_alignment();
  1680. s->me.dia_size= s->avctx->dia_size;
  1681. s->first_slice_line=1;
  1682. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  1683. s->mb_x=0; //for block init below
  1684. ff_init_block_index(s);
  1685. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  1686. s->block_index[0]+=2;
  1687. s->block_index[1]+=2;
  1688. s->block_index[2]+=2;
  1689. s->block_index[3]+=2;
  1690. /* compute motion vector & mb_type and store in context */
  1691. if(s->pict_type==FF_B_TYPE)
  1692. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  1693. else
  1694. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1695. }
  1696. s->first_slice_line=0;
  1697. }
  1698. return 0;
  1699. }
  1700. static int mb_var_thread(AVCodecContext *c, void *arg){
  1701. MpegEncContext *s= *(void**)arg;
  1702. int mb_x, mb_y;
  1703. ff_check_alignment();
  1704. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1705. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1706. int xx = mb_x * 16;
  1707. int yy = mb_y * 16;
  1708. uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
  1709. int varc;
  1710. int sum = s->dsp.pix_sum(pix, s->linesize);
  1711. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
  1712. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  1713. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  1714. s->me.mb_var_sum_temp += varc;
  1715. }
  1716. }
  1717. return 0;
  1718. }
  1719. static void write_slice_end(MpegEncContext *s){
  1720. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
  1721. if(s->partitioned_frame){
  1722. ff_mpeg4_merge_partitions(s);
  1723. }
  1724. ff_mpeg4_stuffing(&s->pb);
  1725. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  1726. ff_mjpeg_encode_stuffing(&s->pb);
  1727. }
  1728. align_put_bits(&s->pb);
  1729. flush_put_bits(&s->pb);
  1730. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  1731. s->misc_bits+= get_bits_diff(s);
  1732. }
  1733. static int encode_thread(AVCodecContext *c, void *arg){
  1734. MpegEncContext *s= *(void**)arg;
  1735. int mb_x, mb_y, pdif = 0;
  1736. int chr_h= 16>>s->chroma_y_shift;
  1737. int i, j;
  1738. MpegEncContext best_s, backup_s;
  1739. uint8_t bit_buf[2][MAX_MB_BYTES];
  1740. uint8_t bit_buf2[2][MAX_MB_BYTES];
  1741. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  1742. PutBitContext pb[2], pb2[2], tex_pb[2];
  1743. //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
  1744. ff_check_alignment();
  1745. for(i=0; i<2; i++){
  1746. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  1747. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  1748. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  1749. }
  1750. s->last_bits= put_bits_count(&s->pb);
  1751. s->mv_bits=0;
  1752. s->misc_bits=0;
  1753. s->i_tex_bits=0;
  1754. s->p_tex_bits=0;
  1755. s->i_count=0;
  1756. s->f_count=0;
  1757. s->b_count=0;
  1758. s->skip_count=0;
  1759. for(i=0; i<3; i++){
  1760. /* init last dc values */
  1761. /* note: quant matrix value (8) is implied here */
  1762. s->last_dc[i] = 128 << s->intra_dc_precision;
  1763. s->current_picture.error[i] = 0;
  1764. }
  1765. s->mb_skip_run = 0;
  1766. memset(s->last_mv, 0, sizeof(s->last_mv));
  1767. s->last_mv_dir = 0;
  1768. switch(s->codec_id){
  1769. case CODEC_ID_H263:
  1770. case CODEC_ID_H263P:
  1771. case CODEC_ID_FLV1:
  1772. if (CONFIG_H263_ENCODER)
  1773. s->gob_index = ff_h263_get_gob_height(s);
  1774. break;
  1775. case CODEC_ID_MPEG4:
  1776. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  1777. ff_mpeg4_init_partitions(s);
  1778. break;
  1779. }
  1780. s->resync_mb_x=0;
  1781. s->resync_mb_y=0;
  1782. s->first_slice_line = 1;
  1783. s->ptr_lastgob = s->pb.buf;
  1784. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1785. // printf("row %d at %X\n", s->mb_y, (int)s);
  1786. s->mb_x=0;
  1787. s->mb_y= mb_y;
  1788. ff_set_qscale(s, s->qscale);
  1789. ff_init_block_index(s);
  1790. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1791. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  1792. int mb_type= s->mb_type[xy];
  1793. // int d;
  1794. int dmin= INT_MAX;
  1795. int dir;
  1796. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  1797. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1798. return -1;
  1799. }
  1800. if(s->data_partitioning){
  1801. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  1802. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  1803. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1804. return -1;
  1805. }
  1806. }
  1807. s->mb_x = mb_x;
  1808. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  1809. ff_update_block_index(s);
  1810. if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
  1811. ff_h261_reorder_mb_index(s);
  1812. xy= s->mb_y*s->mb_stride + s->mb_x;
  1813. mb_type= s->mb_type[xy];
  1814. }
  1815. /* write gob / video packet header */
  1816. if(s->rtp_mode){
  1817. int current_packet_size, is_gob_start;
  1818. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  1819. is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  1820. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  1821. switch(s->codec_id){
  1822. case CODEC_ID_H263:
  1823. case CODEC_ID_H263P:
  1824. if(!s->h263_slice_structured)
  1825. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  1826. break;
  1827. case CODEC_ID_MPEG2VIDEO:
  1828. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  1829. case CODEC_ID_MPEG1VIDEO:
  1830. if(s->mb_skip_run) is_gob_start=0;
  1831. break;
  1832. }
  1833. if(is_gob_start){
  1834. if(s->start_mb_y != mb_y || mb_x!=0){
  1835. write_slice_end(s);
  1836. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
  1837. ff_mpeg4_init_partitions(s);
  1838. }
  1839. }
  1840. assert((put_bits_count(&s->pb)&7) == 0);
  1841. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  1842. if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
  1843. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  1844. int d= 100 / s->avctx->error_rate;
  1845. if(r % d == 0){
  1846. current_packet_size=0;
  1847. #ifndef ALT_BITSTREAM_WRITER
  1848. s->pb.buf_ptr= s->ptr_lastgob;
  1849. #endif
  1850. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  1851. }
  1852. }
  1853. if (s->avctx->rtp_callback){
  1854. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  1855. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  1856. }
  1857. switch(s->codec_id){
  1858. case CODEC_ID_MPEG4:
  1859. if (CONFIG_MPEG4_ENCODER) {
  1860. ff_mpeg4_encode_video_packet_header(s);
  1861. ff_mpeg4_clean_buffers(s);
  1862. }
  1863. break;
  1864. case CODEC_ID_MPEG1VIDEO:
  1865. case CODEC_ID_MPEG2VIDEO:
  1866. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  1867. ff_mpeg1_encode_slice_header(s);
  1868. ff_mpeg1_clean_buffers(s);
  1869. }
  1870. break;
  1871. case CODEC_ID_H263:
  1872. case CODEC_ID_H263P:
  1873. if (CONFIG_H263_ENCODER)
  1874. h263_encode_gob_header(s, mb_y);
  1875. break;
  1876. }
  1877. if(s->flags&CODEC_FLAG_PASS1){
  1878. int bits= put_bits_count(&s->pb);
  1879. s->misc_bits+= bits - s->last_bits;
  1880. s->last_bits= bits;
  1881. }
  1882. s->ptr_lastgob += current_packet_size;
  1883. s->first_slice_line=1;
  1884. s->resync_mb_x=mb_x;
  1885. s->resync_mb_y=mb_y;
  1886. }
  1887. }
  1888. if( (s->resync_mb_x == s->mb_x)
  1889. && s->resync_mb_y+1 == s->mb_y){
  1890. s->first_slice_line=0;
  1891. }
  1892. s->mb_skipped=0;
  1893. s->dquant=0; //only for QP_RD
  1894. if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
  1895. int next_block=0;
  1896. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  1897. copy_context_before_encode(&backup_s, s, -1);
  1898. backup_s.pb= s->pb;
  1899. best_s.data_partitioning= s->data_partitioning;
  1900. best_s.partitioned_frame= s->partitioned_frame;
  1901. if(s->data_partitioning){
  1902. backup_s.pb2= s->pb2;
  1903. backup_s.tex_pb= s->tex_pb;
  1904. }
  1905. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  1906. s->mv_dir = MV_DIR_FORWARD;
  1907. s->mv_type = MV_TYPE_16X16;
  1908. s->mb_intra= 0;
  1909. s->mv[0][0][0] = s->p_mv_table[xy][0];
  1910. s->mv[0][0][1] = s->p_mv_table[xy][1];
  1911. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  1912. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1913. }
  1914. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  1915. s->mv_dir = MV_DIR_FORWARD;
  1916. s->mv_type = MV_TYPE_FIELD;
  1917. s->mb_intra= 0;
  1918. for(i=0; i<2; i++){
  1919. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  1920. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  1921. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  1922. }
  1923. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  1924. &dmin, &next_block, 0, 0);
  1925. }
  1926. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  1927. s->mv_dir = MV_DIR_FORWARD;
  1928. s->mv_type = MV_TYPE_16X16;
  1929. s->mb_intra= 0;
  1930. s->mv[0][0][0] = 0;
  1931. s->mv[0][0][1] = 0;
  1932. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  1933. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1934. }
  1935. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  1936. s->mv_dir = MV_DIR_FORWARD;
  1937. s->mv_type = MV_TYPE_8X8;
  1938. s->mb_intra= 0;
  1939. for(i=0; i<4; i++){
  1940. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  1941. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  1942. }
  1943. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  1944. &dmin, &next_block, 0, 0);
  1945. }
  1946. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  1947. s->mv_dir = MV_DIR_FORWARD;
  1948. s->mv_type = MV_TYPE_16X16;
  1949. s->mb_intra= 0;
  1950. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  1951. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  1952. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  1953. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1954. }
  1955. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  1956. s->mv_dir = MV_DIR_BACKWARD;
  1957. s->mv_type = MV_TYPE_16X16;
  1958. s->mb_intra= 0;
  1959. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  1960. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  1961. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  1962. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  1963. }
  1964. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  1965. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  1966. s->mv_type = MV_TYPE_16X16;
  1967. s->mb_intra= 0;
  1968. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  1969. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  1970. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  1971. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  1972. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  1973. &dmin, &next_block, 0, 0);
  1974. }
  1975. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  1976. s->mv_dir = MV_DIR_FORWARD;
  1977. s->mv_type = MV_TYPE_FIELD;
  1978. s->mb_intra= 0;
  1979. for(i=0; i<2; i++){
  1980. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  1981. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  1982. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  1983. }
  1984. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  1985. &dmin, &next_block, 0, 0);
  1986. }
  1987. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  1988. s->mv_dir = MV_DIR_BACKWARD;
  1989. s->mv_type = MV_TYPE_FIELD;
  1990. s->mb_intra= 0;
  1991. for(i=0; i<2; i++){
  1992. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  1993. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  1994. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  1995. }
  1996. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  1997. &dmin, &next_block, 0, 0);
  1998. }
  1999. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  2000. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2001. s->mv_type = MV_TYPE_FIELD;
  2002. s->mb_intra= 0;
  2003. for(dir=0; dir<2; dir++){
  2004. for(i=0; i<2; i++){
  2005. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2006. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2007. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2008. }
  2009. }
  2010. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  2011. &dmin, &next_block, 0, 0);
  2012. }
  2013. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  2014. s->mv_dir = 0;
  2015. s->mv_type = MV_TYPE_16X16;
  2016. s->mb_intra= 1;
  2017. s->mv[0][0][0] = 0;
  2018. s->mv[0][0][1] = 0;
  2019. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  2020. &dmin, &next_block, 0, 0);
  2021. if(s->h263_pred || s->h263_aic){
  2022. if(best_s.mb_intra)
  2023. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  2024. else
  2025. ff_clean_intra_table_entries(s); //old mode?
  2026. }
  2027. }
  2028. if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
  2029. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  2030. const int last_qp= backup_s.qscale;
  2031. int qpi, qp, dc[6];
  2032. DCTELEM ac[6][16];
  2033. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2034. static const int dquant_tab[4]={-1,1,-2,2};
  2035. assert(backup_s.dquant == 0);
  2036. //FIXME intra
  2037. s->mv_dir= best_s.mv_dir;
  2038. s->mv_type = MV_TYPE_16X16;
  2039. s->mb_intra= best_s.mb_intra;
  2040. s->mv[0][0][0] = best_s.mv[0][0][0];
  2041. s->mv[0][0][1] = best_s.mv[0][0][1];
  2042. s->mv[1][0][0] = best_s.mv[1][0][0];
  2043. s->mv[1][0][1] = best_s.mv[1][0][1];
  2044. qpi = s->pict_type == FF_B_TYPE ? 2 : 0;
  2045. for(; qpi<4; qpi++){
  2046. int dquant= dquant_tab[qpi];
  2047. qp= last_qp + dquant;
  2048. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2049. continue;
  2050. backup_s.dquant= dquant;
  2051. if(s->mb_intra && s->dc_val[0]){
  2052. for(i=0; i<6; i++){
  2053. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2054. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
  2055. }
  2056. }
  2057. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2058. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2059. if(best_s.qscale != qp){
  2060. if(s->mb_intra && s->dc_val[0]){
  2061. for(i=0; i<6; i++){
  2062. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2063. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
  2064. }
  2065. }
  2066. }
  2067. }
  2068. }
  2069. }
  2070. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2071. int mx= s->b_direct_mv_table[xy][0];
  2072. int my= s->b_direct_mv_table[xy][1];
  2073. backup_s.dquant = 0;
  2074. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2075. s->mb_intra= 0;
  2076. ff_mpeg4_set_direct_mv(s, mx, my);
  2077. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2078. &dmin, &next_block, mx, my);
  2079. }
  2080. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2081. backup_s.dquant = 0;
  2082. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2083. s->mb_intra= 0;
  2084. ff_mpeg4_set_direct_mv(s, 0, 0);
  2085. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2086. &dmin, &next_block, 0, 0);
  2087. }
  2088. if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
  2089. int coded=0;
  2090. for(i=0; i<6; i++)
  2091. coded |= s->block_last_index[i];
  2092. if(coded){
  2093. int mx,my;
  2094. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2095. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2096. mx=my=0; //FIXME find the one we actually used
  2097. ff_mpeg4_set_direct_mv(s, mx, my);
  2098. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2099. mx= s->mv[1][0][0];
  2100. my= s->mv[1][0][1];
  2101. }else{
  2102. mx= s->mv[0][0][0];
  2103. my= s->mv[0][0][1];
  2104. }
  2105. s->mv_dir= best_s.mv_dir;
  2106. s->mv_type = best_s.mv_type;
  2107. s->mb_intra= 0;
  2108. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2109. s->mv[0][0][1] = best_s.mv[0][0][1];
  2110. s->mv[1][0][0] = best_s.mv[1][0][0];
  2111. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2112. backup_s.dquant= 0;
  2113. s->skipdct=1;
  2114. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2115. &dmin, &next_block, mx, my);
  2116. s->skipdct=0;
  2117. }
  2118. }
  2119. s->current_picture.qscale_table[xy]= best_s.qscale;
  2120. copy_context_after_encode(s, &best_s, -1);
  2121. pb_bits_count= put_bits_count(&s->pb);
  2122. flush_put_bits(&s->pb);
  2123. ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2124. s->pb= backup_s.pb;
  2125. if(s->data_partitioning){
  2126. pb2_bits_count= put_bits_count(&s->pb2);
  2127. flush_put_bits(&s->pb2);
  2128. ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2129. s->pb2= backup_s.pb2;
  2130. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2131. flush_put_bits(&s->tex_pb);
  2132. ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2133. s->tex_pb= backup_s.tex_pb;
  2134. }
  2135. s->last_bits= put_bits_count(&s->pb);
  2136. if (CONFIG_H263_ENCODER &&
  2137. s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
  2138. ff_h263_update_motion_val(s);
  2139. if(next_block==0){ //FIXME 16 vs linesize16
  2140. s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
  2141. s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2142. s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2143. }
  2144. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2145. MPV_decode_mb(s, s->block);
  2146. } else {
  2147. int motion_x = 0, motion_y = 0;
  2148. s->mv_type=MV_TYPE_16X16;
  2149. // only one MB-Type possible
  2150. switch(mb_type){
  2151. case CANDIDATE_MB_TYPE_INTRA:
  2152. s->mv_dir = 0;
  2153. s->mb_intra= 1;
  2154. motion_x= s->mv[0][0][0] = 0;
  2155. motion_y= s->mv[0][0][1] = 0;
  2156. break;
  2157. case CANDIDATE_MB_TYPE_INTER:
  2158. s->mv_dir = MV_DIR_FORWARD;
  2159. s->mb_intra= 0;
  2160. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2161. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2162. break;
  2163. case CANDIDATE_MB_TYPE_INTER_I:
  2164. s->mv_dir = MV_DIR_FORWARD;
  2165. s->mv_type = MV_TYPE_FIELD;
  2166. s->mb_intra= 0;
  2167. for(i=0; i<2; i++){
  2168. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2169. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2170. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2171. }
  2172. break;
  2173. case CANDIDATE_MB_TYPE_INTER4V:
  2174. s->mv_dir = MV_DIR_FORWARD;
  2175. s->mv_type = MV_TYPE_8X8;
  2176. s->mb_intra= 0;
  2177. for(i=0; i<4; i++){
  2178. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  2179. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  2180. }
  2181. break;
  2182. case CANDIDATE_MB_TYPE_DIRECT:
  2183. if (CONFIG_MPEG4_ENCODER) {
  2184. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2185. s->mb_intra= 0;
  2186. motion_x=s->b_direct_mv_table[xy][0];
  2187. motion_y=s->b_direct_mv_table[xy][1];
  2188. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2189. }
  2190. break;
  2191. case CANDIDATE_MB_TYPE_DIRECT0:
  2192. if (CONFIG_MPEG4_ENCODER) {
  2193. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2194. s->mb_intra= 0;
  2195. ff_mpeg4_set_direct_mv(s, 0, 0);
  2196. }
  2197. break;
  2198. case CANDIDATE_MB_TYPE_BIDIR:
  2199. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2200. s->mb_intra= 0;
  2201. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2202. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2203. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2204. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2205. break;
  2206. case CANDIDATE_MB_TYPE_BACKWARD:
  2207. s->mv_dir = MV_DIR_BACKWARD;
  2208. s->mb_intra= 0;
  2209. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2210. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2211. break;
  2212. case CANDIDATE_MB_TYPE_FORWARD:
  2213. s->mv_dir = MV_DIR_FORWARD;
  2214. s->mb_intra= 0;
  2215. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2216. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2217. // printf(" %d %d ", motion_x, motion_y);
  2218. break;
  2219. case CANDIDATE_MB_TYPE_FORWARD_I:
  2220. s->mv_dir = MV_DIR_FORWARD;
  2221. s->mv_type = MV_TYPE_FIELD;
  2222. s->mb_intra= 0;
  2223. for(i=0; i<2; i++){
  2224. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2225. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2226. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2227. }
  2228. break;
  2229. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2230. s->mv_dir = MV_DIR_BACKWARD;
  2231. s->mv_type = MV_TYPE_FIELD;
  2232. s->mb_intra= 0;
  2233. for(i=0; i<2; i++){
  2234. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2235. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2236. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2237. }
  2238. break;
  2239. case CANDIDATE_MB_TYPE_BIDIR_I:
  2240. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2241. s->mv_type = MV_TYPE_FIELD;
  2242. s->mb_intra= 0;
  2243. for(dir=0; dir<2; dir++){
  2244. for(i=0; i<2; i++){
  2245. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2246. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2247. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2248. }
  2249. }
  2250. break;
  2251. default:
  2252. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2253. }
  2254. encode_mb(s, motion_x, motion_y);
  2255. // RAL: Update last macroblock type
  2256. s->last_mv_dir = s->mv_dir;
  2257. if (CONFIG_H263_ENCODER &&
  2258. s->out_format == FMT_H263 && s->pict_type!=FF_B_TYPE)
  2259. ff_h263_update_motion_val(s);
  2260. MPV_decode_mb(s, s->block);
  2261. }
  2262. /* clean the MV table in IPS frames for direct mode in B frames */
  2263. if(s->mb_intra /* && I,P,S_TYPE */){
  2264. s->p_mv_table[xy][0]=0;
  2265. s->p_mv_table[xy][1]=0;
  2266. }
  2267. if(s->flags&CODEC_FLAG_PSNR){
  2268. int w= 16;
  2269. int h= 16;
  2270. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2271. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2272. s->current_picture.error[0] += sse(
  2273. s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2274. s->dest[0], w, h, s->linesize);
  2275. s->current_picture.error[1] += sse(
  2276. s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2277. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2278. s->current_picture.error[2] += sse(
  2279. s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2280. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2281. }
  2282. if(s->loop_filter){
  2283. if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  2284. ff_h263_loop_filter(s);
  2285. }
  2286. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
  2287. }
  2288. }
  2289. //not beautiful here but we must write it before flushing so it has to be here
  2290. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == FF_I_TYPE)
  2291. msmpeg4_encode_ext_header(s);
  2292. write_slice_end(s);
  2293. /* Send the last GOB if RTP */
  2294. if (s->avctx->rtp_callback) {
  2295. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2296. pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2297. /* Call the RTP callback to send the last GOB */
  2298. emms_c();
  2299. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2300. }
  2301. return 0;
  2302. }
  2303. #define MERGE(field) dst->field += src->field; src->field=0
  2304. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2305. MERGE(me.scene_change_score);
  2306. MERGE(me.mc_mb_var_sum_temp);
  2307. MERGE(me.mb_var_sum_temp);
  2308. }
  2309. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2310. int i;
  2311. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2312. MERGE(dct_count[1]);
  2313. MERGE(mv_bits);
  2314. MERGE(i_tex_bits);
  2315. MERGE(p_tex_bits);
  2316. MERGE(i_count);
  2317. MERGE(f_count);
  2318. MERGE(b_count);
  2319. MERGE(skip_count);
  2320. MERGE(misc_bits);
  2321. MERGE(error_count);
  2322. MERGE(padding_bug_score);
  2323. MERGE(current_picture.error[0]);
  2324. MERGE(current_picture.error[1]);
  2325. MERGE(current_picture.error[2]);
  2326. if(dst->avctx->noise_reduction){
  2327. for(i=0; i<64; i++){
  2328. MERGE(dct_error_sum[0][i]);
  2329. MERGE(dct_error_sum[1][i]);
  2330. }
  2331. }
  2332. assert(put_bits_count(&src->pb) % 8 ==0);
  2333. assert(put_bits_count(&dst->pb) % 8 ==0);
  2334. ff_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2335. flush_put_bits(&dst->pb);
  2336. }
  2337. static int estimate_qp(MpegEncContext *s, int dry_run){
  2338. if (s->next_lambda){
  2339. s->current_picture_ptr->quality=
  2340. s->current_picture.quality = s->next_lambda;
  2341. if(!dry_run) s->next_lambda= 0;
  2342. } else if (!s->fixed_qscale) {
  2343. s->current_picture_ptr->quality=
  2344. s->current_picture.quality = ff_rate_estimate_qscale(s, dry_run);
  2345. if (s->current_picture.quality < 0)
  2346. return -1;
  2347. }
  2348. if(s->adaptive_quant){
  2349. switch(s->codec_id){
  2350. case CODEC_ID_MPEG4:
  2351. if (CONFIG_MPEG4_ENCODER)
  2352. ff_clean_mpeg4_qscales(s);
  2353. break;
  2354. case CODEC_ID_H263:
  2355. case CODEC_ID_H263P:
  2356. case CODEC_ID_FLV1:
  2357. if (CONFIG_H263_ENCODER)
  2358. ff_clean_h263_qscales(s);
  2359. break;
  2360. default:
  2361. ff_init_qscale_tab(s);
  2362. }
  2363. s->lambda= s->lambda_table[0];
  2364. //FIXME broken
  2365. }else
  2366. s->lambda= s->current_picture.quality;
  2367. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  2368. update_qscale(s);
  2369. return 0;
  2370. }
  2371. /* must be called before writing the header */
  2372. static void set_frame_distances(MpegEncContext * s){
  2373. assert(s->current_picture_ptr->pts != AV_NOPTS_VALUE);
  2374. s->time= s->current_picture_ptr->pts*s->avctx->time_base.num;
  2375. if(s->pict_type==FF_B_TYPE){
  2376. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  2377. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  2378. }else{
  2379. s->pp_time= s->time - s->last_non_b_time;
  2380. s->last_non_b_time= s->time;
  2381. assert(s->picture_number==0 || s->pp_time > 0);
  2382. }
  2383. }
  2384. static int encode_picture(MpegEncContext *s, int picture_number)
  2385. {
  2386. int i;
  2387. int bits;
  2388. s->picture_number = picture_number;
  2389. /* Reset the average MB variance */
  2390. s->me.mb_var_sum_temp =
  2391. s->me.mc_mb_var_sum_temp = 0;
  2392. /* we need to initialize some time vars before we can encode b-frames */
  2393. // RAL: Condition added for MPEG1VIDEO
  2394. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->h263_msmpeg4))
  2395. set_frame_distances(s);
  2396. if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
  2397. ff_set_mpeg4_time(s);
  2398. s->me.scene_change_score=0;
  2399. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  2400. if(s->pict_type==FF_I_TYPE){
  2401. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2402. else s->no_rounding=0;
  2403. }else if(s->pict_type!=FF_B_TYPE){
  2404. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2405. s->no_rounding ^= 1;
  2406. }
  2407. if(s->flags & CODEC_FLAG_PASS2){
  2408. if (estimate_qp(s,1) < 0)
  2409. return -1;
  2410. ff_get_2pass_fcode(s);
  2411. }else if(!(s->flags & CODEC_FLAG_QSCALE)){
  2412. if(s->pict_type==FF_B_TYPE)
  2413. s->lambda= s->last_lambda_for[s->pict_type];
  2414. else
  2415. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  2416. update_qscale(s);
  2417. }
  2418. s->mb_intra=0; //for the rate distortion & bit compare functions
  2419. for(i=1; i<s->avctx->thread_count; i++){
  2420. ff_update_duplicate_context(s->thread_context[i], s);
  2421. }
  2422. if(ff_init_me(s)<0)
  2423. return -1;
  2424. /* Estimate motion for every MB */
  2425. if(s->pict_type != FF_I_TYPE){
  2426. s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  2427. s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  2428. if(s->pict_type != FF_B_TYPE && s->avctx->me_threshold==0){
  2429. if((s->avctx->pre_me && s->last_non_b_pict_type==FF_I_TYPE) || s->avctx->pre_me==2){
  2430. s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
  2431. }
  2432. }
  2433. s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
  2434. }else /* if(s->pict_type == FF_I_TYPE) */{
  2435. /* I-Frame */
  2436. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2437. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2438. if(!s->fixed_qscale){
  2439. /* finding spatial complexity for I-frame rate control */
  2440. s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
  2441. }
  2442. }
  2443. for(i=1; i<s->avctx->thread_count; i++){
  2444. merge_context_after_me(s, s->thread_context[i]);
  2445. }
  2446. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  2447. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  2448. emms_c();
  2449. if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == FF_P_TYPE){
  2450. s->pict_type= FF_I_TYPE;
  2451. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2452. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2453. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2454. }
  2455. if(!s->umvplus){
  2456. if(s->pict_type==FF_P_TYPE || s->pict_type==FF_S_TYPE) {
  2457. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  2458. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2459. int a,b;
  2460. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  2461. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  2462. s->f_code= FFMAX3(s->f_code, a, b);
  2463. }
  2464. ff_fix_long_p_mvs(s);
  2465. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  2466. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2467. int j;
  2468. for(i=0; i<2; i++){
  2469. for(j=0; j<2; j++)
  2470. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  2471. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  2472. }
  2473. }
  2474. }
  2475. if(s->pict_type==FF_B_TYPE){
  2476. int a, b;
  2477. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  2478. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2479. s->f_code = FFMAX(a, b);
  2480. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  2481. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2482. s->b_code = FFMAX(a, b);
  2483. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  2484. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  2485. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2486. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2487. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2488. int dir, j;
  2489. for(dir=0; dir<2; dir++){
  2490. for(i=0; i<2; i++){
  2491. for(j=0; j<2; j++){
  2492. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  2493. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  2494. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  2495. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  2496. }
  2497. }
  2498. }
  2499. }
  2500. }
  2501. }
  2502. if (estimate_qp(s, 0) < 0)
  2503. return -1;
  2504. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==FF_I_TYPE && !(s->flags & CODEC_FLAG_QSCALE))
  2505. s->qscale= 3; //reduce clipping problems
  2506. if (s->out_format == FMT_MJPEG) {
  2507. /* for mjpeg, we do include qscale in the matrix */
  2508. s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
  2509. for(i=1;i<64;i++){
  2510. int j= s->dsp.idct_permutation[i];
  2511. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  2512. }
  2513. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2514. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2515. s->qscale= 8;
  2516. }
  2517. //FIXME var duplication
  2518. s->current_picture_ptr->key_frame=
  2519. s->current_picture.key_frame= s->pict_type == FF_I_TYPE; //FIXME pic_ptr
  2520. s->current_picture_ptr->pict_type=
  2521. s->current_picture.pict_type= s->pict_type;
  2522. if(s->current_picture.key_frame)
  2523. s->picture_in_gop_number=0;
  2524. s->last_bits= put_bits_count(&s->pb);
  2525. switch(s->out_format) {
  2526. case FMT_MJPEG:
  2527. if (CONFIG_MJPEG_ENCODER)
  2528. ff_mjpeg_encode_picture_header(s);
  2529. break;
  2530. case FMT_H261:
  2531. if (CONFIG_H261_ENCODER)
  2532. ff_h261_encode_picture_header(s, picture_number);
  2533. break;
  2534. case FMT_H263:
  2535. if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
  2536. ff_wmv2_encode_picture_header(s, picture_number);
  2537. else if (CONFIG_MSMPEG4_ENCODER && s->h263_msmpeg4)
  2538. msmpeg4_encode_picture_header(s, picture_number);
  2539. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  2540. mpeg4_encode_picture_header(s, picture_number);
  2541. else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
  2542. rv10_encode_picture_header(s, picture_number);
  2543. else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
  2544. rv20_encode_picture_header(s, picture_number);
  2545. else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
  2546. ff_flv_encode_picture_header(s, picture_number);
  2547. else if (CONFIG_H263_ENCODER)
  2548. h263_encode_picture_header(s, picture_number);
  2549. break;
  2550. case FMT_MPEG1:
  2551. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2552. mpeg1_encode_picture_header(s, picture_number);
  2553. break;
  2554. case FMT_H264:
  2555. break;
  2556. default:
  2557. assert(0);
  2558. }
  2559. bits= put_bits_count(&s->pb);
  2560. s->header_bits= bits - s->last_bits;
  2561. for(i=1; i<s->avctx->thread_count; i++){
  2562. update_duplicate_context_after_me(s->thread_context[i], s);
  2563. }
  2564. s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, s->avctx->thread_count, sizeof(void*));
  2565. for(i=1; i<s->avctx->thread_count; i++){
  2566. merge_context_after_encode(s, s->thread_context[i]);
  2567. }
  2568. emms_c();
  2569. return 0;
  2570. }
  2571. void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
  2572. const int intra= s->mb_intra;
  2573. int i;
  2574. s->dct_count[intra]++;
  2575. for(i=0; i<64; i++){
  2576. int level= block[i];
  2577. if(level){
  2578. if(level>0){
  2579. s->dct_error_sum[intra][i] += level;
  2580. level -= s->dct_offset[intra][i];
  2581. if(level<0) level=0;
  2582. }else{
  2583. s->dct_error_sum[intra][i] -= level;
  2584. level += s->dct_offset[intra][i];
  2585. if(level>0) level=0;
  2586. }
  2587. block[i]= level;
  2588. }
  2589. }
  2590. }
  2591. int dct_quantize_trellis_c(MpegEncContext *s,
  2592. DCTELEM *block, int n,
  2593. int qscale, int *overflow){
  2594. const int *qmat;
  2595. const uint8_t *scantable= s->intra_scantable.scantable;
  2596. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2597. int max=0;
  2598. unsigned int threshold1, threshold2;
  2599. int bias=0;
  2600. int run_tab[65];
  2601. int level_tab[65];
  2602. int score_tab[65];
  2603. int survivor[65];
  2604. int survivor_count;
  2605. int last_run=0;
  2606. int last_level=0;
  2607. int last_score= 0;
  2608. int last_i;
  2609. int coeff[2][64];
  2610. int coeff_count[64];
  2611. int qmul, qadd, start_i, last_non_zero, i, dc;
  2612. const int esc_length= s->ac_esc_length;
  2613. uint8_t * length;
  2614. uint8_t * last_length;
  2615. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  2616. s->dsp.fdct (block);
  2617. if(s->dct_error_sum)
  2618. s->denoise_dct(s, block);
  2619. qmul= qscale*16;
  2620. qadd= ((qscale-1)|1)*8;
  2621. if (s->mb_intra) {
  2622. int q;
  2623. if (!s->h263_aic) {
  2624. if (n < 4)
  2625. q = s->y_dc_scale;
  2626. else
  2627. q = s->c_dc_scale;
  2628. q = q << 3;
  2629. } else{
  2630. /* For AIC we skip quant/dequant of INTRADC */
  2631. q = 1 << 3;
  2632. qadd=0;
  2633. }
  2634. /* note: block[0] is assumed to be positive */
  2635. block[0] = (block[0] + (q >> 1)) / q;
  2636. start_i = 1;
  2637. last_non_zero = 0;
  2638. qmat = s->q_intra_matrix[qscale];
  2639. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2640. bias= 1<<(QMAT_SHIFT-1);
  2641. length = s->intra_ac_vlc_length;
  2642. last_length= s->intra_ac_vlc_last_length;
  2643. } else {
  2644. start_i = 0;
  2645. last_non_zero = -1;
  2646. qmat = s->q_inter_matrix[qscale];
  2647. length = s->inter_ac_vlc_length;
  2648. last_length= s->inter_ac_vlc_last_length;
  2649. }
  2650. last_i= start_i;
  2651. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  2652. threshold2= (threshold1<<1);
  2653. for(i=63; i>=start_i; i--) {
  2654. const int j = scantable[i];
  2655. int level = block[j] * qmat[j];
  2656. if(((unsigned)(level+threshold1))>threshold2){
  2657. last_non_zero = i;
  2658. break;
  2659. }
  2660. }
  2661. for(i=start_i; i<=last_non_zero; i++) {
  2662. const int j = scantable[i];
  2663. int level = block[j] * qmat[j];
  2664. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  2665. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  2666. if(((unsigned)(level+threshold1))>threshold2){
  2667. if(level>0){
  2668. level= (bias + level)>>QMAT_SHIFT;
  2669. coeff[0][i]= level;
  2670. coeff[1][i]= level-1;
  2671. // coeff[2][k]= level-2;
  2672. }else{
  2673. level= (bias - level)>>QMAT_SHIFT;
  2674. coeff[0][i]= -level;
  2675. coeff[1][i]= -level+1;
  2676. // coeff[2][k]= -level+2;
  2677. }
  2678. coeff_count[i]= FFMIN(level, 2);
  2679. assert(coeff_count[i]);
  2680. max |=level;
  2681. }else{
  2682. coeff[0][i]= (level>>31)|1;
  2683. coeff_count[i]= 1;
  2684. }
  2685. }
  2686. *overflow= s->max_qcoeff < max; //overflow might have happened
  2687. if(last_non_zero < start_i){
  2688. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2689. return last_non_zero;
  2690. }
  2691. score_tab[start_i]= 0;
  2692. survivor[0]= start_i;
  2693. survivor_count= 1;
  2694. for(i=start_i; i<=last_non_zero; i++){
  2695. int level_index, j, zero_distortion;
  2696. int dct_coeff= FFABS(block[ scantable[i] ]);
  2697. int best_score=256*256*256*120;
  2698. if ( s->dsp.fdct == fdct_ifast
  2699. #ifndef FAAN_POSTSCALE
  2700. || s->dsp.fdct == ff_faandct
  2701. #endif
  2702. )
  2703. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  2704. zero_distortion= dct_coeff*dct_coeff;
  2705. for(level_index=0; level_index < coeff_count[i]; level_index++){
  2706. int distortion;
  2707. int level= coeff[level_index][i];
  2708. const int alevel= FFABS(level);
  2709. int unquant_coeff;
  2710. assert(level);
  2711. if(s->out_format == FMT_H263){
  2712. unquant_coeff= alevel*qmul + qadd;
  2713. }else{ //MPEG1
  2714. j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
  2715. if(s->mb_intra){
  2716. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  2717. unquant_coeff = (unquant_coeff - 1) | 1;
  2718. }else{
  2719. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  2720. unquant_coeff = (unquant_coeff - 1) | 1;
  2721. }
  2722. unquant_coeff<<= 3;
  2723. }
  2724. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  2725. level+=64;
  2726. if((level&(~127)) == 0){
  2727. for(j=survivor_count-1; j>=0; j--){
  2728. int run= i - survivor[j];
  2729. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2730. score += score_tab[i-run];
  2731. if(score < best_score){
  2732. best_score= score;
  2733. run_tab[i+1]= run;
  2734. level_tab[i+1]= level-64;
  2735. }
  2736. }
  2737. if(s->out_format == FMT_H263){
  2738. for(j=survivor_count-1; j>=0; j--){
  2739. int run= i - survivor[j];
  2740. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2741. score += score_tab[i-run];
  2742. if(score < last_score){
  2743. last_score= score;
  2744. last_run= run;
  2745. last_level= level-64;
  2746. last_i= i+1;
  2747. }
  2748. }
  2749. }
  2750. }else{
  2751. distortion += esc_length*lambda;
  2752. for(j=survivor_count-1; j>=0; j--){
  2753. int run= i - survivor[j];
  2754. int score= distortion + score_tab[i-run];
  2755. if(score < best_score){
  2756. best_score= score;
  2757. run_tab[i+1]= run;
  2758. level_tab[i+1]= level-64;
  2759. }
  2760. }
  2761. if(s->out_format == FMT_H263){
  2762. for(j=survivor_count-1; j>=0; j--){
  2763. int run= i - survivor[j];
  2764. int score= distortion + score_tab[i-run];
  2765. if(score < last_score){
  2766. last_score= score;
  2767. last_run= run;
  2768. last_level= level-64;
  2769. last_i= i+1;
  2770. }
  2771. }
  2772. }
  2773. }
  2774. }
  2775. score_tab[i+1]= best_score;
  2776. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  2777. if(last_non_zero <= 27){
  2778. for(; survivor_count; survivor_count--){
  2779. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  2780. break;
  2781. }
  2782. }else{
  2783. for(; survivor_count; survivor_count--){
  2784. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  2785. break;
  2786. }
  2787. }
  2788. survivor[ survivor_count++ ]= i+1;
  2789. }
  2790. if(s->out_format != FMT_H263){
  2791. last_score= 256*256*256*120;
  2792. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  2793. int score= score_tab[i];
  2794. if(i) score += lambda*2; //FIXME exacter?
  2795. if(score < last_score){
  2796. last_score= score;
  2797. last_i= i;
  2798. last_level= level_tab[i];
  2799. last_run= run_tab[i];
  2800. }
  2801. }
  2802. }
  2803. s->coded_score[n] = last_score;
  2804. dc= FFABS(block[0]);
  2805. last_non_zero= last_i - 1;
  2806. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2807. if(last_non_zero < start_i)
  2808. return last_non_zero;
  2809. if(last_non_zero == 0 && start_i == 0){
  2810. int best_level= 0;
  2811. int best_score= dc * dc;
  2812. for(i=0; i<coeff_count[0]; i++){
  2813. int level= coeff[i][0];
  2814. int alevel= FFABS(level);
  2815. int unquant_coeff, score, distortion;
  2816. if(s->out_format == FMT_H263){
  2817. unquant_coeff= (alevel*qmul + qadd)>>3;
  2818. }else{ //MPEG1
  2819. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  2820. unquant_coeff = (unquant_coeff - 1) | 1;
  2821. }
  2822. unquant_coeff = (unquant_coeff + 4) >> 3;
  2823. unquant_coeff<<= 3 + 3;
  2824. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  2825. level+=64;
  2826. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  2827. else score= distortion + esc_length*lambda;
  2828. if(score < best_score){
  2829. best_score= score;
  2830. best_level= level - 64;
  2831. }
  2832. }
  2833. block[0]= best_level;
  2834. s->coded_score[n] = best_score - dc*dc;
  2835. if(best_level == 0) return -1;
  2836. else return last_non_zero;
  2837. }
  2838. i= last_i;
  2839. assert(last_level);
  2840. block[ perm_scantable[last_non_zero] ]= last_level;
  2841. i -= last_run + 1;
  2842. for(; i>start_i; i -= run_tab[i] + 1){
  2843. block[ perm_scantable[i-1] ]= level_tab[i];
  2844. }
  2845. return last_non_zero;
  2846. }
  2847. //#define REFINE_STATS 1
  2848. static int16_t basis[64][64];
  2849. static void build_basis(uint8_t *perm){
  2850. int i, j, x, y;
  2851. emms_c();
  2852. for(i=0; i<8; i++){
  2853. for(j=0; j<8; j++){
  2854. for(y=0; y<8; y++){
  2855. for(x=0; x<8; x++){
  2856. double s= 0.25*(1<<BASIS_SHIFT);
  2857. int index= 8*i + j;
  2858. int perm_index= perm[index];
  2859. if(i==0) s*= sqrt(0.5);
  2860. if(j==0) s*= sqrt(0.5);
  2861. basis[perm_index][8*x + y]= lrintf(s * cos((M_PI/8.0)*i*(x+0.5)) * cos((M_PI/8.0)*j*(y+0.5)));
  2862. }
  2863. }
  2864. }
  2865. }
  2866. }
  2867. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  2868. DCTELEM *block, int16_t *weight, DCTELEM *orig,
  2869. int n, int qscale){
  2870. int16_t rem[64];
  2871. DECLARE_ALIGNED_16(DCTELEM, d1[64]);
  2872. const uint8_t *scantable= s->intra_scantable.scantable;
  2873. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2874. // unsigned int threshold1, threshold2;
  2875. // int bias=0;
  2876. int run_tab[65];
  2877. int prev_run=0;
  2878. int prev_level=0;
  2879. int qmul, qadd, start_i, last_non_zero, i, dc;
  2880. uint8_t * length;
  2881. uint8_t * last_length;
  2882. int lambda;
  2883. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  2884. #ifdef REFINE_STATS
  2885. static int count=0;
  2886. static int after_last=0;
  2887. static int to_zero=0;
  2888. static int from_zero=0;
  2889. static int raise=0;
  2890. static int lower=0;
  2891. static int messed_sign=0;
  2892. #endif
  2893. if(basis[0][0] == 0)
  2894. build_basis(s->dsp.idct_permutation);
  2895. qmul= qscale*2;
  2896. qadd= (qscale-1)|1;
  2897. if (s->mb_intra) {
  2898. if (!s->h263_aic) {
  2899. if (n < 4)
  2900. q = s->y_dc_scale;
  2901. else
  2902. q = s->c_dc_scale;
  2903. } else{
  2904. /* For AIC we skip quant/dequant of INTRADC */
  2905. q = 1;
  2906. qadd=0;
  2907. }
  2908. q <<= RECON_SHIFT-3;
  2909. /* note: block[0] is assumed to be positive */
  2910. dc= block[0]*q;
  2911. // block[0] = (block[0] + (q >> 1)) / q;
  2912. start_i = 1;
  2913. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2914. // bias= 1<<(QMAT_SHIFT-1);
  2915. length = s->intra_ac_vlc_length;
  2916. last_length= s->intra_ac_vlc_last_length;
  2917. } else {
  2918. dc= 0;
  2919. start_i = 0;
  2920. length = s->inter_ac_vlc_length;
  2921. last_length= s->inter_ac_vlc_last_length;
  2922. }
  2923. last_non_zero = s->block_last_index[n];
  2924. #ifdef REFINE_STATS
  2925. {START_TIMER
  2926. #endif
  2927. dc += (1<<(RECON_SHIFT-1));
  2928. for(i=0; i<64; i++){
  2929. rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
  2930. }
  2931. #ifdef REFINE_STATS
  2932. STOP_TIMER("memset rem[]")}
  2933. #endif
  2934. sum=0;
  2935. for(i=0; i<64; i++){
  2936. int one= 36;
  2937. int qns=4;
  2938. int w;
  2939. w= FFABS(weight[i]) + qns*one;
  2940. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  2941. weight[i] = w;
  2942. // w=weight[i] = (63*qns + (w/2)) / w;
  2943. assert(w>0);
  2944. assert(w<(1<<6));
  2945. sum += w*w;
  2946. }
  2947. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  2948. #ifdef REFINE_STATS
  2949. {START_TIMER
  2950. #endif
  2951. run=0;
  2952. rle_index=0;
  2953. for(i=start_i; i<=last_non_zero; i++){
  2954. int j= perm_scantable[i];
  2955. const int level= block[j];
  2956. int coeff;
  2957. if(level){
  2958. if(level<0) coeff= qmul*level - qadd;
  2959. else coeff= qmul*level + qadd;
  2960. run_tab[rle_index++]=run;
  2961. run=0;
  2962. s->dsp.add_8x8basis(rem, basis[j], coeff);
  2963. }else{
  2964. run++;
  2965. }
  2966. }
  2967. #ifdef REFINE_STATS
  2968. if(last_non_zero>0){
  2969. STOP_TIMER("init rem[]")
  2970. }
  2971. }
  2972. {START_TIMER
  2973. #endif
  2974. for(;;){
  2975. int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
  2976. int best_coeff=0;
  2977. int best_change=0;
  2978. int run2, best_unquant_change=0, analyze_gradient;
  2979. #ifdef REFINE_STATS
  2980. {START_TIMER
  2981. #endif
  2982. analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
  2983. if(analyze_gradient){
  2984. #ifdef REFINE_STATS
  2985. {START_TIMER
  2986. #endif
  2987. for(i=0; i<64; i++){
  2988. int w= weight[i];
  2989. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  2990. }
  2991. #ifdef REFINE_STATS
  2992. STOP_TIMER("rem*w*w")}
  2993. {START_TIMER
  2994. #endif
  2995. s->dsp.fdct(d1);
  2996. #ifdef REFINE_STATS
  2997. STOP_TIMER("dct")}
  2998. #endif
  2999. }
  3000. if(start_i){
  3001. const int level= block[0];
  3002. int change, old_coeff;
  3003. assert(s->mb_intra);
  3004. old_coeff= q*level;
  3005. for(change=-1; change<=1; change+=2){
  3006. int new_level= level + change;
  3007. int score, new_coeff;
  3008. new_coeff= q*new_level;
  3009. if(new_coeff >= 2048 || new_coeff < 0)
  3010. continue;
  3011. score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
  3012. if(score<best_score){
  3013. best_score= score;
  3014. best_coeff= 0;
  3015. best_change= change;
  3016. best_unquant_change= new_coeff - old_coeff;
  3017. }
  3018. }
  3019. }
  3020. run=0;
  3021. rle_index=0;
  3022. run2= run_tab[rle_index++];
  3023. prev_level=0;
  3024. prev_run=0;
  3025. for(i=start_i; i<64; i++){
  3026. int j= perm_scantable[i];
  3027. const int level= block[j];
  3028. int change, old_coeff;
  3029. if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  3030. break;
  3031. if(level){
  3032. if(level<0) old_coeff= qmul*level - qadd;
  3033. else old_coeff= qmul*level + qadd;
  3034. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3035. }else{
  3036. old_coeff=0;
  3037. run2--;
  3038. assert(run2>=0 || i >= last_non_zero );
  3039. }
  3040. for(change=-1; change<=1; change+=2){
  3041. int new_level= level + change;
  3042. int score, new_coeff, unquant_change;
  3043. score=0;
  3044. if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3045. continue;
  3046. if(new_level){
  3047. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3048. else new_coeff= qmul*new_level + qadd;
  3049. if(new_coeff >= 2048 || new_coeff <= -2048)
  3050. continue;
  3051. //FIXME check for overflow
  3052. if(level){
  3053. if(level < 63 && level > -63){
  3054. if(i < last_non_zero)
  3055. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3056. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3057. else
  3058. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3059. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3060. }
  3061. }else{
  3062. assert(FFABS(new_level)==1);
  3063. if(analyze_gradient){
  3064. int g= d1[ scantable[i] ];
  3065. if(g && (g^new_level) >= 0)
  3066. continue;
  3067. }
  3068. if(i < last_non_zero){
  3069. int next_i= i + run2 + 1;
  3070. int next_level= block[ perm_scantable[next_i] ] + 64;
  3071. if(next_level&(~127))
  3072. next_level= 0;
  3073. if(next_i < last_non_zero)
  3074. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3075. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3076. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3077. else
  3078. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3079. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3080. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3081. }else{
  3082. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3083. if(prev_level){
  3084. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3085. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3086. }
  3087. }
  3088. }
  3089. }else{
  3090. new_coeff=0;
  3091. assert(FFABS(level)==1);
  3092. if(i < last_non_zero){
  3093. int next_i= i + run2 + 1;
  3094. int next_level= block[ perm_scantable[next_i] ] + 64;
  3095. if(next_level&(~127))
  3096. next_level= 0;
  3097. if(next_i < last_non_zero)
  3098. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3099. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3100. - length[UNI_AC_ENC_INDEX(run, 65)];
  3101. else
  3102. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3103. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3104. - length[UNI_AC_ENC_INDEX(run, 65)];
  3105. }else{
  3106. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3107. if(prev_level){
  3108. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3109. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3110. }
  3111. }
  3112. }
  3113. score *= lambda;
  3114. unquant_change= new_coeff - old_coeff;
  3115. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3116. score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
  3117. if(score<best_score){
  3118. best_score= score;
  3119. best_coeff= i;
  3120. best_change= change;
  3121. best_unquant_change= unquant_change;
  3122. }
  3123. }
  3124. if(level){
  3125. prev_level= level + 64;
  3126. if(prev_level&(~127))
  3127. prev_level= 0;
  3128. prev_run= run;
  3129. run=0;
  3130. }else{
  3131. run++;
  3132. }
  3133. }
  3134. #ifdef REFINE_STATS
  3135. STOP_TIMER("iterative step")}
  3136. #endif
  3137. if(best_change){
  3138. int j= perm_scantable[ best_coeff ];
  3139. block[j] += best_change;
  3140. if(best_coeff > last_non_zero){
  3141. last_non_zero= best_coeff;
  3142. assert(block[j]);
  3143. #ifdef REFINE_STATS
  3144. after_last++;
  3145. #endif
  3146. }else{
  3147. #ifdef REFINE_STATS
  3148. if(block[j]){
  3149. if(block[j] - best_change){
  3150. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3151. raise++;
  3152. }else{
  3153. lower++;
  3154. }
  3155. }else{
  3156. from_zero++;
  3157. }
  3158. }else{
  3159. to_zero++;
  3160. }
  3161. #endif
  3162. for(; last_non_zero>=start_i; last_non_zero--){
  3163. if(block[perm_scantable[last_non_zero]])
  3164. break;
  3165. }
  3166. }
  3167. #ifdef REFINE_STATS
  3168. count++;
  3169. if(256*256*256*64 % count == 0){
  3170. printf("after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
  3171. }
  3172. #endif
  3173. run=0;
  3174. rle_index=0;
  3175. for(i=start_i; i<=last_non_zero; i++){
  3176. int j= perm_scantable[i];
  3177. const int level= block[j];
  3178. if(level){
  3179. run_tab[rle_index++]=run;
  3180. run=0;
  3181. }else{
  3182. run++;
  3183. }
  3184. }
  3185. s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3186. }else{
  3187. break;
  3188. }
  3189. }
  3190. #ifdef REFINE_STATS
  3191. if(last_non_zero>0){
  3192. STOP_TIMER("iterative search")
  3193. }
  3194. }
  3195. #endif
  3196. return last_non_zero;
  3197. }
  3198. int dct_quantize_c(MpegEncContext *s,
  3199. DCTELEM *block, int n,
  3200. int qscale, int *overflow)
  3201. {
  3202. int i, j, level, last_non_zero, q, start_i;
  3203. const int *qmat;
  3204. const uint8_t *scantable= s->intra_scantable.scantable;
  3205. int bias;
  3206. int max=0;
  3207. unsigned int threshold1, threshold2;
  3208. s->dsp.fdct (block);
  3209. if(s->dct_error_sum)
  3210. s->denoise_dct(s, block);
  3211. if (s->mb_intra) {
  3212. if (!s->h263_aic) {
  3213. if (n < 4)
  3214. q = s->y_dc_scale;
  3215. else
  3216. q = s->c_dc_scale;
  3217. q = q << 3;
  3218. } else
  3219. /* For AIC we skip quant/dequant of INTRADC */
  3220. q = 1 << 3;
  3221. /* note: block[0] is assumed to be positive */
  3222. block[0] = (block[0] + (q >> 1)) / q;
  3223. start_i = 1;
  3224. last_non_zero = 0;
  3225. qmat = s->q_intra_matrix[qscale];
  3226. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3227. } else {
  3228. start_i = 0;
  3229. last_non_zero = -1;
  3230. qmat = s->q_inter_matrix[qscale];
  3231. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3232. }
  3233. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3234. threshold2= (threshold1<<1);
  3235. for(i=63;i>=start_i;i--) {
  3236. j = scantable[i];
  3237. level = block[j] * qmat[j];
  3238. if(((unsigned)(level+threshold1))>threshold2){
  3239. last_non_zero = i;
  3240. break;
  3241. }else{
  3242. block[j]=0;
  3243. }
  3244. }
  3245. for(i=start_i; i<=last_non_zero; i++) {
  3246. j = scantable[i];
  3247. level = block[j] * qmat[j];
  3248. // if( bias+level >= (1<<QMAT_SHIFT)
  3249. // || bias-level >= (1<<QMAT_SHIFT)){
  3250. if(((unsigned)(level+threshold1))>threshold2){
  3251. if(level>0){
  3252. level= (bias + level)>>QMAT_SHIFT;
  3253. block[j]= level;
  3254. }else{
  3255. level= (bias - level)>>QMAT_SHIFT;
  3256. block[j]= -level;
  3257. }
  3258. max |=level;
  3259. }else{
  3260. block[j]=0;
  3261. }
  3262. }
  3263. *overflow= s->max_qcoeff < max; //overflow might have happened
  3264. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3265. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3266. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3267. return last_non_zero;
  3268. }
  3269. AVCodec h263_encoder = {
  3270. "h263",
  3271. CODEC_TYPE_VIDEO,
  3272. CODEC_ID_H263,
  3273. sizeof(MpegEncContext),
  3274. MPV_encode_init,
  3275. MPV_encode_picture,
  3276. MPV_encode_end,
  3277. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3278. .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3279. };
  3280. AVCodec h263p_encoder = {
  3281. "h263p",
  3282. CODEC_TYPE_VIDEO,
  3283. CODEC_ID_H263P,
  3284. sizeof(MpegEncContext),
  3285. MPV_encode_init,
  3286. MPV_encode_picture,
  3287. MPV_encode_end,
  3288. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3289. .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  3290. };
  3291. AVCodec msmpeg4v1_encoder = {
  3292. "msmpeg4v1",
  3293. CODEC_TYPE_VIDEO,
  3294. CODEC_ID_MSMPEG4V1,
  3295. sizeof(MpegEncContext),
  3296. MPV_encode_init,
  3297. MPV_encode_picture,
  3298. MPV_encode_end,
  3299. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3300. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 1"),
  3301. };
  3302. AVCodec msmpeg4v2_encoder = {
  3303. "msmpeg4v2",
  3304. CODEC_TYPE_VIDEO,
  3305. CODEC_ID_MSMPEG4V2,
  3306. sizeof(MpegEncContext),
  3307. MPV_encode_init,
  3308. MPV_encode_picture,
  3309. MPV_encode_end,
  3310. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3311. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  3312. };
  3313. AVCodec msmpeg4v3_encoder = {
  3314. "msmpeg4",
  3315. CODEC_TYPE_VIDEO,
  3316. CODEC_ID_MSMPEG4V3,
  3317. sizeof(MpegEncContext),
  3318. MPV_encode_init,
  3319. MPV_encode_picture,
  3320. MPV_encode_end,
  3321. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3322. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  3323. };
  3324. AVCodec wmv1_encoder = {
  3325. "wmv1",
  3326. CODEC_TYPE_VIDEO,
  3327. CODEC_ID_WMV1,
  3328. sizeof(MpegEncContext),
  3329. MPV_encode_init,
  3330. MPV_encode_picture,
  3331. MPV_encode_end,
  3332. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3333. .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  3334. };