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.

4202 lines
152KB

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