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.

4768 lines
174KB

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