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.

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