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.

4712 lines
172KB

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