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.

4610 lines
165KB

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