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.

4733 lines
173KB

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