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.

4667 lines
171KB

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