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.

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