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.

4328 lines
155KB

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