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.

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