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.

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