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.

4336 lines
156KB

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