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.

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