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.

4669 lines
171KB

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