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.

4158 lines
150KB

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