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.

4641 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, got_output;
  1100. av_init_packet(&pkt);
  1101. ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  1102. if (ret < 0)
  1103. return ret;
  1104. ret = pkt.size;
  1105. av_packet_unref(&pkt);
  1106. return ret;
  1107. }
  1108. static int estimate_best_b_count(MpegEncContext *s)
  1109. {
  1110. AVCodec *codec = avcodec_find_encoder(s->avctx->codec_id);
  1111. AVCodecContext *c = avcodec_alloc_context3(NULL);
  1112. const int scale = s->brd_scale;
  1113. int i, j, out_size, p_lambda, b_lambda, lambda2;
  1114. int64_t best_rd = INT64_MAX;
  1115. int best_b_count = -1;
  1116. if (!c)
  1117. return AVERROR(ENOMEM);
  1118. assert(scale >= 0 && scale <= 3);
  1119. //emms_c();
  1120. //s->next_picture_ptr->quality;
  1121. p_lambda = s->last_lambda_for[AV_PICTURE_TYPE_P];
  1122. //p_lambda * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  1123. b_lambda = s->last_lambda_for[AV_PICTURE_TYPE_B];
  1124. if (!b_lambda) // FIXME we should do this somewhere else
  1125. b_lambda = p_lambda;
  1126. lambda2 = (b_lambda * b_lambda + (1 << FF_LAMBDA_SHIFT) / 2) >>
  1127. FF_LAMBDA_SHIFT;
  1128. c->width = s->width >> scale;
  1129. c->height = s->height >> scale;
  1130. c->flags = AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_PSNR;
  1131. c->flags |= s->avctx->flags & AV_CODEC_FLAG_QPEL;
  1132. c->mb_decision = s->avctx->mb_decision;
  1133. c->me_cmp = s->avctx->me_cmp;
  1134. c->mb_cmp = s->avctx->mb_cmp;
  1135. c->me_sub_cmp = s->avctx->me_sub_cmp;
  1136. c->pix_fmt = AV_PIX_FMT_YUV420P;
  1137. c->time_base = s->avctx->time_base;
  1138. c->max_b_frames = s->max_b_frames;
  1139. if (avcodec_open2(c, codec, NULL) < 0)
  1140. return -1;
  1141. for (i = 0; i < s->max_b_frames + 2; i++) {
  1142. Picture pre_input, *pre_input_ptr = i ? s->input_picture[i - 1] :
  1143. s->next_picture_ptr;
  1144. if (pre_input_ptr && (!i || s->input_picture[i - 1])) {
  1145. pre_input = *pre_input_ptr;
  1146. if (!pre_input.shared && i) {
  1147. pre_input.f->data[0] += INPLACE_OFFSET;
  1148. pre_input.f->data[1] += INPLACE_OFFSET;
  1149. pre_input.f->data[2] += INPLACE_OFFSET;
  1150. }
  1151. s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[0],
  1152. s->tmp_frames[i]->linesize[0],
  1153. pre_input.f->data[0],
  1154. pre_input.f->linesize[0],
  1155. c->width, c->height);
  1156. s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[1],
  1157. s->tmp_frames[i]->linesize[1],
  1158. pre_input.f->data[1],
  1159. pre_input.f->linesize[1],
  1160. c->width >> 1, c->height >> 1);
  1161. s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[2],
  1162. s->tmp_frames[i]->linesize[2],
  1163. pre_input.f->data[2],
  1164. pre_input.f->linesize[2],
  1165. c->width >> 1, c->height >> 1);
  1166. }
  1167. }
  1168. for (j = 0; j < s->max_b_frames + 1; j++) {
  1169. int64_t rd = 0;
  1170. if (!s->input_picture[j])
  1171. break;
  1172. c->error[0] = c->error[1] = c->error[2] = 0;
  1173. s->tmp_frames[0]->pict_type = AV_PICTURE_TYPE_I;
  1174. s->tmp_frames[0]->quality = 1 * FF_QP2LAMBDA;
  1175. out_size = encode_frame(c, s->tmp_frames[0]);
  1176. //rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  1177. for (i = 0; i < s->max_b_frames + 1; i++) {
  1178. int is_p = i % (j + 1) == j || i == s->max_b_frames;
  1179. s->tmp_frames[i + 1]->pict_type = is_p ?
  1180. AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
  1181. s->tmp_frames[i + 1]->quality = is_p ? p_lambda : b_lambda;
  1182. out_size = encode_frame(c, s->tmp_frames[i + 1]);
  1183. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  1184. }
  1185. /* get the delayed frames */
  1186. while (out_size) {
  1187. out_size = encode_frame(c, NULL);
  1188. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  1189. }
  1190. rd += c->error[0] + c->error[1] + c->error[2];
  1191. if (rd < best_rd) {
  1192. best_rd = rd;
  1193. best_b_count = j;
  1194. }
  1195. }
  1196. avcodec_free_context(&c);
  1197. return best_b_count;
  1198. }
  1199. static int select_input_picture(MpegEncContext *s)
  1200. {
  1201. int i, ret;
  1202. for (i = 1; i < MAX_PICTURE_COUNT; i++)
  1203. s->reordered_input_picture[i - 1] = s->reordered_input_picture[i];
  1204. s->reordered_input_picture[MAX_PICTURE_COUNT - 1] = NULL;
  1205. /* set next picture type & ordering */
  1206. if (!s->reordered_input_picture[0] && s->input_picture[0]) {
  1207. if (/*s->picture_in_gop_number >= s->gop_size ||*/
  1208. !s->next_picture_ptr || s->intra_only) {
  1209. s->reordered_input_picture[0] = s->input_picture[0];
  1210. s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_I;
  1211. s->reordered_input_picture[0]->f->coded_picture_number =
  1212. s->coded_picture_number++;
  1213. } else {
  1214. int b_frames = 0;
  1215. if (s->frame_skip_threshold || s->frame_skip_factor) {
  1216. if (s->picture_in_gop_number < s->gop_size &&
  1217. skip_check(s, s->input_picture[0], s->next_picture_ptr)) {
  1218. // FIXME check that the gop check above is +-1 correct
  1219. av_frame_unref(s->input_picture[0]->f);
  1220. emms_c();
  1221. ff_vbv_update(s, 0);
  1222. goto no_output_pic;
  1223. }
  1224. }
  1225. if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  1226. for (i = 0; i < s->max_b_frames + 1; i++) {
  1227. int pict_num = s->input_picture[0]->f->display_picture_number + i;
  1228. if (pict_num >= s->rc_context.num_entries)
  1229. break;
  1230. if (!s->input_picture[i]) {
  1231. s->rc_context.entry[pict_num - 1].new_pict_type = AV_PICTURE_TYPE_P;
  1232. break;
  1233. }
  1234. s->input_picture[i]->f->pict_type =
  1235. s->rc_context.entry[pict_num].new_pict_type;
  1236. }
  1237. }
  1238. if (s->b_frame_strategy == 0) {
  1239. b_frames = s->max_b_frames;
  1240. while (b_frames && !s->input_picture[b_frames])
  1241. b_frames--;
  1242. } else if (s->b_frame_strategy == 1) {
  1243. for (i = 1; i < s->max_b_frames + 1; i++) {
  1244. if (s->input_picture[i] &&
  1245. s->input_picture[i]->b_frame_score == 0) {
  1246. s->input_picture[i]->b_frame_score =
  1247. get_intra_count(s,
  1248. s->input_picture[i ]->f->data[0],
  1249. s->input_picture[i - 1]->f->data[0],
  1250. s->linesize) + 1;
  1251. }
  1252. }
  1253. for (i = 0; i < s->max_b_frames + 1; i++) {
  1254. if (!s->input_picture[i] ||
  1255. s->input_picture[i]->b_frame_score - 1 >
  1256. s->mb_num / s->b_sensitivity)
  1257. break;
  1258. }
  1259. b_frames = FFMAX(0, i - 1);
  1260. /* reset scores */
  1261. for (i = 0; i < b_frames + 1; i++) {
  1262. s->input_picture[i]->b_frame_score = 0;
  1263. }
  1264. } else if (s->b_frame_strategy == 2) {
  1265. b_frames = estimate_best_b_count(s);
  1266. }
  1267. emms_c();
  1268. for (i = b_frames - 1; i >= 0; i--) {
  1269. int type = s->input_picture[i]->f->pict_type;
  1270. if (type && type != AV_PICTURE_TYPE_B)
  1271. b_frames = i;
  1272. }
  1273. if (s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_B &&
  1274. b_frames == s->max_b_frames) {
  1275. av_log(s->avctx, AV_LOG_ERROR,
  1276. "warning, too many B-frames in a row\n");
  1277. }
  1278. if (s->picture_in_gop_number + b_frames >= s->gop_size) {
  1279. if ((s->mpv_flags & FF_MPV_FLAG_STRICT_GOP) &&
  1280. s->gop_size > s->picture_in_gop_number) {
  1281. b_frames = s->gop_size - s->picture_in_gop_number - 1;
  1282. } else {
  1283. if (s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)
  1284. b_frames = 0;
  1285. s->input_picture[b_frames]->f->pict_type = AV_PICTURE_TYPE_I;
  1286. }
  1287. }
  1288. if ((s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) && b_frames &&
  1289. s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_I)
  1290. b_frames--;
  1291. s->reordered_input_picture[0] = s->input_picture[b_frames];
  1292. if (s->reordered_input_picture[0]->f->pict_type != AV_PICTURE_TYPE_I)
  1293. s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_P;
  1294. s->reordered_input_picture[0]->f->coded_picture_number =
  1295. s->coded_picture_number++;
  1296. for (i = 0; i < b_frames; i++) {
  1297. s->reordered_input_picture[i + 1] = s->input_picture[i];
  1298. s->reordered_input_picture[i + 1]->f->pict_type =
  1299. AV_PICTURE_TYPE_B;
  1300. s->reordered_input_picture[i + 1]->f->coded_picture_number =
  1301. s->coded_picture_number++;
  1302. }
  1303. }
  1304. }
  1305. no_output_pic:
  1306. ff_mpeg_unref_picture(s->avctx, &s->new_picture);
  1307. if (s->reordered_input_picture[0]) {
  1308. s->reordered_input_picture[0]->reference =
  1309. s->reordered_input_picture[0]->f->pict_type !=
  1310. AV_PICTURE_TYPE_B ? 3 : 0;
  1311. if ((ret = ff_mpeg_ref_picture(s->avctx, &s->new_picture, s->reordered_input_picture[0])))
  1312. return ret;
  1313. if (s->reordered_input_picture[0]->shared || s->avctx->rc_buffer_size) {
  1314. // input is a shared pix, so we can't modify it -> allocate a new
  1315. // one & ensure that the shared one is reuseable
  1316. Picture *pic;
  1317. int i = ff_find_unused_picture(s->avctx, s->picture, 0);
  1318. if (i < 0)
  1319. return i;
  1320. pic = &s->picture[i];
  1321. pic->reference = s->reordered_input_picture[0]->reference;
  1322. if (alloc_picture(s, pic, 0) < 0) {
  1323. return -1;
  1324. }
  1325. ret = av_frame_copy_props(pic->f, s->reordered_input_picture[0]->f);
  1326. if (ret < 0)
  1327. return ret;
  1328. /* mark us unused / free shared pic */
  1329. av_frame_unref(s->reordered_input_picture[0]->f);
  1330. s->reordered_input_picture[0]->shared = 0;
  1331. s->current_picture_ptr = pic;
  1332. } else {
  1333. // input is not a shared pix -> reuse buffer for current_pix
  1334. s->current_picture_ptr = s->reordered_input_picture[0];
  1335. for (i = 0; i < 4; i++) {
  1336. s->new_picture.f->data[i] += INPLACE_OFFSET;
  1337. }
  1338. }
  1339. ff_mpeg_unref_picture(s->avctx, &s->current_picture);
  1340. if ((ret = ff_mpeg_ref_picture(s->avctx, &s->current_picture,
  1341. s->current_picture_ptr)) < 0)
  1342. return ret;
  1343. s->picture_number = s->new_picture.f->display_picture_number;
  1344. }
  1345. return 0;
  1346. }
  1347. static void frame_end(MpegEncContext *s)
  1348. {
  1349. int i;
  1350. if (s->unrestricted_mv &&
  1351. s->current_picture.reference &&
  1352. !s->intra_only) {
  1353. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  1354. int hshift = desc->log2_chroma_w;
  1355. int vshift = desc->log2_chroma_h;
  1356. s->mpvencdsp.draw_edges(s->current_picture.f->data[0], s->linesize,
  1357. s->h_edge_pos, s->v_edge_pos,
  1358. EDGE_WIDTH, EDGE_WIDTH,
  1359. EDGE_TOP | EDGE_BOTTOM);
  1360. s->mpvencdsp.draw_edges(s->current_picture.f->data[1], s->uvlinesize,
  1361. s->h_edge_pos >> hshift,
  1362. s->v_edge_pos >> vshift,
  1363. EDGE_WIDTH >> hshift,
  1364. EDGE_WIDTH >> vshift,
  1365. EDGE_TOP | EDGE_BOTTOM);
  1366. s->mpvencdsp.draw_edges(s->current_picture.f->data[2], s->uvlinesize,
  1367. s->h_edge_pos >> hshift,
  1368. s->v_edge_pos >> vshift,
  1369. EDGE_WIDTH >> hshift,
  1370. EDGE_WIDTH >> vshift,
  1371. EDGE_TOP | EDGE_BOTTOM);
  1372. }
  1373. emms_c();
  1374. s->last_pict_type = s->pict_type;
  1375. s->last_lambda_for [s->pict_type] = s->current_picture_ptr->f->quality;
  1376. if (s->pict_type!= AV_PICTURE_TYPE_B)
  1377. s->last_non_b_pict_type = s->pict_type;
  1378. if (s->encoding) {
  1379. /* release non-reference frames */
  1380. for (i = 0; i < MAX_PICTURE_COUNT; i++) {
  1381. if (!s->picture[i].reference)
  1382. ff_mpeg_unref_picture(s->avctx, &s->picture[i]);
  1383. }
  1384. }
  1385. #if FF_API_CODED_FRAME
  1386. FF_DISABLE_DEPRECATION_WARNINGS
  1387. av_frame_copy_props(s->avctx->coded_frame, s->current_picture.f);
  1388. FF_ENABLE_DEPRECATION_WARNINGS
  1389. #endif
  1390. #if FF_API_ERROR_FRAME
  1391. FF_DISABLE_DEPRECATION_WARNINGS
  1392. memcpy(s->current_picture.f->error, s->current_picture.encoding_error,
  1393. sizeof(s->current_picture.encoding_error));
  1394. FF_ENABLE_DEPRECATION_WARNINGS
  1395. #endif
  1396. }
  1397. static void update_noise_reduction(MpegEncContext *s)
  1398. {
  1399. int intra, i;
  1400. for (intra = 0; intra < 2; intra++) {
  1401. if (s->dct_count[intra] > (1 << 16)) {
  1402. for (i = 0; i < 64; i++) {
  1403. s->dct_error_sum[intra][i] >>= 1;
  1404. }
  1405. s->dct_count[intra] >>= 1;
  1406. }
  1407. for (i = 0; i < 64; i++) {
  1408. s->dct_offset[intra][i] = (s->noise_reduction *
  1409. s->dct_count[intra] +
  1410. s->dct_error_sum[intra][i] / 2) /
  1411. (s->dct_error_sum[intra][i] + 1);
  1412. }
  1413. }
  1414. }
  1415. static int frame_start(MpegEncContext *s)
  1416. {
  1417. int ret;
  1418. /* mark & release old frames */
  1419. if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
  1420. s->last_picture_ptr != s->next_picture_ptr &&
  1421. s->last_picture_ptr->f->buf[0]) {
  1422. ff_mpeg_unref_picture(s->avctx, s->last_picture_ptr);
  1423. }
  1424. s->current_picture_ptr->f->pict_type = s->pict_type;
  1425. s->current_picture_ptr->f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
  1426. ff_mpeg_unref_picture(s->avctx, &s->current_picture);
  1427. if ((ret = ff_mpeg_ref_picture(s->avctx, &s->current_picture,
  1428. s->current_picture_ptr)) < 0)
  1429. return ret;
  1430. if (s->pict_type != AV_PICTURE_TYPE_B) {
  1431. s->last_picture_ptr = s->next_picture_ptr;
  1432. if (!s->droppable)
  1433. s->next_picture_ptr = s->current_picture_ptr;
  1434. }
  1435. if (s->last_picture_ptr) {
  1436. ff_mpeg_unref_picture(s->avctx, &s->last_picture);
  1437. if (s->last_picture_ptr->f->buf[0] &&
  1438. (ret = ff_mpeg_ref_picture(s->avctx, &s->last_picture,
  1439. s->last_picture_ptr)) < 0)
  1440. return ret;
  1441. }
  1442. if (s->next_picture_ptr) {
  1443. ff_mpeg_unref_picture(s->avctx, &s->next_picture);
  1444. if (s->next_picture_ptr->f->buf[0] &&
  1445. (ret = ff_mpeg_ref_picture(s->avctx, &s->next_picture,
  1446. s->next_picture_ptr)) < 0)
  1447. return ret;
  1448. }
  1449. if (s->picture_structure!= PICT_FRAME) {
  1450. int i;
  1451. for (i = 0; i < 4; i++) {
  1452. if (s->picture_structure == PICT_BOTTOM_FIELD) {
  1453. s->current_picture.f->data[i] +=
  1454. s->current_picture.f->linesize[i];
  1455. }
  1456. s->current_picture.f->linesize[i] *= 2;
  1457. s->last_picture.f->linesize[i] *= 2;
  1458. s->next_picture.f->linesize[i] *= 2;
  1459. }
  1460. }
  1461. if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  1462. s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
  1463. s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
  1464. } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
  1465. s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
  1466. s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
  1467. } else {
  1468. s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
  1469. s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
  1470. }
  1471. if (s->dct_error_sum) {
  1472. assert(s->noise_reduction && s->encoding);
  1473. update_noise_reduction(s);
  1474. }
  1475. return 0;
  1476. }
  1477. static void write_pass1_stats(MpegEncContext *s)
  1478. {
  1479. snprintf(s->avctx->stats_out, 256,
  1480. "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d "
  1481. "fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d "
  1482. "hbits:%d;\n",
  1483. s->current_picture_ptr->f->display_picture_number,
  1484. s->current_picture_ptr->f->coded_picture_number,
  1485. s->pict_type,
  1486. s->current_picture.f->quality,
  1487. s->i_tex_bits,
  1488. s->p_tex_bits,
  1489. s->mv_bits,
  1490. s->misc_bits,
  1491. s->f_code,
  1492. s->b_code,
  1493. s->current_picture.mc_mb_var_sum,
  1494. s->current_picture.mb_var_sum,
  1495. s->i_count, s->skip_count,
  1496. s->header_bits);
  1497. }
  1498. int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
  1499. const AVFrame *pic_arg, int *got_packet)
  1500. {
  1501. MpegEncContext *s = avctx->priv_data;
  1502. int i, stuffing_count, ret;
  1503. int context_count = s->slice_context_count;
  1504. s->picture_in_gop_number++;
  1505. if (load_input_picture(s, pic_arg) < 0)
  1506. return -1;
  1507. if (select_input_picture(s) < 0) {
  1508. return -1;
  1509. }
  1510. /* output? */
  1511. if (s->new_picture.f->data[0]) {
  1512. uint8_t *sd;
  1513. if (!pkt->data &&
  1514. (ret = ff_alloc_packet(pkt, s->mb_width*s->mb_height*MAX_MB_BYTES)) < 0)
  1515. return ret;
  1516. if (s->mb_info) {
  1517. s->mb_info_ptr = av_packet_new_side_data(pkt,
  1518. AV_PKT_DATA_H263_MB_INFO,
  1519. s->mb_width*s->mb_height*12);
  1520. s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;
  1521. }
  1522. for (i = 0; i < context_count; i++) {
  1523. int start_y = s->thread_context[i]->start_mb_y;
  1524. int end_y = s->thread_context[i]-> end_mb_y;
  1525. int h = s->mb_height;
  1526. uint8_t *start = pkt->data + (size_t)(((int64_t) pkt->size) * start_y / h);
  1527. uint8_t *end = pkt->data + (size_t)(((int64_t) pkt->size) * end_y / h);
  1528. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1529. }
  1530. s->pict_type = s->new_picture.f->pict_type;
  1531. //emms_c();
  1532. ret = frame_start(s);
  1533. if (ret < 0)
  1534. return ret;
  1535. vbv_retry:
  1536. if (encode_picture(s, s->picture_number) < 0)
  1537. return -1;
  1538. #if FF_API_STAT_BITS
  1539. FF_DISABLE_DEPRECATION_WARNINGS
  1540. avctx->header_bits = s->header_bits;
  1541. avctx->mv_bits = s->mv_bits;
  1542. avctx->misc_bits = s->misc_bits;
  1543. avctx->i_tex_bits = s->i_tex_bits;
  1544. avctx->p_tex_bits = s->p_tex_bits;
  1545. avctx->i_count = s->i_count;
  1546. // FIXME f/b_count in avctx
  1547. avctx->p_count = s->mb_num - s->i_count - s->skip_count;
  1548. avctx->skip_count = s->skip_count;
  1549. FF_ENABLE_DEPRECATION_WARNINGS
  1550. #endif
  1551. frame_end(s);
  1552. sd = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
  1553. sizeof(int));
  1554. if (!sd)
  1555. return AVERROR(ENOMEM);
  1556. *(int *)sd = s->current_picture.f->quality;
  1557. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1558. ff_mjpeg_encode_picture_trailer(&s->pb, s->header_bits);
  1559. if (avctx->rc_buffer_size) {
  1560. RateControlContext *rcc = &s->rc_context;
  1561. int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1562. if (put_bits_count(&s->pb) > max_size &&
  1563. s->lambda < s->lmax) {
  1564. s->next_lambda = FFMAX(s->lambda + 1, s->lambda *
  1565. (s->qscale + 1) / s->qscale);
  1566. if (s->adaptive_quant) {
  1567. int i;
  1568. for (i = 0; i < s->mb_height * s->mb_stride; i++)
  1569. s->lambda_table[i] =
  1570. FFMAX(s->lambda_table[i] + 1,
  1571. s->lambda_table[i] * (s->qscale + 1) /
  1572. s->qscale);
  1573. }
  1574. s->mb_skipped = 0; // done in frame_start()
  1575. // done in encode_picture() so we must undo it
  1576. if (s->pict_type == AV_PICTURE_TYPE_P) {
  1577. if (s->flipflop_rounding ||
  1578. s->codec_id == AV_CODEC_ID_H263P ||
  1579. s->codec_id == AV_CODEC_ID_MPEG4)
  1580. s->no_rounding ^= 1;
  1581. }
  1582. if (s->pict_type != AV_PICTURE_TYPE_B) {
  1583. s->time_base = s->last_time_base;
  1584. s->last_non_b_time = s->time - s->pp_time;
  1585. }
  1586. for (i = 0; i < context_count; i++) {
  1587. PutBitContext *pb = &s->thread_context[i]->pb;
  1588. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1589. }
  1590. goto vbv_retry;
  1591. }
  1592. assert(s->avctx->rc_max_rate);
  1593. }
  1594. if (s->avctx->flags & AV_CODEC_FLAG_PASS1)
  1595. write_pass1_stats(s);
  1596. for (i = 0; i < 4; i++) {
  1597. s->current_picture_ptr->encoding_error[i] = s->current_picture.encoding_error[i];
  1598. avctx->error[i] += s->current_picture_ptr->encoding_error[i];
  1599. }
  1600. if (s->avctx->flags & AV_CODEC_FLAG_PASS1)
  1601. assert(put_bits_count(&s->pb) == s->header_bits + s->mv_bits +
  1602. s->misc_bits + s->i_tex_bits +
  1603. s->p_tex_bits);
  1604. flush_put_bits(&s->pb);
  1605. s->frame_bits = put_bits_count(&s->pb);
  1606. stuffing_count = ff_vbv_update(s, s->frame_bits);
  1607. if (stuffing_count) {
  1608. if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
  1609. stuffing_count + 50) {
  1610. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1611. return -1;
  1612. }
  1613. switch (s->codec_id) {
  1614. case AV_CODEC_ID_MPEG1VIDEO:
  1615. case AV_CODEC_ID_MPEG2VIDEO:
  1616. while (stuffing_count--) {
  1617. put_bits(&s->pb, 8, 0);
  1618. }
  1619. break;
  1620. case AV_CODEC_ID_MPEG4:
  1621. put_bits(&s->pb, 16, 0);
  1622. put_bits(&s->pb, 16, 0x1C3);
  1623. stuffing_count -= 4;
  1624. while (stuffing_count--) {
  1625. put_bits(&s->pb, 8, 0xFF);
  1626. }
  1627. break;
  1628. default:
  1629. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1630. }
  1631. flush_put_bits(&s->pb);
  1632. s->frame_bits = put_bits_count(&s->pb);
  1633. }
  1634. /* update MPEG-1/2 vbv_delay for CBR */
  1635. if (s->avctx->rc_max_rate &&
  1636. s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  1637. s->out_format == FMT_MPEG1 &&
  1638. 90000LL * (avctx->rc_buffer_size - 1) <=
  1639. s->avctx->rc_max_rate * 0xFFFFLL) {
  1640. AVCPBProperties *props;
  1641. size_t props_size;
  1642. int vbv_delay, min_delay;
  1643. double inbits = s->avctx->rc_max_rate *
  1644. av_q2d(s->avctx->time_base);
  1645. int minbits = s->frame_bits - 8 *
  1646. (s->vbv_delay_ptr - s->pb.buf - 1);
  1647. double bits = s->rc_context.buffer_index + minbits - inbits;
  1648. if (bits < 0)
  1649. av_log(s->avctx, AV_LOG_ERROR,
  1650. "Internal error, negative bits\n");
  1651. assert(s->repeat_first_field == 0);
  1652. vbv_delay = bits * 90000 / s->avctx->rc_max_rate;
  1653. min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /
  1654. s->avctx->rc_max_rate;
  1655. vbv_delay = FFMAX(vbv_delay, min_delay);
  1656. assert(vbv_delay < 0xFFFF);
  1657. s->vbv_delay_ptr[0] &= 0xF8;
  1658. s->vbv_delay_ptr[0] |= vbv_delay >> 13;
  1659. s->vbv_delay_ptr[1] = vbv_delay >> 5;
  1660. s->vbv_delay_ptr[2] &= 0x07;
  1661. s->vbv_delay_ptr[2] |= vbv_delay << 3;
  1662. props = av_cpb_properties_alloc(&props_size);
  1663. if (!props)
  1664. return AVERROR(ENOMEM);
  1665. props->vbv_delay = vbv_delay * 300;
  1666. ret = av_packet_add_side_data(pkt, AV_PKT_DATA_CPB_PROPERTIES,
  1667. (uint8_t*)props, props_size);
  1668. if (ret < 0) {
  1669. av_freep(&props);
  1670. return ret;
  1671. }
  1672. #if FF_API_VBV_DELAY
  1673. FF_DISABLE_DEPRECATION_WARNINGS
  1674. avctx->vbv_delay = vbv_delay * 300;
  1675. FF_ENABLE_DEPRECATION_WARNINGS
  1676. #endif
  1677. }
  1678. s->total_bits += s->frame_bits;
  1679. #if FF_API_STAT_BITS
  1680. FF_DISABLE_DEPRECATION_WARNINGS
  1681. avctx->frame_bits = s->frame_bits;
  1682. FF_ENABLE_DEPRECATION_WARNINGS
  1683. #endif
  1684. pkt->pts = s->current_picture.f->pts;
  1685. if (!s->low_delay && s->pict_type != AV_PICTURE_TYPE_B) {
  1686. if (!s->current_picture.f->coded_picture_number)
  1687. pkt->dts = pkt->pts - s->dts_delta;
  1688. else
  1689. pkt->dts = s->reordered_pts;
  1690. s->reordered_pts = pkt->pts;
  1691. } else
  1692. pkt->dts = pkt->pts;
  1693. if (s->current_picture.f->key_frame)
  1694. pkt->flags |= AV_PKT_FLAG_KEY;
  1695. if (s->mb_info)
  1696. av_packet_shrink_side_data(pkt, AV_PKT_DATA_H263_MB_INFO, s->mb_info_size);
  1697. } else {
  1698. s->frame_bits = 0;
  1699. }
  1700. assert((s->frame_bits & 7) == 0);
  1701. pkt->size = s->frame_bits / 8;
  1702. *got_packet = !!pkt->size;
  1703. return 0;
  1704. }
  1705. static inline void dct_single_coeff_elimination(MpegEncContext *s,
  1706. int n, int threshold)
  1707. {
  1708. static const char tab[64] = {
  1709. 3, 2, 2, 1, 1, 1, 1, 1,
  1710. 1, 1, 1, 1, 1, 1, 1, 1,
  1711. 1, 1, 1, 1, 1, 1, 1, 1,
  1712. 0, 0, 0, 0, 0, 0, 0, 0,
  1713. 0, 0, 0, 0, 0, 0, 0, 0,
  1714. 0, 0, 0, 0, 0, 0, 0, 0,
  1715. 0, 0, 0, 0, 0, 0, 0, 0,
  1716. 0, 0, 0, 0, 0, 0, 0, 0
  1717. };
  1718. int score = 0;
  1719. int run = 0;
  1720. int i;
  1721. int16_t *block = s->block[n];
  1722. const int last_index = s->block_last_index[n];
  1723. int skip_dc;
  1724. if (threshold < 0) {
  1725. skip_dc = 0;
  1726. threshold = -threshold;
  1727. } else
  1728. skip_dc = 1;
  1729. /* Are all we could set to zero already zero? */
  1730. if (last_index <= skip_dc - 1)
  1731. return;
  1732. for (i = 0; i <= last_index; i++) {
  1733. const int j = s->intra_scantable.permutated[i];
  1734. const int level = FFABS(block[j]);
  1735. if (level == 1) {
  1736. if (skip_dc && i == 0)
  1737. continue;
  1738. score += tab[run];
  1739. run = 0;
  1740. } else if (level > 1) {
  1741. return;
  1742. } else {
  1743. run++;
  1744. }
  1745. }
  1746. if (score >= threshold)
  1747. return;
  1748. for (i = skip_dc; i <= last_index; i++) {
  1749. const int j = s->intra_scantable.permutated[i];
  1750. block[j] = 0;
  1751. }
  1752. if (block[0])
  1753. s->block_last_index[n] = 0;
  1754. else
  1755. s->block_last_index[n] = -1;
  1756. }
  1757. static inline void clip_coeffs(MpegEncContext *s, int16_t *block,
  1758. int last_index)
  1759. {
  1760. int i;
  1761. const int maxlevel = s->max_qcoeff;
  1762. const int minlevel = s->min_qcoeff;
  1763. int overflow = 0;
  1764. if (s->mb_intra) {
  1765. i = 1; // skip clipping of intra dc
  1766. } else
  1767. i = 0;
  1768. for (; i <= last_index; i++) {
  1769. const int j = s->intra_scantable.permutated[i];
  1770. int level = block[j];
  1771. if (level > maxlevel) {
  1772. level = maxlevel;
  1773. overflow++;
  1774. } else if (level < minlevel) {
  1775. level = minlevel;
  1776. overflow++;
  1777. }
  1778. block[j] = level;
  1779. }
  1780. if (overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1781. av_log(s->avctx, AV_LOG_INFO,
  1782. "warning, clipping %d dct coefficients to %d..%d\n",
  1783. overflow, minlevel, maxlevel);
  1784. }
  1785. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride)
  1786. {
  1787. int x, y;
  1788. // FIXME optimize
  1789. for (y = 0; y < 8; y++) {
  1790. for (x = 0; x < 8; x++) {
  1791. int x2, y2;
  1792. int sum = 0;
  1793. int sqr = 0;
  1794. int count = 0;
  1795. for (y2 = FFMAX(y - 1, 0); y2 < FFMIN(8, y + 2); y2++) {
  1796. for (x2= FFMAX(x - 1, 0); x2 < FFMIN(8, x + 2); x2++) {
  1797. int v = ptr[x2 + y2 * stride];
  1798. sum += v;
  1799. sqr += v * v;
  1800. count++;
  1801. }
  1802. }
  1803. weight[x + 8 * y]= (36 * ff_sqrt(count * sqr - sum * sum)) / count;
  1804. }
  1805. }
  1806. }
  1807. static av_always_inline void encode_mb_internal(MpegEncContext *s,
  1808. int motion_x, int motion_y,
  1809. int mb_block_height,
  1810. int mb_block_count)
  1811. {
  1812. int16_t weight[8][64];
  1813. int16_t orig[8][64];
  1814. const int mb_x = s->mb_x;
  1815. const int mb_y = s->mb_y;
  1816. int i;
  1817. int skip_dct[8];
  1818. int dct_offset = s->linesize * 8; // default for progressive frames
  1819. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1820. ptrdiff_t wrap_y, wrap_c;
  1821. for (i = 0; i < mb_block_count; i++)
  1822. skip_dct[i] = s->skipdct;
  1823. if (s->adaptive_quant) {
  1824. const int last_qp = s->qscale;
  1825. const int mb_xy = mb_x + mb_y * s->mb_stride;
  1826. s->lambda = s->lambda_table[mb_xy];
  1827. update_qscale(s);
  1828. if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {
  1829. s->qscale = s->current_picture_ptr->qscale_table[mb_xy];
  1830. s->dquant = s->qscale - last_qp;
  1831. if (s->out_format == FMT_H263) {
  1832. s->dquant = av_clip(s->dquant, -2, 2);
  1833. if (s->codec_id == AV_CODEC_ID_MPEG4) {
  1834. if (!s->mb_intra) {
  1835. if (s->pict_type == AV_PICTURE_TYPE_B) {
  1836. if (s->dquant & 1 || s->mv_dir & MV_DIRECT)
  1837. s->dquant = 0;
  1838. }
  1839. if (s->mv_type == MV_TYPE_8X8)
  1840. s->dquant = 0;
  1841. }
  1842. }
  1843. }
  1844. }
  1845. ff_set_qscale(s, last_qp + s->dquant);
  1846. } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)
  1847. ff_set_qscale(s, s->qscale + s->dquant);
  1848. wrap_y = s->linesize;
  1849. wrap_c = s->uvlinesize;
  1850. ptr_y = s->new_picture.f->data[0] +
  1851. (mb_y * 16 * wrap_y) + mb_x * 16;
  1852. ptr_cb = s->new_picture.f->data[1] +
  1853. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1854. ptr_cr = s->new_picture.f->data[2] +
  1855. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1856. if (mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) {
  1857. uint8_t *ebuf = s->sc.edge_emu_buffer + 32;
  1858. s->vdsp.emulated_edge_mc(ebuf, ptr_y,
  1859. wrap_y, wrap_y,
  1860. 16, 16, mb_x * 16, mb_y * 16,
  1861. s->width, s->height);
  1862. ptr_y = ebuf;
  1863. s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb,
  1864. wrap_c, wrap_c,
  1865. 8, mb_block_height, mb_x * 8, mb_y * 8,
  1866. s->width >> 1, s->height >> 1);
  1867. ptr_cb = ebuf + 18 * wrap_y;
  1868. s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr,
  1869. wrap_c, wrap_c,
  1870. 8, mb_block_height, mb_x * 8, mb_y * 8,
  1871. s->width >> 1, s->height >> 1);
  1872. ptr_cr = ebuf + 18 * wrap_y + 8;
  1873. }
  1874. if (s->mb_intra) {
  1875. if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1876. int progressive_score, interlaced_score;
  1877. s->interlaced_dct = 0;
  1878. progressive_score = s->mecc.ildct_cmp[4](s, ptr_y, NULL, wrap_y, 8) +
  1879. s->mecc.ildct_cmp[4](s, ptr_y + wrap_y * 8,
  1880. NULL, wrap_y, 8) - 400;
  1881. if (progressive_score > 0) {
  1882. interlaced_score = s->mecc.ildct_cmp[4](s, ptr_y,
  1883. NULL, wrap_y * 2, 8) +
  1884. s->mecc.ildct_cmp[4](s, ptr_y + wrap_y,
  1885. NULL, wrap_y * 2, 8);
  1886. if (progressive_score > interlaced_score) {
  1887. s->interlaced_dct = 1;
  1888. dct_offset = wrap_y;
  1889. wrap_y <<= 1;
  1890. if (s->chroma_format == CHROMA_422)
  1891. wrap_c <<= 1;
  1892. }
  1893. }
  1894. }
  1895. s->pdsp.get_pixels(s->block[0], ptr_y, wrap_y);
  1896. s->pdsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
  1897. s->pdsp.get_pixels(s->block[2], ptr_y + dct_offset, wrap_y);
  1898. s->pdsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  1899. if (s->avctx->flags & AV_CODEC_FLAG_GRAY) {
  1900. skip_dct[4] = 1;
  1901. skip_dct[5] = 1;
  1902. } else {
  1903. s->pdsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1904. s->pdsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1905. if (!s->chroma_y_shift) { /* 422 */
  1906. s->pdsp.get_pixels(s->block[6],
  1907. ptr_cb + (dct_offset >> 1), wrap_c);
  1908. s->pdsp.get_pixels(s->block[7],
  1909. ptr_cr + (dct_offset >> 1), wrap_c);
  1910. }
  1911. }
  1912. } else {
  1913. op_pixels_func (*op_pix)[4];
  1914. qpel_mc_func (*op_qpix)[16];
  1915. uint8_t *dest_y, *dest_cb, *dest_cr;
  1916. dest_y = s->dest[0];
  1917. dest_cb = s->dest[1];
  1918. dest_cr = s->dest[2];
  1919. if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {
  1920. op_pix = s->hdsp.put_pixels_tab;
  1921. op_qpix = s->qdsp.put_qpel_pixels_tab;
  1922. } else {
  1923. op_pix = s->hdsp.put_no_rnd_pixels_tab;
  1924. op_qpix = s->qdsp.put_no_rnd_qpel_pixels_tab;
  1925. }
  1926. if (s->mv_dir & MV_DIR_FORWARD) {
  1927. ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 0,
  1928. s->last_picture.f->data,
  1929. op_pix, op_qpix);
  1930. op_pix = s->hdsp.avg_pixels_tab;
  1931. op_qpix = s->qdsp.avg_qpel_pixels_tab;
  1932. }
  1933. if (s->mv_dir & MV_DIR_BACKWARD) {
  1934. ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 1,
  1935. s->next_picture.f->data,
  1936. op_pix, op_qpix);
  1937. }
  1938. if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1939. int progressive_score, interlaced_score;
  1940. s->interlaced_dct = 0;
  1941. progressive_score = s->mecc.ildct_cmp[0](s, dest_y, ptr_y, wrap_y, 8) +
  1942. s->mecc.ildct_cmp[0](s, dest_y + wrap_y * 8,
  1943. ptr_y + wrap_y * 8,
  1944. wrap_y, 8) - 400;
  1945. if (s->avctx->ildct_cmp == FF_CMP_VSSE)
  1946. progressive_score -= 400;
  1947. if (progressive_score > 0) {
  1948. interlaced_score = s->mecc.ildct_cmp[0](s, dest_y, ptr_y,
  1949. wrap_y * 2, 8) +
  1950. s->mecc.ildct_cmp[0](s, dest_y + wrap_y,
  1951. ptr_y + wrap_y,
  1952. wrap_y * 2, 8);
  1953. if (progressive_score > interlaced_score) {
  1954. s->interlaced_dct = 1;
  1955. dct_offset = wrap_y;
  1956. wrap_y <<= 1;
  1957. if (s->chroma_format == CHROMA_422)
  1958. wrap_c <<= 1;
  1959. }
  1960. }
  1961. }
  1962. s->pdsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);
  1963. s->pdsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1964. s->pdsp.diff_pixels(s->block[2], ptr_y + dct_offset,
  1965. dest_y + dct_offset, wrap_y);
  1966. s->pdsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,
  1967. dest_y + dct_offset + 8, wrap_y);
  1968. if (s->avctx->flags & AV_CODEC_FLAG_GRAY) {
  1969. skip_dct[4] = 1;
  1970. skip_dct[5] = 1;
  1971. } else {
  1972. s->pdsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1973. s->pdsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1974. if (!s->chroma_y_shift) { /* 422 */
  1975. s->pdsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),
  1976. dest_cb + (dct_offset >> 1), wrap_c);
  1977. s->pdsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),
  1978. dest_cr + (dct_offset >> 1), wrap_c);
  1979. }
  1980. }
  1981. /* pre quantization */
  1982. if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <
  1983. 2 * s->qscale * s->qscale) {
  1984. // FIXME optimize
  1985. if (s->mecc.sad[1](NULL, ptr_y, dest_y, wrap_y, 8) < 20 * s->qscale)
  1986. skip_dct[0] = 1;
  1987. if (s->mecc.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20 * s->qscale)
  1988. skip_dct[1] = 1;
  1989. if (s->mecc.sad[1](NULL, ptr_y + dct_offset, dest_y + dct_offset,
  1990. wrap_y, 8) < 20 * s->qscale)
  1991. skip_dct[2] = 1;
  1992. if (s->mecc.sad[1](NULL, ptr_y + dct_offset + 8, dest_y + dct_offset + 8,
  1993. wrap_y, 8) < 20 * s->qscale)
  1994. skip_dct[3] = 1;
  1995. if (s->mecc.sad[1](NULL, ptr_cb, dest_cb, wrap_c, 8) < 20 * s->qscale)
  1996. skip_dct[4] = 1;
  1997. if (s->mecc.sad[1](NULL, ptr_cr, dest_cr, wrap_c, 8) < 20 * s->qscale)
  1998. skip_dct[5] = 1;
  1999. if (!s->chroma_y_shift) { /* 422 */
  2000. if (s->mecc.sad[1](NULL, ptr_cb + (dct_offset >> 1),
  2001. dest_cb + (dct_offset >> 1),
  2002. wrap_c, 8) < 20 * s->qscale)
  2003. skip_dct[6] = 1;
  2004. if (s->mecc.sad[1](NULL, ptr_cr + (dct_offset >> 1),
  2005. dest_cr + (dct_offset >> 1),
  2006. wrap_c, 8) < 20 * s->qscale)
  2007. skip_dct[7] = 1;
  2008. }
  2009. }
  2010. }
  2011. if (s->quantizer_noise_shaping) {
  2012. if (!skip_dct[0])
  2013. get_visual_weight(weight[0], ptr_y , wrap_y);
  2014. if (!skip_dct[1])
  2015. get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  2016. if (!skip_dct[2])
  2017. get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  2018. if (!skip_dct[3])
  2019. get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  2020. if (!skip_dct[4])
  2021. get_visual_weight(weight[4], ptr_cb , wrap_c);
  2022. if (!skip_dct[5])
  2023. get_visual_weight(weight[5], ptr_cr , wrap_c);
  2024. if (!s->chroma_y_shift) { /* 422 */
  2025. if (!skip_dct[6])
  2026. get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),
  2027. wrap_c);
  2028. if (!skip_dct[7])
  2029. get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),
  2030. wrap_c);
  2031. }
  2032. memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);
  2033. }
  2034. /* DCT & quantize */
  2035. assert(s->out_format != FMT_MJPEG || s->qscale == 8);
  2036. {
  2037. for (i = 0; i < mb_block_count; i++) {
  2038. if (!skip_dct[i]) {
  2039. int overflow;
  2040. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  2041. // FIXME we could decide to change to quantizer instead of
  2042. // clipping
  2043. // JS: I don't think that would be a good idea it could lower
  2044. // quality instead of improve it. Just INTRADC clipping
  2045. // deserves changes in quantizer
  2046. if (overflow)
  2047. clip_coeffs(s, s->block[i], s->block_last_index[i]);
  2048. } else
  2049. s->block_last_index[i] = -1;
  2050. }
  2051. if (s->quantizer_noise_shaping) {
  2052. for (i = 0; i < mb_block_count; i++) {
  2053. if (!skip_dct[i]) {
  2054. s->block_last_index[i] =
  2055. dct_quantize_refine(s, s->block[i], weight[i],
  2056. orig[i], i, s->qscale);
  2057. }
  2058. }
  2059. }
  2060. if (s->luma_elim_threshold && !s->mb_intra)
  2061. for (i = 0; i < 4; i++)
  2062. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  2063. if (s->chroma_elim_threshold && !s->mb_intra)
  2064. for (i = 4; i < mb_block_count; i++)
  2065. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  2066. if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
  2067. for (i = 0; i < mb_block_count; i++) {
  2068. if (s->block_last_index[i] == -1)
  2069. s->coded_score[i] = INT_MAX / 256;
  2070. }
  2071. }
  2072. }
  2073. if ((s->avctx->flags & AV_CODEC_FLAG_GRAY) && s->mb_intra) {
  2074. s->block_last_index[4] =
  2075. s->block_last_index[5] = 0;
  2076. s->block[4][0] =
  2077. s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;
  2078. }
  2079. // non c quantize code returns incorrect block_last_index FIXME
  2080. if (s->alternate_scan && s->dct_quantize != ff_dct_quantize_c) {
  2081. for (i = 0; i < mb_block_count; i++) {
  2082. int j;
  2083. if (s->block_last_index[i] > 0) {
  2084. for (j = 63; j > 0; j--) {
  2085. if (s->block[i][s->intra_scantable.permutated[j]])
  2086. break;
  2087. }
  2088. s->block_last_index[i] = j;
  2089. }
  2090. }
  2091. }
  2092. /* huffman encode */
  2093. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  2094. case AV_CODEC_ID_MPEG1VIDEO:
  2095. case AV_CODEC_ID_MPEG2VIDEO:
  2096. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2097. ff_mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  2098. break;
  2099. case AV_CODEC_ID_MPEG4:
  2100. if (CONFIG_MPEG4_ENCODER)
  2101. ff_mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  2102. break;
  2103. case AV_CODEC_ID_MSMPEG4V2:
  2104. case AV_CODEC_ID_MSMPEG4V3:
  2105. case AV_CODEC_ID_WMV1:
  2106. if (CONFIG_MSMPEG4_ENCODER)
  2107. ff_msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  2108. break;
  2109. case AV_CODEC_ID_WMV2:
  2110. if (CONFIG_WMV2_ENCODER)
  2111. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  2112. break;
  2113. case AV_CODEC_ID_H261:
  2114. if (CONFIG_H261_ENCODER)
  2115. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  2116. break;
  2117. case AV_CODEC_ID_H263:
  2118. case AV_CODEC_ID_H263P:
  2119. case AV_CODEC_ID_FLV1:
  2120. case AV_CODEC_ID_RV10:
  2121. case AV_CODEC_ID_RV20:
  2122. if (CONFIG_H263_ENCODER)
  2123. ff_h263_encode_mb(s, s->block, motion_x, motion_y);
  2124. break;
  2125. case AV_CODEC_ID_MJPEG:
  2126. if (CONFIG_MJPEG_ENCODER)
  2127. ff_mjpeg_encode_mb(s, s->block);
  2128. break;
  2129. default:
  2130. assert(0);
  2131. }
  2132. }
  2133. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  2134. {
  2135. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  2136. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  2137. }
  2138. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2139. int i;
  2140. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  2141. /* MPEG-1 */
  2142. d->mb_skip_run= s->mb_skip_run;
  2143. for(i=0; i<3; i++)
  2144. d->last_dc[i] = s->last_dc[i];
  2145. /* statistics */
  2146. d->mv_bits= s->mv_bits;
  2147. d->i_tex_bits= s->i_tex_bits;
  2148. d->p_tex_bits= s->p_tex_bits;
  2149. d->i_count= s->i_count;
  2150. d->f_count= s->f_count;
  2151. d->b_count= s->b_count;
  2152. d->skip_count= s->skip_count;
  2153. d->misc_bits= s->misc_bits;
  2154. d->last_bits= 0;
  2155. d->mb_skipped= 0;
  2156. d->qscale= s->qscale;
  2157. d->dquant= s->dquant;
  2158. d->esc3_level_length= s->esc3_level_length;
  2159. }
  2160. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2161. int i;
  2162. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  2163. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  2164. /* MPEG-1 */
  2165. d->mb_skip_run= s->mb_skip_run;
  2166. for(i=0; i<3; i++)
  2167. d->last_dc[i] = s->last_dc[i];
  2168. /* statistics */
  2169. d->mv_bits= s->mv_bits;
  2170. d->i_tex_bits= s->i_tex_bits;
  2171. d->p_tex_bits= s->p_tex_bits;
  2172. d->i_count= s->i_count;
  2173. d->f_count= s->f_count;
  2174. d->b_count= s->b_count;
  2175. d->skip_count= s->skip_count;
  2176. d->misc_bits= s->misc_bits;
  2177. d->mb_intra= s->mb_intra;
  2178. d->mb_skipped= s->mb_skipped;
  2179. d->mv_type= s->mv_type;
  2180. d->mv_dir= s->mv_dir;
  2181. d->pb= s->pb;
  2182. if(s->data_partitioning){
  2183. d->pb2= s->pb2;
  2184. d->tex_pb= s->tex_pb;
  2185. }
  2186. d->block= s->block;
  2187. for(i=0; i<8; i++)
  2188. d->block_last_index[i]= s->block_last_index[i];
  2189. d->interlaced_dct= s->interlaced_dct;
  2190. d->qscale= s->qscale;
  2191. d->esc3_level_length= s->esc3_level_length;
  2192. }
  2193. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  2194. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  2195. int *dmin, int *next_block, int motion_x, int motion_y)
  2196. {
  2197. int score;
  2198. uint8_t *dest_backup[3];
  2199. copy_context_before_encode(s, backup, type);
  2200. s->block= s->blocks[*next_block];
  2201. s->pb= pb[*next_block];
  2202. if(s->data_partitioning){
  2203. s->pb2 = pb2 [*next_block];
  2204. s->tex_pb= tex_pb[*next_block];
  2205. }
  2206. if(*next_block){
  2207. memcpy(dest_backup, s->dest, sizeof(s->dest));
  2208. s->dest[0] = s->sc.rd_scratchpad;
  2209. s->dest[1] = s->sc.rd_scratchpad + 16*s->linesize;
  2210. s->dest[2] = s->sc.rd_scratchpad + 16*s->linesize + 8;
  2211. assert(s->linesize >= 32); //FIXME
  2212. }
  2213. encode_mb(s, motion_x, motion_y);
  2214. score= put_bits_count(&s->pb);
  2215. if(s->data_partitioning){
  2216. score+= put_bits_count(&s->pb2);
  2217. score+= put_bits_count(&s->tex_pb);
  2218. }
  2219. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  2220. ff_mpv_decode_mb(s, s->block);
  2221. score *= s->lambda2;
  2222. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  2223. }
  2224. if(*next_block){
  2225. memcpy(s->dest, dest_backup, sizeof(s->dest));
  2226. }
  2227. if(score<*dmin){
  2228. *dmin= score;
  2229. *next_block^=1;
  2230. copy_context_after_encode(best, s, type);
  2231. }
  2232. }
  2233. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  2234. uint32_t *sq = ff_square_tab + 256;
  2235. int acc=0;
  2236. int x,y;
  2237. if(w==16 && h==16)
  2238. return s->mecc.sse[0](NULL, src1, src2, stride, 16);
  2239. else if(w==8 && h==8)
  2240. return s->mecc.sse[1](NULL, src1, src2, stride, 8);
  2241. for(y=0; y<h; y++){
  2242. for(x=0; x<w; x++){
  2243. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  2244. }
  2245. }
  2246. assert(acc>=0);
  2247. return acc;
  2248. }
  2249. static int sse_mb(MpegEncContext *s){
  2250. int w= 16;
  2251. int h= 16;
  2252. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2253. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2254. if(w==16 && h==16)
  2255. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  2256. 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) +
  2257. 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) +
  2258. 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);
  2259. }else{
  2260. 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) +
  2261. 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) +
  2262. 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);
  2263. }
  2264. else
  2265. 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)
  2266. +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)
  2267. +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);
  2268. }
  2269. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  2270. MpegEncContext *s= *(void**)arg;
  2271. s->me.pre_pass=1;
  2272. s->me.dia_size= s->avctx->pre_dia_size;
  2273. s->first_slice_line=1;
  2274. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  2275. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  2276. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2277. }
  2278. s->first_slice_line=0;
  2279. }
  2280. s->me.pre_pass=0;
  2281. return 0;
  2282. }
  2283. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  2284. MpegEncContext *s= *(void**)arg;
  2285. s->me.dia_size= s->avctx->dia_size;
  2286. s->first_slice_line=1;
  2287. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  2288. s->mb_x=0; //for block init below
  2289. ff_init_block_index(s);
  2290. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  2291. s->block_index[0]+=2;
  2292. s->block_index[1]+=2;
  2293. s->block_index[2]+=2;
  2294. s->block_index[3]+=2;
  2295. /* compute motion vector & mb_type and store in context */
  2296. if(s->pict_type==AV_PICTURE_TYPE_B)
  2297. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  2298. else
  2299. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2300. }
  2301. s->first_slice_line=0;
  2302. }
  2303. return 0;
  2304. }
  2305. static int mb_var_thread(AVCodecContext *c, void *arg){
  2306. MpegEncContext *s= *(void**)arg;
  2307. int mb_x, mb_y;
  2308. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2309. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2310. int xx = mb_x * 16;
  2311. int yy = mb_y * 16;
  2312. uint8_t *pix = s->new_picture.f->data[0] + (yy * s->linesize) + xx;
  2313. int varc;
  2314. int sum = s->mpvencdsp.pix_sum(pix, s->linesize);
  2315. varc = (s->mpvencdsp.pix_norm1(pix, s->linesize) -
  2316. (((unsigned) sum * sum) >> 8) + 500 + 128) >> 8;
  2317. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  2318. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  2319. s->me.mb_var_sum_temp += varc;
  2320. }
  2321. }
  2322. return 0;
  2323. }
  2324. static void write_slice_end(MpegEncContext *s){
  2325. if(CONFIG_MPEG4_ENCODER && s->codec_id==AV_CODEC_ID_MPEG4){
  2326. if(s->partitioned_frame){
  2327. ff_mpeg4_merge_partitions(s);
  2328. }
  2329. ff_mpeg4_stuffing(&s->pb);
  2330. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  2331. ff_mjpeg_encode_stuffing(&s->pb);
  2332. }
  2333. avpriv_align_put_bits(&s->pb);
  2334. flush_put_bits(&s->pb);
  2335. if ((s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->partitioned_frame)
  2336. s->misc_bits+= get_bits_diff(s);
  2337. }
  2338. static void write_mb_info(MpegEncContext *s)
  2339. {
  2340. uint8_t *ptr = s->mb_info_ptr + s->mb_info_size - 12;
  2341. int offset = put_bits_count(&s->pb);
  2342. int mba = s->mb_x + s->mb_width * (s->mb_y % s->gob_index);
  2343. int gobn = s->mb_y / s->gob_index;
  2344. int pred_x, pred_y;
  2345. if (CONFIG_H263_ENCODER)
  2346. ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  2347. bytestream_put_le32(&ptr, offset);
  2348. bytestream_put_byte(&ptr, s->qscale);
  2349. bytestream_put_byte(&ptr, gobn);
  2350. bytestream_put_le16(&ptr, mba);
  2351. bytestream_put_byte(&ptr, pred_x); /* hmv1 */
  2352. bytestream_put_byte(&ptr, pred_y); /* vmv1 */
  2353. /* 4MV not implemented */
  2354. bytestream_put_byte(&ptr, 0); /* hmv2 */
  2355. bytestream_put_byte(&ptr, 0); /* vmv2 */
  2356. }
  2357. static void update_mb_info(MpegEncContext *s, int startcode)
  2358. {
  2359. if (!s->mb_info)
  2360. return;
  2361. if (put_bits_count(&s->pb) - s->prev_mb_info*8 >= s->mb_info*8) {
  2362. s->mb_info_size += 12;
  2363. s->prev_mb_info = s->last_mb_info;
  2364. }
  2365. if (startcode) {
  2366. s->prev_mb_info = put_bits_count(&s->pb)/8;
  2367. /* This might have incremented mb_info_size above, and we return without
  2368. * actually writing any info into that slot yet. But in that case,
  2369. * this will be called again at the start of the after writing the
  2370. * start code, actually writing the mb info. */
  2371. return;
  2372. }
  2373. s->last_mb_info = put_bits_count(&s->pb)/8;
  2374. if (!s->mb_info_size)
  2375. s->mb_info_size += 12;
  2376. write_mb_info(s);
  2377. }
  2378. static int encode_thread(AVCodecContext *c, void *arg){
  2379. MpegEncContext *s= *(void**)arg;
  2380. int mb_x, mb_y;
  2381. int chr_h= 16>>s->chroma_y_shift;
  2382. int i, j;
  2383. MpegEncContext best_s = { 0 }, backup_s;
  2384. uint8_t bit_buf[2][MAX_MB_BYTES];
  2385. uint8_t bit_buf2[2][MAX_MB_BYTES];
  2386. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  2387. PutBitContext pb[2], pb2[2], tex_pb[2];
  2388. for(i=0; i<2; i++){
  2389. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  2390. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  2391. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  2392. }
  2393. s->last_bits= put_bits_count(&s->pb);
  2394. s->mv_bits=0;
  2395. s->misc_bits=0;
  2396. s->i_tex_bits=0;
  2397. s->p_tex_bits=0;
  2398. s->i_count=0;
  2399. s->f_count=0;
  2400. s->b_count=0;
  2401. s->skip_count=0;
  2402. for(i=0; i<3; i++){
  2403. /* init last dc values */
  2404. /* note: quant matrix value (8) is implied here */
  2405. s->last_dc[i] = 128 << s->intra_dc_precision;
  2406. s->current_picture.encoding_error[i] = 0;
  2407. }
  2408. s->mb_skip_run = 0;
  2409. memset(s->last_mv, 0, sizeof(s->last_mv));
  2410. s->last_mv_dir = 0;
  2411. switch(s->codec_id){
  2412. case AV_CODEC_ID_H263:
  2413. case AV_CODEC_ID_H263P:
  2414. case AV_CODEC_ID_FLV1:
  2415. if (CONFIG_H263_ENCODER)
  2416. s->gob_index = H263_GOB_HEIGHT(s->height);
  2417. break;
  2418. case AV_CODEC_ID_MPEG4:
  2419. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  2420. ff_mpeg4_init_partitions(s);
  2421. break;
  2422. }
  2423. s->resync_mb_x=0;
  2424. s->resync_mb_y=0;
  2425. s->first_slice_line = 1;
  2426. s->ptr_lastgob = s->pb.buf;
  2427. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2428. s->mb_x=0;
  2429. s->mb_y= mb_y;
  2430. ff_set_qscale(s, s->qscale);
  2431. ff_init_block_index(s);
  2432. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2433. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  2434. int mb_type= s->mb_type[xy];
  2435. // int d;
  2436. int dmin= INT_MAX;
  2437. int dir;
  2438. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  2439. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  2440. return -1;
  2441. }
  2442. if(s->data_partitioning){
  2443. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  2444. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  2445. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  2446. return -1;
  2447. }
  2448. }
  2449. s->mb_x = mb_x;
  2450. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  2451. ff_update_block_index(s);
  2452. if(CONFIG_H261_ENCODER && s->codec_id == AV_CODEC_ID_H261){
  2453. ff_h261_reorder_mb_index(s);
  2454. xy= s->mb_y*s->mb_stride + s->mb_x;
  2455. mb_type= s->mb_type[xy];
  2456. }
  2457. /* write gob / video packet header */
  2458. if(s->rtp_mode){
  2459. int current_packet_size, is_gob_start;
  2460. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  2461. is_gob_start = s->rtp_payload_size &&
  2462. current_packet_size >= s->rtp_payload_size &&
  2463. mb_y + mb_x > 0;
  2464. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  2465. switch(s->codec_id){
  2466. case AV_CODEC_ID_H263:
  2467. case AV_CODEC_ID_H263P:
  2468. if(!s->h263_slice_structured)
  2469. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  2470. break;
  2471. case AV_CODEC_ID_MPEG2VIDEO:
  2472. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  2473. case AV_CODEC_ID_MPEG1VIDEO:
  2474. if(s->mb_skip_run) is_gob_start=0;
  2475. break;
  2476. }
  2477. if(is_gob_start){
  2478. if(s->start_mb_y != mb_y || mb_x!=0){
  2479. write_slice_end(s);
  2480. if(CONFIG_MPEG4_ENCODER && s->codec_id==AV_CODEC_ID_MPEG4 && s->partitioned_frame){
  2481. ff_mpeg4_init_partitions(s);
  2482. }
  2483. }
  2484. assert((put_bits_count(&s->pb)&7) == 0);
  2485. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2486. if (s->error_rate && s->resync_mb_x + s->resync_mb_y > 0) {
  2487. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  2488. int d = 100 / s->error_rate;
  2489. if(r % d == 0){
  2490. current_packet_size=0;
  2491. s->pb.buf_ptr= s->ptr_lastgob;
  2492. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  2493. }
  2494. }
  2495. #if FF_API_RTP_CALLBACK
  2496. FF_DISABLE_DEPRECATION_WARNINGS
  2497. if (s->avctx->rtp_callback){
  2498. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  2499. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  2500. }
  2501. FF_ENABLE_DEPRECATION_WARNINGS
  2502. #endif
  2503. update_mb_info(s, 1);
  2504. switch(s->codec_id){
  2505. case AV_CODEC_ID_MPEG4:
  2506. if (CONFIG_MPEG4_ENCODER) {
  2507. ff_mpeg4_encode_video_packet_header(s);
  2508. ff_mpeg4_clean_buffers(s);
  2509. }
  2510. break;
  2511. case AV_CODEC_ID_MPEG1VIDEO:
  2512. case AV_CODEC_ID_MPEG2VIDEO:
  2513. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  2514. ff_mpeg1_encode_slice_header(s);
  2515. ff_mpeg1_clean_buffers(s);
  2516. }
  2517. break;
  2518. case AV_CODEC_ID_H263:
  2519. case AV_CODEC_ID_H263P:
  2520. if (CONFIG_H263_ENCODER)
  2521. ff_h263_encode_gob_header(s, mb_y);
  2522. break;
  2523. }
  2524. if (s->avctx->flags & AV_CODEC_FLAG_PASS1) {
  2525. int bits= put_bits_count(&s->pb);
  2526. s->misc_bits+= bits - s->last_bits;
  2527. s->last_bits= bits;
  2528. }
  2529. s->ptr_lastgob += current_packet_size;
  2530. s->first_slice_line=1;
  2531. s->resync_mb_x=mb_x;
  2532. s->resync_mb_y=mb_y;
  2533. }
  2534. }
  2535. if( (s->resync_mb_x == s->mb_x)
  2536. && s->resync_mb_y+1 == s->mb_y){
  2537. s->first_slice_line=0;
  2538. }
  2539. s->mb_skipped=0;
  2540. s->dquant=0; //only for QP_RD
  2541. update_mb_info(s, 0);
  2542. 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
  2543. int next_block=0;
  2544. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  2545. copy_context_before_encode(&backup_s, s, -1);
  2546. backup_s.pb= s->pb;
  2547. best_s.data_partitioning= s->data_partitioning;
  2548. best_s.partitioned_frame= s->partitioned_frame;
  2549. if(s->data_partitioning){
  2550. backup_s.pb2= s->pb2;
  2551. backup_s.tex_pb= s->tex_pb;
  2552. }
  2553. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  2554. s->mv_dir = MV_DIR_FORWARD;
  2555. s->mv_type = MV_TYPE_16X16;
  2556. s->mb_intra= 0;
  2557. s->mv[0][0][0] = s->p_mv_table[xy][0];
  2558. s->mv[0][0][1] = s->p_mv_table[xy][1];
  2559. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  2560. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2561. }
  2562. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  2563. s->mv_dir = MV_DIR_FORWARD;
  2564. s->mv_type = MV_TYPE_FIELD;
  2565. s->mb_intra= 0;
  2566. for(i=0; i<2; i++){
  2567. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2568. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2569. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2570. }
  2571. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  2572. &dmin, &next_block, 0, 0);
  2573. }
  2574. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  2575. s->mv_dir = MV_DIR_FORWARD;
  2576. s->mv_type = MV_TYPE_16X16;
  2577. s->mb_intra= 0;
  2578. s->mv[0][0][0] = 0;
  2579. s->mv[0][0][1] = 0;
  2580. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  2581. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2582. }
  2583. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  2584. s->mv_dir = MV_DIR_FORWARD;
  2585. s->mv_type = MV_TYPE_8X8;
  2586. s->mb_intra= 0;
  2587. for(i=0; i<4; i++){
  2588. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  2589. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  2590. }
  2591. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  2592. &dmin, &next_block, 0, 0);
  2593. }
  2594. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  2595. s->mv_dir = MV_DIR_FORWARD;
  2596. s->mv_type = MV_TYPE_16X16;
  2597. s->mb_intra= 0;
  2598. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2599. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2600. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  2601. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2602. }
  2603. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  2604. s->mv_dir = MV_DIR_BACKWARD;
  2605. s->mv_type = MV_TYPE_16X16;
  2606. s->mb_intra= 0;
  2607. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2608. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2609. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  2610. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  2611. }
  2612. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  2613. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2614. s->mv_type = MV_TYPE_16X16;
  2615. s->mb_intra= 0;
  2616. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2617. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2618. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2619. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2620. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  2621. &dmin, &next_block, 0, 0);
  2622. }
  2623. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  2624. s->mv_dir = MV_DIR_FORWARD;
  2625. s->mv_type = MV_TYPE_FIELD;
  2626. s->mb_intra= 0;
  2627. for(i=0; i<2; i++){
  2628. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2629. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2630. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2631. }
  2632. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  2633. &dmin, &next_block, 0, 0);
  2634. }
  2635. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  2636. s->mv_dir = MV_DIR_BACKWARD;
  2637. s->mv_type = MV_TYPE_FIELD;
  2638. s->mb_intra= 0;
  2639. for(i=0; i<2; i++){
  2640. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2641. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2642. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2643. }
  2644. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  2645. &dmin, &next_block, 0, 0);
  2646. }
  2647. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  2648. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2649. s->mv_type = MV_TYPE_FIELD;
  2650. s->mb_intra= 0;
  2651. for(dir=0; dir<2; dir++){
  2652. for(i=0; i<2; i++){
  2653. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2654. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2655. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2656. }
  2657. }
  2658. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  2659. &dmin, &next_block, 0, 0);
  2660. }
  2661. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  2662. s->mv_dir = 0;
  2663. s->mv_type = MV_TYPE_16X16;
  2664. s->mb_intra= 1;
  2665. s->mv[0][0][0] = 0;
  2666. s->mv[0][0][1] = 0;
  2667. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  2668. &dmin, &next_block, 0, 0);
  2669. if(s->h263_pred || s->h263_aic){
  2670. if(best_s.mb_intra)
  2671. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  2672. else
  2673. ff_clean_intra_table_entries(s); //old mode?
  2674. }
  2675. }
  2676. if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) && dmin < INT_MAX) {
  2677. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  2678. const int last_qp= backup_s.qscale;
  2679. int qpi, qp, dc[6];
  2680. int16_t ac[6][16];
  2681. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2682. static const int dquant_tab[4]={-1,1,-2,2};
  2683. assert(backup_s.dquant == 0);
  2684. //FIXME intra
  2685. s->mv_dir= best_s.mv_dir;
  2686. s->mv_type = MV_TYPE_16X16;
  2687. s->mb_intra= best_s.mb_intra;
  2688. s->mv[0][0][0] = best_s.mv[0][0][0];
  2689. s->mv[0][0][1] = best_s.mv[0][0][1];
  2690. s->mv[1][0][0] = best_s.mv[1][0][0];
  2691. s->mv[1][0][1] = best_s.mv[1][0][1];
  2692. qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
  2693. for(; qpi<4; qpi++){
  2694. int dquant= dquant_tab[qpi];
  2695. qp= last_qp + dquant;
  2696. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2697. continue;
  2698. backup_s.dquant= dquant;
  2699. if(s->mb_intra && s->dc_val[0]){
  2700. for(i=0; i<6; i++){
  2701. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2702. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(int16_t)*16);
  2703. }
  2704. }
  2705. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2706. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2707. if(best_s.qscale != qp){
  2708. if(s->mb_intra && s->dc_val[0]){
  2709. for(i=0; i<6; i++){
  2710. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2711. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(int16_t)*16);
  2712. }
  2713. }
  2714. }
  2715. }
  2716. }
  2717. }
  2718. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2719. int mx= s->b_direct_mv_table[xy][0];
  2720. int my= s->b_direct_mv_table[xy][1];
  2721. backup_s.dquant = 0;
  2722. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2723. s->mb_intra= 0;
  2724. ff_mpeg4_set_direct_mv(s, mx, my);
  2725. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2726. &dmin, &next_block, mx, my);
  2727. }
  2728. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2729. backup_s.dquant = 0;
  2730. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2731. s->mb_intra= 0;
  2732. ff_mpeg4_set_direct_mv(s, 0, 0);
  2733. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2734. &dmin, &next_block, 0, 0);
  2735. }
  2736. if (!best_s.mb_intra && s->mpv_flags & FF_MPV_FLAG_SKIP_RD) {
  2737. int coded=0;
  2738. for(i=0; i<6; i++)
  2739. coded |= s->block_last_index[i];
  2740. if(coded){
  2741. int mx,my;
  2742. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2743. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2744. mx=my=0; //FIXME find the one we actually used
  2745. ff_mpeg4_set_direct_mv(s, mx, my);
  2746. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2747. mx= s->mv[1][0][0];
  2748. my= s->mv[1][0][1];
  2749. }else{
  2750. mx= s->mv[0][0][0];
  2751. my= s->mv[0][0][1];
  2752. }
  2753. s->mv_dir= best_s.mv_dir;
  2754. s->mv_type = best_s.mv_type;
  2755. s->mb_intra= 0;
  2756. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2757. s->mv[0][0][1] = best_s.mv[0][0][1];
  2758. s->mv[1][0][0] = best_s.mv[1][0][0];
  2759. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2760. backup_s.dquant= 0;
  2761. s->skipdct=1;
  2762. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2763. &dmin, &next_block, mx, my);
  2764. s->skipdct=0;
  2765. }
  2766. }
  2767. s->current_picture.qscale_table[xy] = best_s.qscale;
  2768. copy_context_after_encode(s, &best_s, -1);
  2769. pb_bits_count= put_bits_count(&s->pb);
  2770. flush_put_bits(&s->pb);
  2771. avpriv_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2772. s->pb= backup_s.pb;
  2773. if(s->data_partitioning){
  2774. pb2_bits_count= put_bits_count(&s->pb2);
  2775. flush_put_bits(&s->pb2);
  2776. avpriv_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2777. s->pb2= backup_s.pb2;
  2778. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2779. flush_put_bits(&s->tex_pb);
  2780. avpriv_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2781. s->tex_pb= backup_s.tex_pb;
  2782. }
  2783. s->last_bits= put_bits_count(&s->pb);
  2784. if (CONFIG_H263_ENCODER &&
  2785. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2786. ff_h263_update_motion_val(s);
  2787. if(next_block==0){ //FIXME 16 vs linesize16
  2788. s->hdsp.put_pixels_tab[0][0](s->dest[0], s->sc.rd_scratchpad , s->linesize ,16);
  2789. s->hdsp.put_pixels_tab[1][0](s->dest[1], s->sc.rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2790. s->hdsp.put_pixels_tab[1][0](s->dest[2], s->sc.rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2791. }
  2792. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2793. ff_mpv_decode_mb(s, s->block);
  2794. } else {
  2795. int motion_x = 0, motion_y = 0;
  2796. s->mv_type=MV_TYPE_16X16;
  2797. // only one MB-Type possible
  2798. switch(mb_type){
  2799. case CANDIDATE_MB_TYPE_INTRA:
  2800. s->mv_dir = 0;
  2801. s->mb_intra= 1;
  2802. motion_x= s->mv[0][0][0] = 0;
  2803. motion_y= s->mv[0][0][1] = 0;
  2804. break;
  2805. case CANDIDATE_MB_TYPE_INTER:
  2806. s->mv_dir = MV_DIR_FORWARD;
  2807. s->mb_intra= 0;
  2808. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2809. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2810. break;
  2811. case CANDIDATE_MB_TYPE_INTER_I:
  2812. s->mv_dir = MV_DIR_FORWARD;
  2813. s->mv_type = MV_TYPE_FIELD;
  2814. s->mb_intra= 0;
  2815. for(i=0; i<2; i++){
  2816. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2817. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2818. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2819. }
  2820. break;
  2821. case CANDIDATE_MB_TYPE_INTER4V:
  2822. s->mv_dir = MV_DIR_FORWARD;
  2823. s->mv_type = MV_TYPE_8X8;
  2824. s->mb_intra= 0;
  2825. for(i=0; i<4; i++){
  2826. s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  2827. s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  2828. }
  2829. break;
  2830. case CANDIDATE_MB_TYPE_DIRECT:
  2831. if (CONFIG_MPEG4_ENCODER) {
  2832. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2833. s->mb_intra= 0;
  2834. motion_x=s->b_direct_mv_table[xy][0];
  2835. motion_y=s->b_direct_mv_table[xy][1];
  2836. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2837. }
  2838. break;
  2839. case CANDIDATE_MB_TYPE_DIRECT0:
  2840. if (CONFIG_MPEG4_ENCODER) {
  2841. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2842. s->mb_intra= 0;
  2843. ff_mpeg4_set_direct_mv(s, 0, 0);
  2844. }
  2845. break;
  2846. case CANDIDATE_MB_TYPE_BIDIR:
  2847. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2848. s->mb_intra= 0;
  2849. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2850. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2851. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2852. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2853. break;
  2854. case CANDIDATE_MB_TYPE_BACKWARD:
  2855. s->mv_dir = MV_DIR_BACKWARD;
  2856. s->mb_intra= 0;
  2857. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2858. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2859. break;
  2860. case CANDIDATE_MB_TYPE_FORWARD:
  2861. s->mv_dir = MV_DIR_FORWARD;
  2862. s->mb_intra= 0;
  2863. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2864. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2865. break;
  2866. case CANDIDATE_MB_TYPE_FORWARD_I:
  2867. s->mv_dir = MV_DIR_FORWARD;
  2868. s->mv_type = MV_TYPE_FIELD;
  2869. s->mb_intra= 0;
  2870. for(i=0; i<2; i++){
  2871. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2872. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2873. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2874. }
  2875. break;
  2876. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2877. s->mv_dir = MV_DIR_BACKWARD;
  2878. s->mv_type = MV_TYPE_FIELD;
  2879. s->mb_intra= 0;
  2880. for(i=0; i<2; i++){
  2881. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2882. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2883. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2884. }
  2885. break;
  2886. case CANDIDATE_MB_TYPE_BIDIR_I:
  2887. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2888. s->mv_type = MV_TYPE_FIELD;
  2889. s->mb_intra= 0;
  2890. for(dir=0; dir<2; dir++){
  2891. for(i=0; i<2; i++){
  2892. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2893. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2894. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2895. }
  2896. }
  2897. break;
  2898. default:
  2899. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2900. }
  2901. encode_mb(s, motion_x, motion_y);
  2902. // RAL: Update last macroblock type
  2903. s->last_mv_dir = s->mv_dir;
  2904. if (CONFIG_H263_ENCODER &&
  2905. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2906. ff_h263_update_motion_val(s);
  2907. ff_mpv_decode_mb(s, s->block);
  2908. }
  2909. /* clean the MV table in IPS frames for direct mode in B-frames */
  2910. if(s->mb_intra /* && I,P,S_TYPE */){
  2911. s->p_mv_table[xy][0]=0;
  2912. s->p_mv_table[xy][1]=0;
  2913. }
  2914. if (s->avctx->flags & AV_CODEC_FLAG_PSNR) {
  2915. int w= 16;
  2916. int h= 16;
  2917. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2918. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2919. s->current_picture.encoding_error[0] += sse(
  2920. s, s->new_picture.f->data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2921. s->dest[0], w, h, s->linesize);
  2922. s->current_picture.encoding_error[1] += sse(
  2923. s, s->new_picture.f->data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2924. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2925. s->current_picture.encoding_error[2] += sse(
  2926. s, s->new_picture.f->data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2927. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2928. }
  2929. if(s->loop_filter){
  2930. if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  2931. ff_h263_loop_filter(s);
  2932. }
  2933. ff_dlog(s->avctx, "MB %d %d bits\n",
  2934. s->mb_x + s->mb_y * s->mb_stride, put_bits_count(&s->pb));
  2935. }
  2936. }
  2937. //not beautiful here but we must write it before flushing so it has to be here
  2938. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
  2939. ff_msmpeg4_encode_ext_header(s);
  2940. write_slice_end(s);
  2941. #if FF_API_RTP_CALLBACK
  2942. FF_DISABLE_DEPRECATION_WARNINGS
  2943. /* Send the last GOB if RTP */
  2944. if (s->avctx->rtp_callback) {
  2945. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2946. int pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2947. /* Call the RTP callback to send the last GOB */
  2948. emms_c();
  2949. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2950. }
  2951. FF_ENABLE_DEPRECATION_WARNINGS
  2952. #endif
  2953. return 0;
  2954. }
  2955. #define MERGE(field) dst->field += src->field; src->field=0
  2956. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2957. MERGE(me.scene_change_score);
  2958. MERGE(me.mc_mb_var_sum_temp);
  2959. MERGE(me.mb_var_sum_temp);
  2960. }
  2961. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2962. int i;
  2963. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2964. MERGE(dct_count[1]);
  2965. MERGE(mv_bits);
  2966. MERGE(i_tex_bits);
  2967. MERGE(p_tex_bits);
  2968. MERGE(i_count);
  2969. MERGE(f_count);
  2970. MERGE(b_count);
  2971. MERGE(skip_count);
  2972. MERGE(misc_bits);
  2973. MERGE(er.error_count);
  2974. MERGE(padding_bug_score);
  2975. MERGE(current_picture.encoding_error[0]);
  2976. MERGE(current_picture.encoding_error[1]);
  2977. MERGE(current_picture.encoding_error[2]);
  2978. if (dst->noise_reduction){
  2979. for(i=0; i<64; i++){
  2980. MERGE(dct_error_sum[0][i]);
  2981. MERGE(dct_error_sum[1][i]);
  2982. }
  2983. }
  2984. assert(put_bits_count(&src->pb) % 8 ==0);
  2985. assert(put_bits_count(&dst->pb) % 8 ==0);
  2986. avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2987. flush_put_bits(&dst->pb);
  2988. }
  2989. static int estimate_qp(MpegEncContext *s, int dry_run){
  2990. if (s->next_lambda){
  2991. s->current_picture_ptr->f->quality =
  2992. s->current_picture.f->quality = s->next_lambda;
  2993. if(!dry_run) s->next_lambda= 0;
  2994. } else if (!s->fixed_qscale) {
  2995. int quality;
  2996. #if CONFIG_LIBXVID
  2997. if ((s->avctx->flags & AV_CODEC_FLAG_PASS2) && s->rc_strategy == 1)
  2998. quality = ff_xvid_rate_estimate_qscale(s, dry_run);
  2999. else
  3000. #endif
  3001. quality = ff_rate_estimate_qscale(s, dry_run);
  3002. s->current_picture_ptr->f->quality =
  3003. s->current_picture.f->quality = quality;
  3004. if (s->current_picture.f->quality < 0)
  3005. return -1;
  3006. }
  3007. if(s->adaptive_quant){
  3008. switch(s->codec_id){
  3009. case AV_CODEC_ID_MPEG4:
  3010. if (CONFIG_MPEG4_ENCODER)
  3011. ff_clean_mpeg4_qscales(s);
  3012. break;
  3013. case AV_CODEC_ID_H263:
  3014. case AV_CODEC_ID_H263P:
  3015. case AV_CODEC_ID_FLV1:
  3016. if (CONFIG_H263_ENCODER)
  3017. ff_clean_h263_qscales(s);
  3018. break;
  3019. default:
  3020. ff_init_qscale_tab(s);
  3021. }
  3022. s->lambda= s->lambda_table[0];
  3023. //FIXME broken
  3024. }else
  3025. s->lambda = s->current_picture.f->quality;
  3026. update_qscale(s);
  3027. return 0;
  3028. }
  3029. /* must be called before writing the header */
  3030. static void set_frame_distances(MpegEncContext * s){
  3031. assert(s->current_picture_ptr->f->pts != AV_NOPTS_VALUE);
  3032. s->time = s->current_picture_ptr->f->pts * s->avctx->time_base.num;
  3033. if(s->pict_type==AV_PICTURE_TYPE_B){
  3034. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  3035. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  3036. }else{
  3037. s->pp_time= s->time - s->last_non_b_time;
  3038. s->last_non_b_time= s->time;
  3039. assert(s->picture_number==0 || s->pp_time > 0);
  3040. }
  3041. }
  3042. static int encode_picture(MpegEncContext *s, int picture_number)
  3043. {
  3044. int i, ret;
  3045. int bits;
  3046. int context_count = s->slice_context_count;
  3047. s->picture_number = picture_number;
  3048. /* Reset the average MB variance */
  3049. s->me.mb_var_sum_temp =
  3050. s->me.mc_mb_var_sum_temp = 0;
  3051. /* we need to initialize some time vars before we can encode B-frames */
  3052. // RAL: Condition added for MPEG1VIDEO
  3053. if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
  3054. set_frame_distances(s);
  3055. if(CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4)
  3056. ff_set_mpeg4_time(s);
  3057. s->me.scene_change_score=0;
  3058. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  3059. if(s->pict_type==AV_PICTURE_TYPE_I){
  3060. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  3061. else s->no_rounding=0;
  3062. }else if(s->pict_type!=AV_PICTURE_TYPE_B){
  3063. if(s->flipflop_rounding || s->codec_id == AV_CODEC_ID_H263P || s->codec_id == AV_CODEC_ID_MPEG4)
  3064. s->no_rounding ^= 1;
  3065. }
  3066. if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  3067. if (estimate_qp(s,1) < 0)
  3068. return -1;
  3069. ff_get_2pass_fcode(s);
  3070. } else if (!(s->avctx->flags & AV_CODEC_FLAG_QSCALE)) {
  3071. if(s->pict_type==AV_PICTURE_TYPE_B)
  3072. s->lambda= s->last_lambda_for[s->pict_type];
  3073. else
  3074. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  3075. update_qscale(s);
  3076. }
  3077. s->mb_intra=0; //for the rate distortion & bit compare functions
  3078. for(i=1; i<context_count; i++){
  3079. ret = ff_update_duplicate_context(s->thread_context[i], s);
  3080. if (ret < 0)
  3081. return ret;
  3082. }
  3083. if(ff_init_me(s)<0)
  3084. return -1;
  3085. /* Estimate motion for every MB */
  3086. if(s->pict_type != AV_PICTURE_TYPE_I){
  3087. s->lambda = (s->lambda * s->me_penalty_compensation + 128) >> 8;
  3088. s->lambda2 = (s->lambda2 * (int64_t) s->me_penalty_compensation + 128) >> 8;
  3089. if (s->pict_type != AV_PICTURE_TYPE_B) {
  3090. if ((s->me_pre && s->last_non_b_pict_type == AV_PICTURE_TYPE_I) ||
  3091. s->me_pre == 2) {
  3092. s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3093. }
  3094. }
  3095. s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3096. }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
  3097. /* I-Frame */
  3098. for(i=0; i<s->mb_stride*s->mb_height; i++)
  3099. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  3100. if(!s->fixed_qscale){
  3101. /* finding spatial complexity for I-frame rate control */
  3102. s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3103. }
  3104. }
  3105. for(i=1; i<context_count; i++){
  3106. merge_context_after_me(s, s->thread_context[i]);
  3107. }
  3108. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  3109. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  3110. emms_c();
  3111. if (s->me.scene_change_score > s->scenechange_threshold &&
  3112. s->pict_type == AV_PICTURE_TYPE_P) {
  3113. s->pict_type= AV_PICTURE_TYPE_I;
  3114. for(i=0; i<s->mb_stride*s->mb_height; i++)
  3115. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  3116. ff_dlog(s, "Scene change detected, encoding as I Frame %d %d\n",
  3117. s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  3118. }
  3119. if(!s->umvplus){
  3120. if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
  3121. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  3122. if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3123. int a,b;
  3124. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  3125. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  3126. s->f_code= FFMAX3(s->f_code, a, b);
  3127. }
  3128. ff_fix_long_p_mvs(s);
  3129. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  3130. if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3131. int j;
  3132. for(i=0; i<2; i++){
  3133. for(j=0; j<2; j++)
  3134. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  3135. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  3136. }
  3137. }
  3138. }
  3139. if(s->pict_type==AV_PICTURE_TYPE_B){
  3140. int a, b;
  3141. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  3142. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  3143. s->f_code = FFMAX(a, b);
  3144. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  3145. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  3146. s->b_code = FFMAX(a, b);
  3147. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  3148. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  3149. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  3150. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  3151. if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3152. int dir, j;
  3153. for(dir=0; dir<2; dir++){
  3154. for(i=0; i<2; i++){
  3155. for(j=0; j<2; j++){
  3156. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  3157. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  3158. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  3159. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  3160. }
  3161. }
  3162. }
  3163. }
  3164. }
  3165. }
  3166. if (estimate_qp(s, 0) < 0)
  3167. return -1;
  3168. if (s->qscale < 3 && s->max_qcoeff <= 128 &&
  3169. s->pict_type == AV_PICTURE_TYPE_I &&
  3170. !(s->avctx->flags & AV_CODEC_FLAG_QSCALE))
  3171. s->qscale= 3; //reduce clipping problems
  3172. if (s->out_format == FMT_MJPEG) {
  3173. /* for mjpeg, we do include qscale in the matrix */
  3174. for(i=1;i<64;i++){
  3175. int j = s->idsp.idct_permutation[i];
  3176. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  3177. }
  3178. s->y_dc_scale_table=
  3179. s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
  3180. s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
  3181. ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
  3182. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  3183. s->qscale= 8;
  3184. }
  3185. //FIXME var duplication
  3186. s->current_picture_ptr->f->key_frame =
  3187. s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
  3188. s->current_picture_ptr->f->pict_type =
  3189. s->current_picture.f->pict_type = s->pict_type;
  3190. if (s->current_picture.f->key_frame)
  3191. s->picture_in_gop_number=0;
  3192. s->last_bits= put_bits_count(&s->pb);
  3193. switch(s->out_format) {
  3194. case FMT_MJPEG:
  3195. if (CONFIG_MJPEG_ENCODER)
  3196. ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,
  3197. s->pred, s->intra_matrix);
  3198. break;
  3199. case FMT_H261:
  3200. if (CONFIG_H261_ENCODER)
  3201. ff_h261_encode_picture_header(s, picture_number);
  3202. break;
  3203. case FMT_H263:
  3204. if (CONFIG_WMV2_ENCODER && s->codec_id == AV_CODEC_ID_WMV2)
  3205. ff_wmv2_encode_picture_header(s, picture_number);
  3206. else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  3207. ff_msmpeg4_encode_picture_header(s, picture_number);
  3208. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  3209. ff_mpeg4_encode_picture_header(s, picture_number);
  3210. else if (CONFIG_RV10_ENCODER && s->codec_id == AV_CODEC_ID_RV10) {
  3211. ret = ff_rv10_encode_picture_header(s, picture_number);
  3212. if (ret < 0)
  3213. return ret;
  3214. }
  3215. else if (CONFIG_RV20_ENCODER && s->codec_id == AV_CODEC_ID_RV20)
  3216. ff_rv20_encode_picture_header(s, picture_number);
  3217. else if (CONFIG_FLV_ENCODER && s->codec_id == AV_CODEC_ID_FLV1)
  3218. ff_flv_encode_picture_header(s, picture_number);
  3219. else if (CONFIG_H263_ENCODER)
  3220. ff_h263_encode_picture_header(s, picture_number);
  3221. break;
  3222. case FMT_MPEG1:
  3223. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  3224. ff_mpeg1_encode_picture_header(s, picture_number);
  3225. break;
  3226. default:
  3227. assert(0);
  3228. }
  3229. bits= put_bits_count(&s->pb);
  3230. s->header_bits= bits - s->last_bits;
  3231. for(i=1; i<context_count; i++){
  3232. update_duplicate_context_after_me(s->thread_context[i], s);
  3233. }
  3234. s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3235. for(i=1; i<context_count; i++){
  3236. merge_context_after_encode(s, s->thread_context[i]);
  3237. }
  3238. emms_c();
  3239. return 0;
  3240. }
  3241. static void denoise_dct_c(MpegEncContext *s, int16_t *block){
  3242. const int intra= s->mb_intra;
  3243. int i;
  3244. s->dct_count[intra]++;
  3245. for(i=0; i<64; i++){
  3246. int level= block[i];
  3247. if(level){
  3248. if(level>0){
  3249. s->dct_error_sum[intra][i] += level;
  3250. level -= s->dct_offset[intra][i];
  3251. if(level<0) level=0;
  3252. }else{
  3253. s->dct_error_sum[intra][i] -= level;
  3254. level += s->dct_offset[intra][i];
  3255. if(level>0) level=0;
  3256. }
  3257. block[i]= level;
  3258. }
  3259. }
  3260. }
  3261. static int dct_quantize_trellis_c(MpegEncContext *s,
  3262. int16_t *block, int n,
  3263. int qscale, int *overflow){
  3264. const int *qmat;
  3265. const uint8_t *scantable= s->intra_scantable.scantable;
  3266. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  3267. int max=0;
  3268. unsigned int threshold1, threshold2;
  3269. int bias=0;
  3270. int run_tab[65];
  3271. int level_tab[65];
  3272. int score_tab[65];
  3273. int survivor[65];
  3274. int survivor_count;
  3275. int last_run=0;
  3276. int last_level=0;
  3277. int last_score= 0;
  3278. int last_i;
  3279. int coeff[2][64];
  3280. int coeff_count[64];
  3281. int qmul, qadd, start_i, last_non_zero, i, dc;
  3282. const int esc_length= s->ac_esc_length;
  3283. uint8_t * length;
  3284. uint8_t * last_length;
  3285. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  3286. s->fdsp.fdct(block);
  3287. if(s->dct_error_sum)
  3288. s->denoise_dct(s, block);
  3289. qmul= qscale*16;
  3290. qadd= ((qscale-1)|1)*8;
  3291. if (s->mb_intra) {
  3292. int q;
  3293. if (!s->h263_aic) {
  3294. if (n < 4)
  3295. q = s->y_dc_scale;
  3296. else
  3297. q = s->c_dc_scale;
  3298. q = q << 3;
  3299. } else{
  3300. /* For AIC we skip quant/dequant of INTRADC */
  3301. q = 1 << 3;
  3302. qadd=0;
  3303. }
  3304. /* note: block[0] is assumed to be positive */
  3305. block[0] = (block[0] + (q >> 1)) / q;
  3306. start_i = 1;
  3307. last_non_zero = 0;
  3308. qmat = s->q_intra_matrix[qscale];
  3309. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  3310. bias= 1<<(QMAT_SHIFT-1);
  3311. length = s->intra_ac_vlc_length;
  3312. last_length= s->intra_ac_vlc_last_length;
  3313. } else {
  3314. start_i = 0;
  3315. last_non_zero = -1;
  3316. qmat = s->q_inter_matrix[qscale];
  3317. length = s->inter_ac_vlc_length;
  3318. last_length= s->inter_ac_vlc_last_length;
  3319. }
  3320. last_i= start_i;
  3321. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3322. threshold2= (threshold1<<1);
  3323. for(i=63; i>=start_i; i--) {
  3324. const int j = scantable[i];
  3325. int level = block[j] * qmat[j];
  3326. if(((unsigned)(level+threshold1))>threshold2){
  3327. last_non_zero = i;
  3328. break;
  3329. }
  3330. }
  3331. for(i=start_i; i<=last_non_zero; i++) {
  3332. const int j = scantable[i];
  3333. int level = block[j] * qmat[j];
  3334. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  3335. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  3336. if(((unsigned)(level+threshold1))>threshold2){
  3337. if(level>0){
  3338. level= (bias + level)>>QMAT_SHIFT;
  3339. coeff[0][i]= level;
  3340. coeff[1][i]= level-1;
  3341. // coeff[2][k]= level-2;
  3342. }else{
  3343. level= (bias - level)>>QMAT_SHIFT;
  3344. coeff[0][i]= -level;
  3345. coeff[1][i]= -level+1;
  3346. // coeff[2][k]= -level+2;
  3347. }
  3348. coeff_count[i]= FFMIN(level, 2);
  3349. assert(coeff_count[i]);
  3350. max |=level;
  3351. }else{
  3352. coeff[0][i]= (level>>31)|1;
  3353. coeff_count[i]= 1;
  3354. }
  3355. }
  3356. *overflow= s->max_qcoeff < max; //overflow might have happened
  3357. if(last_non_zero < start_i){
  3358. memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
  3359. return last_non_zero;
  3360. }
  3361. score_tab[start_i]= 0;
  3362. survivor[0]= start_i;
  3363. survivor_count= 1;
  3364. for(i=start_i; i<=last_non_zero; i++){
  3365. int level_index, j, zero_distortion;
  3366. int dct_coeff= FFABS(block[ scantable[i] ]);
  3367. int best_score=256*256*256*120;
  3368. if (s->fdsp.fdct == ff_fdct_ifast)
  3369. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  3370. zero_distortion= dct_coeff*dct_coeff;
  3371. for(level_index=0; level_index < coeff_count[i]; level_index++){
  3372. int distortion;
  3373. int level= coeff[level_index][i];
  3374. const int alevel= FFABS(level);
  3375. int unquant_coeff;
  3376. assert(level);
  3377. if(s->out_format == FMT_H263){
  3378. unquant_coeff= alevel*qmul + qadd;
  3379. } else { // MPEG-1
  3380. j = s->idsp.idct_permutation[scantable[i]]; // FIXME: optimize
  3381. if(s->mb_intra){
  3382. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  3383. unquant_coeff = (unquant_coeff - 1) | 1;
  3384. }else{
  3385. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  3386. unquant_coeff = (unquant_coeff - 1) | 1;
  3387. }
  3388. unquant_coeff<<= 3;
  3389. }
  3390. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  3391. level+=64;
  3392. if((level&(~127)) == 0){
  3393. for(j=survivor_count-1; j>=0; j--){
  3394. int run= i - survivor[j];
  3395. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3396. score += score_tab[i-run];
  3397. if(score < best_score){
  3398. best_score= score;
  3399. run_tab[i+1]= run;
  3400. level_tab[i+1]= level-64;
  3401. }
  3402. }
  3403. if(s->out_format == FMT_H263){
  3404. for(j=survivor_count-1; j>=0; j--){
  3405. int run= i - survivor[j];
  3406. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3407. score += score_tab[i-run];
  3408. if(score < last_score){
  3409. last_score= score;
  3410. last_run= run;
  3411. last_level= level-64;
  3412. last_i= i+1;
  3413. }
  3414. }
  3415. }
  3416. }else{
  3417. distortion += esc_length*lambda;
  3418. for(j=survivor_count-1; j>=0; j--){
  3419. int run= i - survivor[j];
  3420. int score= distortion + score_tab[i-run];
  3421. if(score < best_score){
  3422. best_score= score;
  3423. run_tab[i+1]= run;
  3424. level_tab[i+1]= level-64;
  3425. }
  3426. }
  3427. if(s->out_format == FMT_H263){
  3428. for(j=survivor_count-1; j>=0; j--){
  3429. int run= i - survivor[j];
  3430. int score= distortion + score_tab[i-run];
  3431. if(score < last_score){
  3432. last_score= score;
  3433. last_run= run;
  3434. last_level= level-64;
  3435. last_i= i+1;
  3436. }
  3437. }
  3438. }
  3439. }
  3440. }
  3441. score_tab[i+1]= best_score;
  3442. // 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
  3443. if(last_non_zero <= 27){
  3444. for(; survivor_count; survivor_count--){
  3445. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  3446. break;
  3447. }
  3448. }else{
  3449. for(; survivor_count; survivor_count--){
  3450. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  3451. break;
  3452. }
  3453. }
  3454. survivor[ survivor_count++ ]= i+1;
  3455. }
  3456. if(s->out_format != FMT_H263){
  3457. last_score= 256*256*256*120;
  3458. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  3459. int score= score_tab[i];
  3460. if (i)
  3461. score += lambda * 2; // FIXME more exact?
  3462. if(score < last_score){
  3463. last_score= score;
  3464. last_i= i;
  3465. last_level= level_tab[i];
  3466. last_run= run_tab[i];
  3467. }
  3468. }
  3469. }
  3470. s->coded_score[n] = last_score;
  3471. dc= FFABS(block[0]);
  3472. last_non_zero= last_i - 1;
  3473. memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
  3474. if(last_non_zero < start_i)
  3475. return last_non_zero;
  3476. if(last_non_zero == 0 && start_i == 0){
  3477. int best_level= 0;
  3478. int best_score= dc * dc;
  3479. for(i=0; i<coeff_count[0]; i++){
  3480. int level= coeff[i][0];
  3481. int alevel= FFABS(level);
  3482. int unquant_coeff, score, distortion;
  3483. if(s->out_format == FMT_H263){
  3484. unquant_coeff= (alevel*qmul + qadd)>>3;
  3485. } else { // MPEG-1
  3486. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  3487. unquant_coeff = (unquant_coeff - 1) | 1;
  3488. }
  3489. unquant_coeff = (unquant_coeff + 4) >> 3;
  3490. unquant_coeff<<= 3 + 3;
  3491. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  3492. level+=64;
  3493. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  3494. else score= distortion + esc_length*lambda;
  3495. if(score < best_score){
  3496. best_score= score;
  3497. best_level= level - 64;
  3498. }
  3499. }
  3500. block[0]= best_level;
  3501. s->coded_score[n] = best_score - dc*dc;
  3502. if(best_level == 0) return -1;
  3503. else return last_non_zero;
  3504. }
  3505. i= last_i;
  3506. assert(last_level);
  3507. block[ perm_scantable[last_non_zero] ]= last_level;
  3508. i -= last_run + 1;
  3509. for(; i>start_i; i -= run_tab[i] + 1){
  3510. block[ perm_scantable[i-1] ]= level_tab[i];
  3511. }
  3512. return last_non_zero;
  3513. }
  3514. //#define REFINE_STATS 1
  3515. static int16_t basis[64][64];
  3516. static void build_basis(uint8_t *perm){
  3517. int i, j, x, y;
  3518. emms_c();
  3519. for(i=0; i<8; i++){
  3520. for(j=0; j<8; j++){
  3521. for(y=0; y<8; y++){
  3522. for(x=0; x<8; x++){
  3523. double s= 0.25*(1<<BASIS_SHIFT);
  3524. int index= 8*i + j;
  3525. int perm_index= perm[index];
  3526. if(i==0) s*= sqrt(0.5);
  3527. if(j==0) s*= sqrt(0.5);
  3528. 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)));
  3529. }
  3530. }
  3531. }
  3532. }
  3533. }
  3534. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  3535. int16_t *block, int16_t *weight, int16_t *orig,
  3536. int n, int qscale){
  3537. int16_t rem[64];
  3538. LOCAL_ALIGNED_16(int16_t, d1, [64]);
  3539. const uint8_t *scantable= s->intra_scantable.scantable;
  3540. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  3541. // unsigned int threshold1, threshold2;
  3542. // int bias=0;
  3543. int run_tab[65];
  3544. int prev_run=0;
  3545. int prev_level=0;
  3546. int qmul, qadd, start_i, last_non_zero, i, dc;
  3547. uint8_t * length;
  3548. uint8_t * last_length;
  3549. int lambda;
  3550. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  3551. #ifdef REFINE_STATS
  3552. static int count=0;
  3553. static int after_last=0;
  3554. static int to_zero=0;
  3555. static int from_zero=0;
  3556. static int raise=0;
  3557. static int lower=0;
  3558. static int messed_sign=0;
  3559. #endif
  3560. if(basis[0][0] == 0)
  3561. build_basis(s->idsp.idct_permutation);
  3562. qmul= qscale*2;
  3563. qadd= (qscale-1)|1;
  3564. if (s->mb_intra) {
  3565. if (!s->h263_aic) {
  3566. if (n < 4)
  3567. q = s->y_dc_scale;
  3568. else
  3569. q = s->c_dc_scale;
  3570. } else{
  3571. /* For AIC we skip quant/dequant of INTRADC */
  3572. q = 1;
  3573. qadd=0;
  3574. }
  3575. q <<= RECON_SHIFT-3;
  3576. /* note: block[0] is assumed to be positive */
  3577. dc= block[0]*q;
  3578. // block[0] = (block[0] + (q >> 1)) / q;
  3579. start_i = 1;
  3580. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  3581. // bias= 1<<(QMAT_SHIFT-1);
  3582. length = s->intra_ac_vlc_length;
  3583. last_length= s->intra_ac_vlc_last_length;
  3584. } else {
  3585. dc= 0;
  3586. start_i = 0;
  3587. length = s->inter_ac_vlc_length;
  3588. last_length= s->inter_ac_vlc_last_length;
  3589. }
  3590. last_non_zero = s->block_last_index[n];
  3591. #ifdef REFINE_STATS
  3592. {START_TIMER
  3593. #endif
  3594. dc += (1<<(RECON_SHIFT-1));
  3595. for(i=0; i<64; i++){
  3596. rem[i] = dc - (orig[i] << RECON_SHIFT); // FIXME use orig directly instead of copying to rem[]
  3597. }
  3598. #ifdef REFINE_STATS
  3599. STOP_TIMER("memset rem[]")}
  3600. #endif
  3601. sum=0;
  3602. for(i=0; i<64; i++){
  3603. int one= 36;
  3604. int qns=4;
  3605. int w;
  3606. w= FFABS(weight[i]) + qns*one;
  3607. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  3608. weight[i] = w;
  3609. // w=weight[i] = (63*qns + (w/2)) / w;
  3610. assert(w>0);
  3611. assert(w<(1<<6));
  3612. sum += w*w;
  3613. }
  3614. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  3615. #ifdef REFINE_STATS
  3616. {START_TIMER
  3617. #endif
  3618. run=0;
  3619. rle_index=0;
  3620. for(i=start_i; i<=last_non_zero; i++){
  3621. int j= perm_scantable[i];
  3622. const int level= block[j];
  3623. int coeff;
  3624. if(level){
  3625. if(level<0) coeff= qmul*level - qadd;
  3626. else coeff= qmul*level + qadd;
  3627. run_tab[rle_index++]=run;
  3628. run=0;
  3629. s->mpvencdsp.add_8x8basis(rem, basis[j], coeff);
  3630. }else{
  3631. run++;
  3632. }
  3633. }
  3634. #ifdef REFINE_STATS
  3635. if(last_non_zero>0){
  3636. STOP_TIMER("init rem[]")
  3637. }
  3638. }
  3639. {START_TIMER
  3640. #endif
  3641. for(;;){
  3642. int best_score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0], 0);
  3643. int best_coeff=0;
  3644. int best_change=0;
  3645. int run2, best_unquant_change=0, analyze_gradient;
  3646. #ifdef REFINE_STATS
  3647. {START_TIMER
  3648. #endif
  3649. analyze_gradient = last_non_zero > 2 || s->quantizer_noise_shaping >= 3;
  3650. if(analyze_gradient){
  3651. #ifdef REFINE_STATS
  3652. {START_TIMER
  3653. #endif
  3654. for(i=0; i<64; i++){
  3655. int w= weight[i];
  3656. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  3657. }
  3658. #ifdef REFINE_STATS
  3659. STOP_TIMER("rem*w*w")}
  3660. {START_TIMER
  3661. #endif
  3662. s->fdsp.fdct(d1);
  3663. #ifdef REFINE_STATS
  3664. STOP_TIMER("dct")}
  3665. #endif
  3666. }
  3667. if(start_i){
  3668. const int level= block[0];
  3669. int change, old_coeff;
  3670. assert(s->mb_intra);
  3671. old_coeff= q*level;
  3672. for(change=-1; change<=1; change+=2){
  3673. int new_level= level + change;
  3674. int score, new_coeff;
  3675. new_coeff= q*new_level;
  3676. if(new_coeff >= 2048 || new_coeff < 0)
  3677. continue;
  3678. score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0],
  3679. new_coeff - old_coeff);
  3680. if(score<best_score){
  3681. best_score= score;
  3682. best_coeff= 0;
  3683. best_change= change;
  3684. best_unquant_change= new_coeff - old_coeff;
  3685. }
  3686. }
  3687. }
  3688. run=0;
  3689. rle_index=0;
  3690. run2= run_tab[rle_index++];
  3691. prev_level=0;
  3692. prev_run=0;
  3693. for(i=start_i; i<64; i++){
  3694. int j= perm_scantable[i];
  3695. const int level= block[j];
  3696. int change, old_coeff;
  3697. if(s->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  3698. break;
  3699. if(level){
  3700. if(level<0) old_coeff= qmul*level - qadd;
  3701. else old_coeff= qmul*level + qadd;
  3702. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3703. }else{
  3704. old_coeff=0;
  3705. run2--;
  3706. assert(run2>=0 || i >= last_non_zero );
  3707. }
  3708. for(change=-1; change<=1; change+=2){
  3709. int new_level= level + change;
  3710. int score, new_coeff, unquant_change;
  3711. score=0;
  3712. if(s->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3713. continue;
  3714. if(new_level){
  3715. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3716. else new_coeff= qmul*new_level + qadd;
  3717. if(new_coeff >= 2048 || new_coeff <= -2048)
  3718. continue;
  3719. //FIXME check for overflow
  3720. if(level){
  3721. if(level < 63 && level > -63){
  3722. if(i < last_non_zero)
  3723. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3724. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3725. else
  3726. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3727. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3728. }
  3729. }else{
  3730. assert(FFABS(new_level)==1);
  3731. if(analyze_gradient){
  3732. int g= d1[ scantable[i] ];
  3733. if(g && (g^new_level) >= 0)
  3734. continue;
  3735. }
  3736. if(i < last_non_zero){
  3737. int next_i= i + run2 + 1;
  3738. int next_level= block[ perm_scantable[next_i] ] + 64;
  3739. if(next_level&(~127))
  3740. next_level= 0;
  3741. if(next_i < last_non_zero)
  3742. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3743. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3744. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3745. else
  3746. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3747. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3748. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3749. }else{
  3750. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3751. if(prev_level){
  3752. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3753. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3754. }
  3755. }
  3756. }
  3757. }else{
  3758. new_coeff=0;
  3759. assert(FFABS(level)==1);
  3760. if(i < last_non_zero){
  3761. int next_i= i + run2 + 1;
  3762. int next_level= block[ perm_scantable[next_i] ] + 64;
  3763. if(next_level&(~127))
  3764. next_level= 0;
  3765. if(next_i < last_non_zero)
  3766. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3767. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3768. - length[UNI_AC_ENC_INDEX(run, 65)];
  3769. else
  3770. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3771. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3772. - length[UNI_AC_ENC_INDEX(run, 65)];
  3773. }else{
  3774. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3775. if(prev_level){
  3776. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3777. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3778. }
  3779. }
  3780. }
  3781. score *= lambda;
  3782. unquant_change= new_coeff - old_coeff;
  3783. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3784. score += s->mpvencdsp.try_8x8basis(rem, weight, basis[j],
  3785. unquant_change);
  3786. if(score<best_score){
  3787. best_score= score;
  3788. best_coeff= i;
  3789. best_change= change;
  3790. best_unquant_change= unquant_change;
  3791. }
  3792. }
  3793. if(level){
  3794. prev_level= level + 64;
  3795. if(prev_level&(~127))
  3796. prev_level= 0;
  3797. prev_run= run;
  3798. run=0;
  3799. }else{
  3800. run++;
  3801. }
  3802. }
  3803. #ifdef REFINE_STATS
  3804. STOP_TIMER("iterative step")}
  3805. #endif
  3806. if(best_change){
  3807. int j= perm_scantable[ best_coeff ];
  3808. block[j] += best_change;
  3809. if(best_coeff > last_non_zero){
  3810. last_non_zero= best_coeff;
  3811. assert(block[j]);
  3812. #ifdef REFINE_STATS
  3813. after_last++;
  3814. #endif
  3815. }else{
  3816. #ifdef REFINE_STATS
  3817. if(block[j]){
  3818. if(block[j] - best_change){
  3819. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3820. raise++;
  3821. }else{
  3822. lower++;
  3823. }
  3824. }else{
  3825. from_zero++;
  3826. }
  3827. }else{
  3828. to_zero++;
  3829. }
  3830. #endif
  3831. for(; last_non_zero>=start_i; last_non_zero--){
  3832. if(block[perm_scantable[last_non_zero]])
  3833. break;
  3834. }
  3835. }
  3836. #ifdef REFINE_STATS
  3837. count++;
  3838. if(256*256*256*64 % count == 0){
  3839. 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);
  3840. }
  3841. #endif
  3842. run=0;
  3843. rle_index=0;
  3844. for(i=start_i; i<=last_non_zero; i++){
  3845. int j= perm_scantable[i];
  3846. const int level= block[j];
  3847. if(level){
  3848. run_tab[rle_index++]=run;
  3849. run=0;
  3850. }else{
  3851. run++;
  3852. }
  3853. }
  3854. s->mpvencdsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3855. }else{
  3856. break;
  3857. }
  3858. }
  3859. #ifdef REFINE_STATS
  3860. if(last_non_zero>0){
  3861. STOP_TIMER("iterative search")
  3862. }
  3863. }
  3864. #endif
  3865. return last_non_zero;
  3866. }
  3867. /**
  3868. * Permute an 8x8 block according to permutation.
  3869. * @param block the block which will be permuted according to
  3870. * the given permutation vector
  3871. * @param permutation the permutation vector
  3872. * @param last the last non zero coefficient in scantable order, used to
  3873. * speed the permutation up
  3874. * @param scantable the used scantable, this is only used to speed the
  3875. * permutation up, the block is not (inverse) permutated
  3876. * to scantable order!
  3877. */
  3878. static void block_permute(int16_t *block, uint8_t *permutation,
  3879. const uint8_t *scantable, int last)
  3880. {
  3881. int i;
  3882. int16_t temp[64];
  3883. if (last <= 0)
  3884. return;
  3885. //FIXME it is ok but not clean and might fail for some permutations
  3886. // if (permutation[1] == 1)
  3887. // return;
  3888. for (i = 0; i <= last; i++) {
  3889. const int j = scantable[i];
  3890. temp[j] = block[j];
  3891. block[j] = 0;
  3892. }
  3893. for (i = 0; i <= last; i++) {
  3894. const int j = scantable[i];
  3895. const int perm_j = permutation[j];
  3896. block[perm_j] = temp[j];
  3897. }
  3898. }
  3899. int ff_dct_quantize_c(MpegEncContext *s,
  3900. int16_t *block, int n,
  3901. int qscale, int *overflow)
  3902. {
  3903. int i, j, level, last_non_zero, q, start_i;
  3904. const int *qmat;
  3905. const uint8_t *scantable= s->intra_scantable.scantable;
  3906. int bias;
  3907. int max=0;
  3908. unsigned int threshold1, threshold2;
  3909. s->fdsp.fdct(block);
  3910. if(s->dct_error_sum)
  3911. s->denoise_dct(s, block);
  3912. if (s->mb_intra) {
  3913. if (!s->h263_aic) {
  3914. if (n < 4)
  3915. q = s->y_dc_scale;
  3916. else
  3917. q = s->c_dc_scale;
  3918. q = q << 3;
  3919. } else
  3920. /* For AIC we skip quant/dequant of INTRADC */
  3921. q = 1 << 3;
  3922. /* note: block[0] is assumed to be positive */
  3923. block[0] = (block[0] + (q >> 1)) / q;
  3924. start_i = 1;
  3925. last_non_zero = 0;
  3926. qmat = s->q_intra_matrix[qscale];
  3927. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3928. } else {
  3929. start_i = 0;
  3930. last_non_zero = -1;
  3931. qmat = s->q_inter_matrix[qscale];
  3932. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3933. }
  3934. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3935. threshold2= (threshold1<<1);
  3936. for(i=63;i>=start_i;i--) {
  3937. j = scantable[i];
  3938. level = block[j] * qmat[j];
  3939. if(((unsigned)(level+threshold1))>threshold2){
  3940. last_non_zero = i;
  3941. break;
  3942. }else{
  3943. block[j]=0;
  3944. }
  3945. }
  3946. for(i=start_i; i<=last_non_zero; i++) {
  3947. j = scantable[i];
  3948. level = block[j] * qmat[j];
  3949. // if( bias+level >= (1<<QMAT_SHIFT)
  3950. // || bias-level >= (1<<QMAT_SHIFT)){
  3951. if(((unsigned)(level+threshold1))>threshold2){
  3952. if(level>0){
  3953. level= (bias + level)>>QMAT_SHIFT;
  3954. block[j]= level;
  3955. }else{
  3956. level= (bias - level)>>QMAT_SHIFT;
  3957. block[j]= -level;
  3958. }
  3959. max |=level;
  3960. }else{
  3961. block[j]=0;
  3962. }
  3963. }
  3964. *overflow= s->max_qcoeff < max; //overflow might have happened
  3965. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3966. if (s->idsp.perm_type != FF_IDCT_PERM_NONE)
  3967. block_permute(block, s->idsp.idct_permutation,
  3968. scantable, last_non_zero);
  3969. return last_non_zero;
  3970. }
  3971. #define OFFSET(x) offsetof(MpegEncContext, x)
  3972. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  3973. static const AVOption h263_options[] = {
  3974. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  3975. { "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},
  3976. { "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 },
  3977. FF_MPV_COMMON_OPTS
  3978. { NULL },
  3979. };
  3980. static const AVClass h263_class = {
  3981. .class_name = "H.263 encoder",
  3982. .item_name = av_default_item_name,
  3983. .option = h263_options,
  3984. .version = LIBAVUTIL_VERSION_INT,
  3985. };
  3986. AVCodec ff_h263_encoder = {
  3987. .name = "h263",
  3988. .long_name = NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3989. .type = AVMEDIA_TYPE_VIDEO,
  3990. .id = AV_CODEC_ID_H263,
  3991. .priv_data_size = sizeof(MpegEncContext),
  3992. .init = ff_mpv_encode_init,
  3993. .encode2 = ff_mpv_encode_picture,
  3994. .close = ff_mpv_encode_end,
  3995. .pix_fmts= (const enum AVPixelFormat[]){AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE},
  3996. .priv_class = &h263_class,
  3997. };
  3998. static const AVOption h263p_options[] = {
  3999. { "umv", "Use unlimited motion vectors.", OFFSET(umvplus), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4000. { "aiv", "Use alternative inter VLC.", OFFSET(alt_inter_vlc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4001. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4002. { "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},
  4003. FF_MPV_COMMON_OPTS
  4004. { NULL },
  4005. };
  4006. static const AVClass h263p_class = {
  4007. .class_name = "H.263p encoder",
  4008. .item_name = av_default_item_name,
  4009. .option = h263p_options,
  4010. .version = LIBAVUTIL_VERSION_INT,
  4011. };
  4012. AVCodec ff_h263p_encoder = {
  4013. .name = "h263p",
  4014. .long_name = NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  4015. .type = AVMEDIA_TYPE_VIDEO,
  4016. .id = AV_CODEC_ID_H263P,
  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. .capabilities = AV_CODEC_CAP_SLICE_THREADS,
  4022. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4023. .priv_class = &h263p_class,
  4024. };
  4025. static const AVClass msmpeg4v2_class = {
  4026. .class_name = "msmpeg4v2 encoder",
  4027. .item_name = av_default_item_name,
  4028. .option = ff_mpv_generic_options,
  4029. .version = LIBAVUTIL_VERSION_INT,
  4030. };
  4031. AVCodec ff_msmpeg4v2_encoder = {
  4032. .name = "msmpeg4v2",
  4033. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  4034. .type = AVMEDIA_TYPE_VIDEO,
  4035. .id = AV_CODEC_ID_MSMPEG4V2,
  4036. .priv_data_size = sizeof(MpegEncContext),
  4037. .init = ff_mpv_encode_init,
  4038. .encode2 = ff_mpv_encode_picture,
  4039. .close = ff_mpv_encode_end,
  4040. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4041. .priv_class = &msmpeg4v2_class,
  4042. };
  4043. static const AVClass msmpeg4v3_class = {
  4044. .class_name = "msmpeg4v3 encoder",
  4045. .item_name = av_default_item_name,
  4046. .option = ff_mpv_generic_options,
  4047. .version = LIBAVUTIL_VERSION_INT,
  4048. };
  4049. AVCodec ff_msmpeg4v3_encoder = {
  4050. .name = "msmpeg4",
  4051. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  4052. .type = AVMEDIA_TYPE_VIDEO,
  4053. .id = AV_CODEC_ID_MSMPEG4V3,
  4054. .priv_data_size = sizeof(MpegEncContext),
  4055. .init = ff_mpv_encode_init,
  4056. .encode2 = ff_mpv_encode_picture,
  4057. .close = ff_mpv_encode_end,
  4058. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4059. .priv_class = &msmpeg4v3_class,
  4060. };
  4061. static const AVClass wmv1_class = {
  4062. .class_name = "wmv1 encoder",
  4063. .item_name = av_default_item_name,
  4064. .option = ff_mpv_generic_options,
  4065. .version = LIBAVUTIL_VERSION_INT,
  4066. };
  4067. AVCodec ff_wmv1_encoder = {
  4068. .name = "wmv1",
  4069. .long_name = NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  4070. .type = AVMEDIA_TYPE_VIDEO,
  4071. .id = AV_CODEC_ID_WMV1,
  4072. .priv_data_size = sizeof(MpegEncContext),
  4073. .init = ff_mpv_encode_init,
  4074. .encode2 = ff_mpv_encode_picture,
  4075. .close = ff_mpv_encode_end,
  4076. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4077. .priv_class = &wmv1_class,
  4078. };