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.

4994 lines
181KB

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