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.

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