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.

4966 lines
180KB

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