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.

3836 lines
140KB

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