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.

4344 lines
156KB

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