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.

4907 lines
179KB

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