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.

4639 lines
165KB

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