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.

4529 lines
162KB

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