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.

4584 lines
167KB

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