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.

4669 lines
166KB

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