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.

4570 lines
163KB

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