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.

4593 lines
167KB

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