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.

4739 lines
173KB

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