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.

4324 lines
155KB

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