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.

4729 lines
173KB

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