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.

4620 lines
169KB

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