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.

4343 lines
156KB

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