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.

5009 lines
181KB

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