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.

4585 lines
164KB

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