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.

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