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.

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