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.

4203 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;
  1262. int context_count = s->slice_context_count;
  1263. for (i = 0; i < context_count; i++) {
  1264. int start_y = s->thread_context[i]->start_mb_y;
  1265. int end_y = s->thread_context[i]-> end_mb_y;
  1266. int h = s->mb_height;
  1267. uint8_t *start = buf + (size_t)(((int64_t) buf_size) * start_y / h);
  1268. uint8_t *end = buf + (size_t)(((int64_t) buf_size) * end_y / h);
  1269. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1270. }
  1271. s->picture_in_gop_number++;
  1272. if (load_input_picture(s, pic_arg) < 0)
  1273. return -1;
  1274. if (select_input_picture(s) < 0) {
  1275. return -1;
  1276. }
  1277. /* output? */
  1278. if (s->new_picture.f.data[0]) {
  1279. s->pict_type = s->new_picture.f.pict_type;
  1280. //emms_c();
  1281. //printf("qs:%f %f %d\n", s->new_picture.quality,
  1282. // s->current_picture.quality, s->qscale);
  1283. MPV_frame_start(s, avctx);
  1284. vbv_retry:
  1285. if (encode_picture(s, s->picture_number) < 0)
  1286. return -1;
  1287. avctx->header_bits = s->header_bits;
  1288. avctx->mv_bits = s->mv_bits;
  1289. avctx->misc_bits = s->misc_bits;
  1290. avctx->i_tex_bits = s->i_tex_bits;
  1291. avctx->p_tex_bits = s->p_tex_bits;
  1292. avctx->i_count = s->i_count;
  1293. // FIXME f/b_count in avctx
  1294. avctx->p_count = s->mb_num - s->i_count - s->skip_count;
  1295. avctx->skip_count = s->skip_count;
  1296. MPV_frame_end(s);
  1297. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1298. ff_mjpeg_encode_picture_trailer(s);
  1299. if (avctx->rc_buffer_size) {
  1300. RateControlContext *rcc = &s->rc_context;
  1301. int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1302. if (put_bits_count(&s->pb) > max_size &&
  1303. s->lambda < s->avctx->lmax) {
  1304. s->next_lambda = FFMAX(s->lambda + 1, s->lambda *
  1305. (s->qscale + 1) / s->qscale);
  1306. if (s->adaptive_quant) {
  1307. int i;
  1308. for (i = 0; i < s->mb_height * s->mb_stride; i++)
  1309. s->lambda_table[i] =
  1310. FFMAX(s->lambda_table[i] + 1,
  1311. s->lambda_table[i] * (s->qscale + 1) /
  1312. s->qscale);
  1313. }
  1314. s->mb_skipped = 0; // done in MPV_frame_start()
  1315. // done in encode_picture() so we must undo it
  1316. if (s->pict_type == AV_PICTURE_TYPE_P) {
  1317. if (s->flipflop_rounding ||
  1318. s->codec_id == CODEC_ID_H263P ||
  1319. s->codec_id == CODEC_ID_MPEG4)
  1320. s->no_rounding ^= 1;
  1321. }
  1322. if (s->pict_type != AV_PICTURE_TYPE_B) {
  1323. s->time_base = s->last_time_base;
  1324. s->last_non_b_time = s->time - s->pp_time;
  1325. }
  1326. //av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
  1327. for (i = 0; i < context_count; i++) {
  1328. PutBitContext *pb = &s->thread_context[i]->pb;
  1329. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1330. }
  1331. goto vbv_retry;
  1332. }
  1333. assert(s->avctx->rc_max_rate);
  1334. }
  1335. if (s->flags & CODEC_FLAG_PASS1)
  1336. ff_write_pass1_stats(s);
  1337. for (i = 0; i < 4; i++) {
  1338. s->current_picture_ptr->f.error[i] = s->current_picture.f.error[i];
  1339. avctx->error[i] += s->current_picture_ptr->f.error[i];
  1340. }
  1341. if (s->flags & CODEC_FLAG_PASS1)
  1342. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits +
  1343. avctx->i_tex_bits + avctx->p_tex_bits ==
  1344. put_bits_count(&s->pb));
  1345. flush_put_bits(&s->pb);
  1346. s->frame_bits = put_bits_count(&s->pb);
  1347. stuffing_count = ff_vbv_update(s, s->frame_bits);
  1348. if (stuffing_count) {
  1349. if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
  1350. stuffing_count + 50) {
  1351. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1352. return -1;
  1353. }
  1354. switch (s->codec_id) {
  1355. case CODEC_ID_MPEG1VIDEO:
  1356. case CODEC_ID_MPEG2VIDEO:
  1357. while (stuffing_count--) {
  1358. put_bits(&s->pb, 8, 0);
  1359. }
  1360. break;
  1361. case CODEC_ID_MPEG4:
  1362. put_bits(&s->pb, 16, 0);
  1363. put_bits(&s->pb, 16, 0x1C3);
  1364. stuffing_count -= 4;
  1365. while (stuffing_count--) {
  1366. put_bits(&s->pb, 8, 0xFF);
  1367. }
  1368. break;
  1369. default:
  1370. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1371. }
  1372. flush_put_bits(&s->pb);
  1373. s->frame_bits = put_bits_count(&s->pb);
  1374. }
  1375. /* update mpeg1/2 vbv_delay for CBR */
  1376. if (s->avctx->rc_max_rate &&
  1377. s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  1378. s->out_format == FMT_MPEG1 &&
  1379. 90000LL * (avctx->rc_buffer_size - 1) <=
  1380. s->avctx->rc_max_rate * 0xFFFFLL) {
  1381. int vbv_delay, min_delay;
  1382. double inbits = s->avctx->rc_max_rate *
  1383. av_q2d(s->avctx->time_base);
  1384. int minbits = s->frame_bits - 8 *
  1385. (s->vbv_delay_ptr - s->pb.buf - 1);
  1386. double bits = s->rc_context.buffer_index + minbits - inbits;
  1387. if (bits < 0)
  1388. av_log(s->avctx, AV_LOG_ERROR,
  1389. "Internal error, negative bits\n");
  1390. assert(s->repeat_first_field == 0);
  1391. vbv_delay = bits * 90000 / s->avctx->rc_max_rate;
  1392. min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /
  1393. s->avctx->rc_max_rate;
  1394. vbv_delay = FFMAX(vbv_delay, min_delay);
  1395. assert(vbv_delay < 0xFFFF);
  1396. s->vbv_delay_ptr[0] &= 0xF8;
  1397. s->vbv_delay_ptr[0] |= vbv_delay >> 13;
  1398. s->vbv_delay_ptr[1] = vbv_delay >> 5;
  1399. s->vbv_delay_ptr[2] &= 0x07;
  1400. s->vbv_delay_ptr[2] |= vbv_delay << 3;
  1401. avctx->vbv_delay = vbv_delay * 300;
  1402. }
  1403. s->total_bits += s->frame_bits;
  1404. avctx->frame_bits = s->frame_bits;
  1405. } else {
  1406. assert((put_bits_ptr(&s->pb) == s->pb.buf));
  1407. s->frame_bits = 0;
  1408. }
  1409. assert((s->frame_bits & 7) == 0);
  1410. return s->frame_bits / 8;
  1411. }
  1412. static inline void dct_single_coeff_elimination(MpegEncContext *s,
  1413. int n, int threshold)
  1414. {
  1415. static const char tab[64] = {
  1416. 3, 2, 2, 1, 1, 1, 1, 1,
  1417. 1, 1, 1, 1, 1, 1, 1, 1,
  1418. 1, 1, 1, 1, 1, 1, 1, 1,
  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. 0, 0, 0, 0, 0, 0, 0, 0
  1424. };
  1425. int score = 0;
  1426. int run = 0;
  1427. int i;
  1428. DCTELEM *block = s->block[n];
  1429. const int last_index = s->block_last_index[n];
  1430. int skip_dc;
  1431. if (threshold < 0) {
  1432. skip_dc = 0;
  1433. threshold = -threshold;
  1434. } else
  1435. skip_dc = 1;
  1436. /* Are all we could set to zero already zero? */
  1437. if (last_index <= skip_dc - 1)
  1438. return;
  1439. for (i = 0; i <= last_index; i++) {
  1440. const int j = s->intra_scantable.permutated[i];
  1441. const int level = FFABS(block[j]);
  1442. if (level == 1) {
  1443. if (skip_dc && i == 0)
  1444. continue;
  1445. score += tab[run];
  1446. run = 0;
  1447. } else if (level > 1) {
  1448. return;
  1449. } else {
  1450. run++;
  1451. }
  1452. }
  1453. if (score >= threshold)
  1454. return;
  1455. for (i = skip_dc; i <= last_index; i++) {
  1456. const int j = s->intra_scantable.permutated[i];
  1457. block[j] = 0;
  1458. }
  1459. if (block[0])
  1460. s->block_last_index[n] = 0;
  1461. else
  1462. s->block_last_index[n] = -1;
  1463. }
  1464. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block,
  1465. int last_index)
  1466. {
  1467. int i;
  1468. const int maxlevel = s->max_qcoeff;
  1469. const int minlevel = s->min_qcoeff;
  1470. int overflow = 0;
  1471. if (s->mb_intra) {
  1472. i = 1; // skip clipping of intra dc
  1473. } else
  1474. i = 0;
  1475. for (; i <= last_index; i++) {
  1476. const int j = s->intra_scantable.permutated[i];
  1477. int level = block[j];
  1478. if (level > maxlevel) {
  1479. level = maxlevel;
  1480. overflow++;
  1481. } else if (level < minlevel) {
  1482. level = minlevel;
  1483. overflow++;
  1484. }
  1485. block[j] = level;
  1486. }
  1487. if (overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1488. av_log(s->avctx, AV_LOG_INFO,
  1489. "warning, clipping %d dct coefficients to %d..%d\n",
  1490. overflow, minlevel, maxlevel);
  1491. }
  1492. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride)
  1493. {
  1494. int x, y;
  1495. // FIXME optimize
  1496. for (y = 0; y < 8; y++) {
  1497. for (x = 0; x < 8; x++) {
  1498. int x2, y2;
  1499. int sum = 0;
  1500. int sqr = 0;
  1501. int count = 0;
  1502. for (y2 = FFMAX(y - 1, 0); y2 < FFMIN(8, y + 2); y2++) {
  1503. for (x2= FFMAX(x - 1, 0); x2 < FFMIN(8, x + 2); x2++) {
  1504. int v = ptr[x2 + y2 * stride];
  1505. sum += v;
  1506. sqr += v * v;
  1507. count++;
  1508. }
  1509. }
  1510. weight[x + 8 * y]= (36 * ff_sqrt(count * sqr - sum * sum)) / count;
  1511. }
  1512. }
  1513. }
  1514. static av_always_inline void encode_mb_internal(MpegEncContext *s,
  1515. int motion_x, int motion_y,
  1516. int mb_block_height,
  1517. int mb_block_count)
  1518. {
  1519. int16_t weight[8][64];
  1520. DCTELEM orig[8][64];
  1521. const int mb_x = s->mb_x;
  1522. const int mb_y = s->mb_y;
  1523. int i;
  1524. int skip_dct[8];
  1525. int dct_offset = s->linesize * 8; // default for progressive frames
  1526. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1527. int wrap_y, wrap_c;
  1528. for (i = 0; i < mb_block_count; i++)
  1529. skip_dct[i] = s->skipdct;
  1530. if (s->adaptive_quant) {
  1531. const int last_qp = s->qscale;
  1532. const int mb_xy = mb_x + mb_y * s->mb_stride;
  1533. s->lambda = s->lambda_table[mb_xy];
  1534. update_qscale(s);
  1535. if (!(s->flags & CODEC_FLAG_QP_RD)) {
  1536. s->qscale = s->current_picture_ptr->f.qscale_table[mb_xy];
  1537. s->dquant = s->qscale - last_qp;
  1538. if (s->out_format == FMT_H263) {
  1539. s->dquant = av_clip(s->dquant, -2, 2);
  1540. if (s->codec_id == CODEC_ID_MPEG4) {
  1541. if (!s->mb_intra) {
  1542. if (s->pict_type == AV_PICTURE_TYPE_B) {
  1543. if (s->dquant & 1 || s->mv_dir & MV_DIRECT)
  1544. s->dquant = 0;
  1545. }
  1546. if (s->mv_type == MV_TYPE_8X8)
  1547. s->dquant = 0;
  1548. }
  1549. }
  1550. }
  1551. }
  1552. ff_set_qscale(s, last_qp + s->dquant);
  1553. } else if (s->flags & CODEC_FLAG_QP_RD)
  1554. ff_set_qscale(s, s->qscale + s->dquant);
  1555. wrap_y = s->linesize;
  1556. wrap_c = s->uvlinesize;
  1557. ptr_y = s->new_picture.f.data[0] +
  1558. (mb_y * 16 * wrap_y) + mb_x * 16;
  1559. ptr_cb = s->new_picture.f.data[1] +
  1560. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1561. ptr_cr = s->new_picture.f.data[2] +
  1562. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1563. if((mb_x*16+16 > s->width || mb_y*16+16 > s->height) && s->codec_id != CODEC_ID_AMV){
  1564. uint8_t *ebuf = s->edge_emu_buffer + 32;
  1565. s->dsp.emulated_edge_mc(ebuf, ptr_y, wrap_y, 16, 16, mb_x * 16,
  1566. mb_y * 16, s->width, s->height);
  1567. ptr_y = ebuf;
  1568. s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb, wrap_c, 8,
  1569. mb_block_height, mb_x * 8, mb_y * 8,
  1570. s->width >> 1, s->height >> 1);
  1571. ptr_cb = ebuf + 18 * wrap_y;
  1572. s->dsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr, wrap_c, 8,
  1573. mb_block_height, mb_x * 8, mb_y * 8,
  1574. s->width >> 1, s->height >> 1);
  1575. ptr_cr = ebuf + 18 * wrap_y + 8;
  1576. }
  1577. if (s->mb_intra) {
  1578. if (s->flags & CODEC_FLAG_INTERLACED_DCT) {
  1579. int progressive_score, interlaced_score;
  1580. s->interlaced_dct = 0;
  1581. progressive_score = s->dsp.ildct_cmp[4](s, ptr_y,
  1582. NULL, wrap_y, 8) +
  1583. s->dsp.ildct_cmp[4](s, ptr_y + wrap_y * 8,
  1584. NULL, wrap_y, 8) - 400;
  1585. if (progressive_score > 0) {
  1586. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y,
  1587. NULL, wrap_y * 2, 8) +
  1588. s->dsp.ildct_cmp[4](s, ptr_y + wrap_y,
  1589. NULL, wrap_y * 2, 8);
  1590. if (progressive_score > interlaced_score) {
  1591. s->interlaced_dct = 1;
  1592. dct_offset = wrap_y;
  1593. wrap_y <<= 1;
  1594. if (s->chroma_format == CHROMA_422)
  1595. wrap_c <<= 1;
  1596. }
  1597. }
  1598. }
  1599. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1600. s->dsp.get_pixels(s->block[1], ptr_y + 8 , wrap_y);
  1601. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1602. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8 , wrap_y);
  1603. if (s->flags & CODEC_FLAG_GRAY) {
  1604. skip_dct[4] = 1;
  1605. skip_dct[5] = 1;
  1606. } else {
  1607. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1608. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1609. if (!s->chroma_y_shift) { /* 422 */
  1610. s->dsp.get_pixels(s->block[6],
  1611. ptr_cb + (dct_offset >> 1), wrap_c);
  1612. s->dsp.get_pixels(s->block[7],
  1613. ptr_cr + (dct_offset >> 1), wrap_c);
  1614. }
  1615. }
  1616. } else {
  1617. op_pixels_func (*op_pix)[4];
  1618. qpel_mc_func (*op_qpix)[16];
  1619. uint8_t *dest_y, *dest_cb, *dest_cr;
  1620. dest_y = s->dest[0];
  1621. dest_cb = s->dest[1];
  1622. dest_cr = s->dest[2];
  1623. if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {
  1624. op_pix = s->dsp.put_pixels_tab;
  1625. op_qpix = s->dsp.put_qpel_pixels_tab;
  1626. } else {
  1627. op_pix = s->dsp.put_no_rnd_pixels_tab;
  1628. op_qpix = s->dsp.put_no_rnd_qpel_pixels_tab;
  1629. }
  1630. if (s->mv_dir & MV_DIR_FORWARD) {
  1631. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data,
  1632. op_pix, op_qpix);
  1633. op_pix = s->dsp.avg_pixels_tab;
  1634. op_qpix = s->dsp.avg_qpel_pixels_tab;
  1635. }
  1636. if (s->mv_dir & MV_DIR_BACKWARD) {
  1637. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data,
  1638. op_pix, op_qpix);
  1639. }
  1640. if (s->flags & CODEC_FLAG_INTERLACED_DCT) {
  1641. int progressive_score, interlaced_score;
  1642. s->interlaced_dct = 0;
  1643. progressive_score = s->dsp.ildct_cmp[0](s, dest_y,
  1644. ptr_y, wrap_y,
  1645. 8) +
  1646. s->dsp.ildct_cmp[0](s, dest_y + wrap_y * 8,
  1647. ptr_y + wrap_y * 8, wrap_y,
  1648. 8) - 400;
  1649. if (s->avctx->ildct_cmp == FF_CMP_VSSE)
  1650. progressive_score -= 400;
  1651. if (progressive_score > 0) {
  1652. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y,
  1653. ptr_y,
  1654. wrap_y * 2, 8) +
  1655. s->dsp.ildct_cmp[0](s, dest_y + wrap_y,
  1656. ptr_y + wrap_y,
  1657. wrap_y * 2, 8);
  1658. if (progressive_score > interlaced_score) {
  1659. s->interlaced_dct = 1;
  1660. dct_offset = wrap_y;
  1661. wrap_y <<= 1;
  1662. if (s->chroma_format == CHROMA_422)
  1663. wrap_c <<= 1;
  1664. }
  1665. }
  1666. }
  1667. s->dsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);
  1668. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1669. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset,
  1670. dest_y + dct_offset, wrap_y);
  1671. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,
  1672. dest_y + dct_offset + 8, wrap_y);
  1673. if (s->flags & CODEC_FLAG_GRAY) {
  1674. skip_dct[4] = 1;
  1675. skip_dct[5] = 1;
  1676. } else {
  1677. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1678. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1679. if (!s->chroma_y_shift) { /* 422 */
  1680. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),
  1681. dest_cb + (dct_offset >> 1), wrap_c);
  1682. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),
  1683. dest_cr + (dct_offset >> 1), wrap_c);
  1684. }
  1685. }
  1686. /* pre quantization */
  1687. if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <
  1688. 2 * s->qscale * s->qscale) {
  1689. // FIXME optimize
  1690. if (s->dsp.sad[1](NULL, ptr_y , dest_y,
  1691. wrap_y, 8) < 20 * s->qscale)
  1692. skip_dct[0] = 1;
  1693. if (s->dsp.sad[1](NULL, ptr_y + 8,
  1694. dest_y + 8, wrap_y, 8) < 20 * s->qscale)
  1695. skip_dct[1] = 1;
  1696. if (s->dsp.sad[1](NULL, ptr_y + dct_offset,
  1697. dest_y + dct_offset, wrap_y, 8) < 20 * s->qscale)
  1698. skip_dct[2] = 1;
  1699. if (s->dsp.sad[1](NULL, ptr_y + dct_offset + 8,
  1700. dest_y + dct_offset + 8,
  1701. wrap_y, 8) < 20 * s->qscale)
  1702. skip_dct[3] = 1;
  1703. if (s->dsp.sad[1](NULL, ptr_cb, dest_cb,
  1704. wrap_c, 8) < 20 * s->qscale)
  1705. skip_dct[4] = 1;
  1706. if (s->dsp.sad[1](NULL, ptr_cr, dest_cr,
  1707. wrap_c, 8) < 20 * s->qscale)
  1708. skip_dct[5] = 1;
  1709. if (!s->chroma_y_shift) { /* 422 */
  1710. if (s->dsp.sad[1](NULL, ptr_cb + (dct_offset >> 1),
  1711. dest_cb + (dct_offset >> 1),
  1712. wrap_c, 8) < 20 * s->qscale)
  1713. skip_dct[6] = 1;
  1714. if (s->dsp.sad[1](NULL, ptr_cr + (dct_offset >> 1),
  1715. dest_cr + (dct_offset >> 1),
  1716. wrap_c, 8) < 20 * s->qscale)
  1717. skip_dct[7] = 1;
  1718. }
  1719. }
  1720. }
  1721. if (s->avctx->quantizer_noise_shaping) {
  1722. if (!skip_dct[0])
  1723. get_visual_weight(weight[0], ptr_y , wrap_y);
  1724. if (!skip_dct[1])
  1725. get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1726. if (!skip_dct[2])
  1727. get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1728. if (!skip_dct[3])
  1729. get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1730. if (!skip_dct[4])
  1731. get_visual_weight(weight[4], ptr_cb , wrap_c);
  1732. if (!skip_dct[5])
  1733. get_visual_weight(weight[5], ptr_cr , wrap_c);
  1734. if (!s->chroma_y_shift) { /* 422 */
  1735. if (!skip_dct[6])
  1736. get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),
  1737. wrap_c);
  1738. if (!skip_dct[7])
  1739. get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),
  1740. wrap_c);
  1741. }
  1742. memcpy(orig[0], s->block[0], sizeof(DCTELEM) * 64 * mb_block_count);
  1743. }
  1744. /* DCT & quantize */
  1745. assert(s->out_format != FMT_MJPEG || s->qscale == 8);
  1746. {
  1747. for (i = 0; i < mb_block_count; i++) {
  1748. if (!skip_dct[i]) {
  1749. int overflow;
  1750. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1751. // FIXME we could decide to change to quantizer instead of
  1752. // clipping
  1753. // JS: I don't think that would be a good idea it could lower
  1754. // quality instead of improve it. Just INTRADC clipping
  1755. // deserves changes in quantizer
  1756. if (overflow)
  1757. clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1758. } else
  1759. s->block_last_index[i] = -1;
  1760. }
  1761. if (s->avctx->quantizer_noise_shaping) {
  1762. for (i = 0; i < mb_block_count; i++) {
  1763. if (!skip_dct[i]) {
  1764. s->block_last_index[i] =
  1765. dct_quantize_refine(s, s->block[i], weight[i],
  1766. orig[i], i, s->qscale);
  1767. }
  1768. }
  1769. }
  1770. if (s->luma_elim_threshold && !s->mb_intra)
  1771. for (i = 0; i < 4; i++)
  1772. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1773. if (s->chroma_elim_threshold && !s->mb_intra)
  1774. for (i = 4; i < mb_block_count; i++)
  1775. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1776. if (s->flags & CODEC_FLAG_CBP_RD) {
  1777. for (i = 0; i < mb_block_count; i++) {
  1778. if (s->block_last_index[i] == -1)
  1779. s->coded_score[i] = INT_MAX / 256;
  1780. }
  1781. }
  1782. }
  1783. if ((s->flags & CODEC_FLAG_GRAY) && s->mb_intra) {
  1784. s->block_last_index[4] =
  1785. s->block_last_index[5] = 0;
  1786. s->block[4][0] =
  1787. s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;
  1788. }
  1789. // non c quantize code returns incorrect block_last_index FIXME
  1790. if (s->alternate_scan && s->dct_quantize != dct_quantize_c) {
  1791. for (i = 0; i < mb_block_count; i++) {
  1792. int j;
  1793. if (s->block_last_index[i] > 0) {
  1794. for (j = 63; j > 0; j--) {
  1795. if (s->block[i][s->intra_scantable.permutated[j]])
  1796. break;
  1797. }
  1798. s->block_last_index[i] = j;
  1799. }
  1800. }
  1801. }
  1802. /* huffman encode */
  1803. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1804. case CODEC_ID_MPEG1VIDEO:
  1805. case CODEC_ID_MPEG2VIDEO:
  1806. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1807. mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1808. break;
  1809. case CODEC_ID_MPEG4:
  1810. if (CONFIG_MPEG4_ENCODER)
  1811. mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1812. break;
  1813. case CODEC_ID_MSMPEG4V2:
  1814. case CODEC_ID_MSMPEG4V3:
  1815. case CODEC_ID_WMV1:
  1816. if (CONFIG_MSMPEG4_ENCODER)
  1817. msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1818. break;
  1819. case CODEC_ID_WMV2:
  1820. if (CONFIG_WMV2_ENCODER)
  1821. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1822. break;
  1823. case CODEC_ID_H261:
  1824. if (CONFIG_H261_ENCODER)
  1825. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1826. break;
  1827. case CODEC_ID_H263:
  1828. case CODEC_ID_H263P:
  1829. case CODEC_ID_FLV1:
  1830. case CODEC_ID_RV10:
  1831. case CODEC_ID_RV20:
  1832. if (CONFIG_H263_ENCODER)
  1833. h263_encode_mb(s, s->block, motion_x, motion_y);
  1834. break;
  1835. case CODEC_ID_MJPEG:
  1836. case CODEC_ID_AMV:
  1837. if (CONFIG_MJPEG_ENCODER)
  1838. ff_mjpeg_encode_mb(s, s->block);
  1839. break;
  1840. default:
  1841. assert(0);
  1842. }
  1843. }
  1844. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1845. {
  1846. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1847. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1848. }
  1849. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1850. int i;
  1851. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1852. /* mpeg1 */
  1853. d->mb_skip_run= s->mb_skip_run;
  1854. for(i=0; i<3; i++)
  1855. d->last_dc[i] = s->last_dc[i];
  1856. /* statistics */
  1857. d->mv_bits= s->mv_bits;
  1858. d->i_tex_bits= s->i_tex_bits;
  1859. d->p_tex_bits= s->p_tex_bits;
  1860. d->i_count= s->i_count;
  1861. d->f_count= s->f_count;
  1862. d->b_count= s->b_count;
  1863. d->skip_count= s->skip_count;
  1864. d->misc_bits= s->misc_bits;
  1865. d->last_bits= 0;
  1866. d->mb_skipped= 0;
  1867. d->qscale= s->qscale;
  1868. d->dquant= s->dquant;
  1869. d->esc3_level_length= s->esc3_level_length;
  1870. }
  1871. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1872. int i;
  1873. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1874. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1875. /* mpeg1 */
  1876. d->mb_skip_run= s->mb_skip_run;
  1877. for(i=0; i<3; i++)
  1878. d->last_dc[i] = s->last_dc[i];
  1879. /* statistics */
  1880. d->mv_bits= s->mv_bits;
  1881. d->i_tex_bits= s->i_tex_bits;
  1882. d->p_tex_bits= s->p_tex_bits;
  1883. d->i_count= s->i_count;
  1884. d->f_count= s->f_count;
  1885. d->b_count= s->b_count;
  1886. d->skip_count= s->skip_count;
  1887. d->misc_bits= s->misc_bits;
  1888. d->mb_intra= s->mb_intra;
  1889. d->mb_skipped= s->mb_skipped;
  1890. d->mv_type= s->mv_type;
  1891. d->mv_dir= s->mv_dir;
  1892. d->pb= s->pb;
  1893. if(s->data_partitioning){
  1894. d->pb2= s->pb2;
  1895. d->tex_pb= s->tex_pb;
  1896. }
  1897. d->block= s->block;
  1898. for(i=0; i<8; i++)
  1899. d->block_last_index[i]= s->block_last_index[i];
  1900. d->interlaced_dct= s->interlaced_dct;
  1901. d->qscale= s->qscale;
  1902. d->esc3_level_length= s->esc3_level_length;
  1903. }
  1904. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1905. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1906. int *dmin, int *next_block, int motion_x, int motion_y)
  1907. {
  1908. int score;
  1909. uint8_t *dest_backup[3];
  1910. copy_context_before_encode(s, backup, type);
  1911. s->block= s->blocks[*next_block];
  1912. s->pb= pb[*next_block];
  1913. if(s->data_partitioning){
  1914. s->pb2 = pb2 [*next_block];
  1915. s->tex_pb= tex_pb[*next_block];
  1916. }
  1917. if(*next_block){
  1918. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1919. s->dest[0] = s->rd_scratchpad;
  1920. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1921. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1922. assert(s->linesize >= 32); //FIXME
  1923. }
  1924. encode_mb(s, motion_x, motion_y);
  1925. score= put_bits_count(&s->pb);
  1926. if(s->data_partitioning){
  1927. score+= put_bits_count(&s->pb2);
  1928. score+= put_bits_count(&s->tex_pb);
  1929. }
  1930. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1931. MPV_decode_mb(s, s->block);
  1932. score *= s->lambda2;
  1933. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1934. }
  1935. if(*next_block){
  1936. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1937. }
  1938. if(score<*dmin){
  1939. *dmin= score;
  1940. *next_block^=1;
  1941. copy_context_after_encode(best, s, type);
  1942. }
  1943. }
  1944. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1945. uint32_t *sq = ff_squareTbl + 256;
  1946. int acc=0;
  1947. int x,y;
  1948. if(w==16 && h==16)
  1949. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  1950. else if(w==8 && h==8)
  1951. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  1952. for(y=0; y<h; y++){
  1953. for(x=0; x<w; x++){
  1954. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  1955. }
  1956. }
  1957. assert(acc>=0);
  1958. return acc;
  1959. }
  1960. static int sse_mb(MpegEncContext *s){
  1961. int w= 16;
  1962. int h= 16;
  1963. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  1964. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  1965. if(w==16 && h==16)
  1966. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  1967. 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)
  1968. +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)
  1969. +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);
  1970. }else{
  1971. 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)
  1972. +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)
  1973. +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);
  1974. }
  1975. else
  1976. 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)
  1977. +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)
  1978. +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);
  1979. }
  1980. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  1981. MpegEncContext *s= *(void**)arg;
  1982. s->me.pre_pass=1;
  1983. s->me.dia_size= s->avctx->pre_dia_size;
  1984. s->first_slice_line=1;
  1985. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  1986. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  1987. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1988. }
  1989. s->first_slice_line=0;
  1990. }
  1991. s->me.pre_pass=0;
  1992. return 0;
  1993. }
  1994. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  1995. MpegEncContext *s= *(void**)arg;
  1996. ff_check_alignment();
  1997. s->me.dia_size= s->avctx->dia_size;
  1998. s->first_slice_line=1;
  1999. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  2000. s->mb_x=0; //for block init below
  2001. ff_init_block_index(s);
  2002. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  2003. s->block_index[0]+=2;
  2004. s->block_index[1]+=2;
  2005. s->block_index[2]+=2;
  2006. s->block_index[3]+=2;
  2007. /* compute motion vector & mb_type and store in context */
  2008. if(s->pict_type==AV_PICTURE_TYPE_B)
  2009. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  2010. else
  2011. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2012. }
  2013. s->first_slice_line=0;
  2014. }
  2015. return 0;
  2016. }
  2017. static int mb_var_thread(AVCodecContext *c, void *arg){
  2018. MpegEncContext *s= *(void**)arg;
  2019. int mb_x, mb_y;
  2020. ff_check_alignment();
  2021. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2022. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2023. int xx = mb_x * 16;
  2024. int yy = mb_y * 16;
  2025. uint8_t *pix = s->new_picture.f.data[0] + (yy * s->linesize) + xx;
  2026. int varc;
  2027. int sum = s->dsp.pix_sum(pix, s->linesize);
  2028. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500 + 128)>>8;
  2029. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  2030. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  2031. s->me.mb_var_sum_temp += varc;
  2032. }
  2033. }
  2034. return 0;
  2035. }
  2036. static void write_slice_end(MpegEncContext *s){
  2037. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
  2038. if(s->partitioned_frame){
  2039. ff_mpeg4_merge_partitions(s);
  2040. }
  2041. ff_mpeg4_stuffing(&s->pb);
  2042. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  2043. ff_mjpeg_encode_stuffing(&s->pb);
  2044. }
  2045. avpriv_align_put_bits(&s->pb);
  2046. flush_put_bits(&s->pb);
  2047. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  2048. s->misc_bits+= get_bits_diff(s);
  2049. }
  2050. static int encode_thread(AVCodecContext *c, void *arg){
  2051. MpegEncContext *s= *(void**)arg;
  2052. int mb_x, mb_y, pdif = 0;
  2053. int chr_h= 16>>s->chroma_y_shift;
  2054. int i, j;
  2055. MpegEncContext best_s, backup_s;
  2056. uint8_t bit_buf[2][MAX_MB_BYTES];
  2057. uint8_t bit_buf2[2][MAX_MB_BYTES];
  2058. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  2059. PutBitContext pb[2], pb2[2], tex_pb[2];
  2060. //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
  2061. ff_check_alignment();
  2062. for(i=0; i<2; i++){
  2063. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  2064. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  2065. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  2066. }
  2067. s->last_bits= put_bits_count(&s->pb);
  2068. s->mv_bits=0;
  2069. s->misc_bits=0;
  2070. s->i_tex_bits=0;
  2071. s->p_tex_bits=0;
  2072. s->i_count=0;
  2073. s->f_count=0;
  2074. s->b_count=0;
  2075. s->skip_count=0;
  2076. for(i=0; i<3; i++){
  2077. /* init last dc values */
  2078. /* note: quant matrix value (8) is implied here */
  2079. s->last_dc[i] = 128 << s->intra_dc_precision;
  2080. s->current_picture.f.error[i] = 0;
  2081. }
  2082. if(s->codec_id==CODEC_ID_AMV){
  2083. s->last_dc[0] = 128*8/13;
  2084. s->last_dc[1] = 128*8/14;
  2085. s->last_dc[2] = 128*8/14;
  2086. }
  2087. s->mb_skip_run = 0;
  2088. memset(s->last_mv, 0, sizeof(s->last_mv));
  2089. s->last_mv_dir = 0;
  2090. switch(s->codec_id){
  2091. case CODEC_ID_H263:
  2092. case CODEC_ID_H263P:
  2093. case CODEC_ID_FLV1:
  2094. if (CONFIG_H263_ENCODER)
  2095. s->gob_index = ff_h263_get_gob_height(s);
  2096. break;
  2097. case CODEC_ID_MPEG4:
  2098. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  2099. ff_mpeg4_init_partitions(s);
  2100. break;
  2101. }
  2102. s->resync_mb_x=0;
  2103. s->resync_mb_y=0;
  2104. s->first_slice_line = 1;
  2105. s->ptr_lastgob = s->pb.buf;
  2106. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2107. // printf("row %d at %X\n", s->mb_y, (int)s);
  2108. s->mb_x=0;
  2109. s->mb_y= mb_y;
  2110. ff_set_qscale(s, s->qscale);
  2111. ff_init_block_index(s);
  2112. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2113. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  2114. int mb_type= s->mb_type[xy];
  2115. // int d;
  2116. int dmin= INT_MAX;
  2117. int dir;
  2118. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  2119. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  2120. return -1;
  2121. }
  2122. if(s->data_partitioning){
  2123. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  2124. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  2125. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  2126. return -1;
  2127. }
  2128. }
  2129. s->mb_x = mb_x;
  2130. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  2131. ff_update_block_index(s);
  2132. if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
  2133. ff_h261_reorder_mb_index(s);
  2134. xy= s->mb_y*s->mb_stride + s->mb_x;
  2135. mb_type= s->mb_type[xy];
  2136. }
  2137. /* write gob / video packet header */
  2138. if(s->rtp_mode){
  2139. int current_packet_size, is_gob_start;
  2140. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  2141. is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  2142. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  2143. switch(s->codec_id){
  2144. case CODEC_ID_H263:
  2145. case CODEC_ID_H263P:
  2146. if(!s->h263_slice_structured)
  2147. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  2148. break;
  2149. case CODEC_ID_MPEG2VIDEO:
  2150. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  2151. case CODEC_ID_MPEG1VIDEO:
  2152. if(s->mb_skip_run) is_gob_start=0;
  2153. break;
  2154. }
  2155. if(is_gob_start){
  2156. if(s->start_mb_y != mb_y || mb_x!=0){
  2157. write_slice_end(s);
  2158. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
  2159. ff_mpeg4_init_partitions(s);
  2160. }
  2161. }
  2162. assert((put_bits_count(&s->pb)&7) == 0);
  2163. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2164. if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
  2165. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  2166. int d= 100 / s->avctx->error_rate;
  2167. if(r % d == 0){
  2168. current_packet_size=0;
  2169. s->pb.buf_ptr= s->ptr_lastgob;
  2170. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  2171. }
  2172. }
  2173. if (s->avctx->rtp_callback){
  2174. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  2175. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  2176. }
  2177. switch(s->codec_id){
  2178. case CODEC_ID_MPEG4:
  2179. if (CONFIG_MPEG4_ENCODER) {
  2180. ff_mpeg4_encode_video_packet_header(s);
  2181. ff_mpeg4_clean_buffers(s);
  2182. }
  2183. break;
  2184. case CODEC_ID_MPEG1VIDEO:
  2185. case CODEC_ID_MPEG2VIDEO:
  2186. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  2187. ff_mpeg1_encode_slice_header(s);
  2188. ff_mpeg1_clean_buffers(s);
  2189. }
  2190. break;
  2191. case CODEC_ID_H263:
  2192. case CODEC_ID_H263P:
  2193. if (CONFIG_H263_ENCODER)
  2194. h263_encode_gob_header(s, mb_y);
  2195. break;
  2196. }
  2197. if(s->flags&CODEC_FLAG_PASS1){
  2198. int bits= put_bits_count(&s->pb);
  2199. s->misc_bits+= bits - s->last_bits;
  2200. s->last_bits= bits;
  2201. }
  2202. s->ptr_lastgob += current_packet_size;
  2203. s->first_slice_line=1;
  2204. s->resync_mb_x=mb_x;
  2205. s->resync_mb_y=mb_y;
  2206. }
  2207. }
  2208. if( (s->resync_mb_x == s->mb_x)
  2209. && s->resync_mb_y+1 == s->mb_y){
  2210. s->first_slice_line=0;
  2211. }
  2212. s->mb_skipped=0;
  2213. s->dquant=0; //only for QP_RD
  2214. if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
  2215. int next_block=0;
  2216. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  2217. copy_context_before_encode(&backup_s, s, -1);
  2218. backup_s.pb= s->pb;
  2219. best_s.data_partitioning= s->data_partitioning;
  2220. best_s.partitioned_frame= s->partitioned_frame;
  2221. if(s->data_partitioning){
  2222. backup_s.pb2= s->pb2;
  2223. backup_s.tex_pb= s->tex_pb;
  2224. }
  2225. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  2226. s->mv_dir = MV_DIR_FORWARD;
  2227. s->mv_type = MV_TYPE_16X16;
  2228. s->mb_intra= 0;
  2229. s->mv[0][0][0] = s->p_mv_table[xy][0];
  2230. s->mv[0][0][1] = s->p_mv_table[xy][1];
  2231. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  2232. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2233. }
  2234. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  2235. s->mv_dir = MV_DIR_FORWARD;
  2236. s->mv_type = MV_TYPE_FIELD;
  2237. s->mb_intra= 0;
  2238. for(i=0; i<2; i++){
  2239. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2240. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2241. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2242. }
  2243. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  2244. &dmin, &next_block, 0, 0);
  2245. }
  2246. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  2247. s->mv_dir = MV_DIR_FORWARD;
  2248. s->mv_type = MV_TYPE_16X16;
  2249. s->mb_intra= 0;
  2250. s->mv[0][0][0] = 0;
  2251. s->mv[0][0][1] = 0;
  2252. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  2253. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2254. }
  2255. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  2256. s->mv_dir = MV_DIR_FORWARD;
  2257. s->mv_type = MV_TYPE_8X8;
  2258. s->mb_intra= 0;
  2259. for(i=0; i<4; i++){
  2260. s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
  2261. s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
  2262. }
  2263. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  2264. &dmin, &next_block, 0, 0);
  2265. }
  2266. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  2267. s->mv_dir = MV_DIR_FORWARD;
  2268. s->mv_type = MV_TYPE_16X16;
  2269. s->mb_intra= 0;
  2270. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2271. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2272. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  2273. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  2274. }
  2275. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  2276. s->mv_dir = MV_DIR_BACKWARD;
  2277. s->mv_type = MV_TYPE_16X16;
  2278. s->mb_intra= 0;
  2279. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2280. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2281. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  2282. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  2283. }
  2284. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  2285. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2286. s->mv_type = MV_TYPE_16X16;
  2287. s->mb_intra= 0;
  2288. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2289. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2290. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2291. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2292. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  2293. &dmin, &next_block, 0, 0);
  2294. }
  2295. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  2296. s->mv_dir = MV_DIR_FORWARD;
  2297. s->mv_type = MV_TYPE_FIELD;
  2298. s->mb_intra= 0;
  2299. for(i=0; i<2; i++){
  2300. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2301. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2302. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2303. }
  2304. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  2305. &dmin, &next_block, 0, 0);
  2306. }
  2307. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  2308. s->mv_dir = MV_DIR_BACKWARD;
  2309. s->mv_type = MV_TYPE_FIELD;
  2310. s->mb_intra= 0;
  2311. for(i=0; i<2; i++){
  2312. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2313. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2314. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2315. }
  2316. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  2317. &dmin, &next_block, 0, 0);
  2318. }
  2319. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  2320. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2321. s->mv_type = MV_TYPE_FIELD;
  2322. s->mb_intra= 0;
  2323. for(dir=0; dir<2; dir++){
  2324. for(i=0; i<2; i++){
  2325. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2326. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2327. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2328. }
  2329. }
  2330. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  2331. &dmin, &next_block, 0, 0);
  2332. }
  2333. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  2334. s->mv_dir = 0;
  2335. s->mv_type = MV_TYPE_16X16;
  2336. s->mb_intra= 1;
  2337. s->mv[0][0][0] = 0;
  2338. s->mv[0][0][1] = 0;
  2339. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  2340. &dmin, &next_block, 0, 0);
  2341. if(s->h263_pred || s->h263_aic){
  2342. if(best_s.mb_intra)
  2343. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  2344. else
  2345. ff_clean_intra_table_entries(s); //old mode?
  2346. }
  2347. }
  2348. if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
  2349. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  2350. const int last_qp= backup_s.qscale;
  2351. int qpi, qp, dc[6];
  2352. DCTELEM ac[6][16];
  2353. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2354. static const int dquant_tab[4]={-1,1,-2,2};
  2355. assert(backup_s.dquant == 0);
  2356. //FIXME intra
  2357. s->mv_dir= best_s.mv_dir;
  2358. s->mv_type = MV_TYPE_16X16;
  2359. s->mb_intra= best_s.mb_intra;
  2360. s->mv[0][0][0] = best_s.mv[0][0][0];
  2361. s->mv[0][0][1] = best_s.mv[0][0][1];
  2362. s->mv[1][0][0] = best_s.mv[1][0][0];
  2363. s->mv[1][0][1] = best_s.mv[1][0][1];
  2364. qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
  2365. for(; qpi<4; qpi++){
  2366. int dquant= dquant_tab[qpi];
  2367. qp= last_qp + dquant;
  2368. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2369. continue;
  2370. backup_s.dquant= dquant;
  2371. if(s->mb_intra && s->dc_val[0]){
  2372. for(i=0; i<6; i++){
  2373. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2374. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
  2375. }
  2376. }
  2377. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2378. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2379. if(best_s.qscale != qp){
  2380. if(s->mb_intra && s->dc_val[0]){
  2381. for(i=0; i<6; i++){
  2382. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2383. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
  2384. }
  2385. }
  2386. }
  2387. }
  2388. }
  2389. }
  2390. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2391. int mx= s->b_direct_mv_table[xy][0];
  2392. int my= s->b_direct_mv_table[xy][1];
  2393. backup_s.dquant = 0;
  2394. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2395. s->mb_intra= 0;
  2396. ff_mpeg4_set_direct_mv(s, mx, my);
  2397. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2398. &dmin, &next_block, mx, my);
  2399. }
  2400. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2401. backup_s.dquant = 0;
  2402. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2403. s->mb_intra= 0;
  2404. ff_mpeg4_set_direct_mv(s, 0, 0);
  2405. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2406. &dmin, &next_block, 0, 0);
  2407. }
  2408. if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
  2409. int coded=0;
  2410. for(i=0; i<6; i++)
  2411. coded |= s->block_last_index[i];
  2412. if(coded){
  2413. int mx,my;
  2414. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2415. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2416. mx=my=0; //FIXME find the one we actually used
  2417. ff_mpeg4_set_direct_mv(s, mx, my);
  2418. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2419. mx= s->mv[1][0][0];
  2420. my= s->mv[1][0][1];
  2421. }else{
  2422. mx= s->mv[0][0][0];
  2423. my= s->mv[0][0][1];
  2424. }
  2425. s->mv_dir= best_s.mv_dir;
  2426. s->mv_type = best_s.mv_type;
  2427. s->mb_intra= 0;
  2428. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2429. s->mv[0][0][1] = best_s.mv[0][0][1];
  2430. s->mv[1][0][0] = best_s.mv[1][0][0];
  2431. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2432. backup_s.dquant= 0;
  2433. s->skipdct=1;
  2434. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2435. &dmin, &next_block, mx, my);
  2436. s->skipdct=0;
  2437. }
  2438. }
  2439. s->current_picture.f.qscale_table[xy] = best_s.qscale;
  2440. copy_context_after_encode(s, &best_s, -1);
  2441. pb_bits_count= put_bits_count(&s->pb);
  2442. flush_put_bits(&s->pb);
  2443. avpriv_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2444. s->pb= backup_s.pb;
  2445. if(s->data_partitioning){
  2446. pb2_bits_count= put_bits_count(&s->pb2);
  2447. flush_put_bits(&s->pb2);
  2448. avpriv_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2449. s->pb2= backup_s.pb2;
  2450. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2451. flush_put_bits(&s->tex_pb);
  2452. avpriv_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2453. s->tex_pb= backup_s.tex_pb;
  2454. }
  2455. s->last_bits= put_bits_count(&s->pb);
  2456. if (CONFIG_H263_ENCODER &&
  2457. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2458. ff_h263_update_motion_val(s);
  2459. if(next_block==0){ //FIXME 16 vs linesize16
  2460. s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
  2461. s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2462. s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2463. }
  2464. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2465. MPV_decode_mb(s, s->block);
  2466. } else {
  2467. int motion_x = 0, motion_y = 0;
  2468. s->mv_type=MV_TYPE_16X16;
  2469. // only one MB-Type possible
  2470. switch(mb_type){
  2471. case CANDIDATE_MB_TYPE_INTRA:
  2472. s->mv_dir = 0;
  2473. s->mb_intra= 1;
  2474. motion_x= s->mv[0][0][0] = 0;
  2475. motion_y= s->mv[0][0][1] = 0;
  2476. break;
  2477. case CANDIDATE_MB_TYPE_INTER:
  2478. s->mv_dir = MV_DIR_FORWARD;
  2479. s->mb_intra= 0;
  2480. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2481. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2482. break;
  2483. case CANDIDATE_MB_TYPE_INTER_I:
  2484. s->mv_dir = MV_DIR_FORWARD;
  2485. s->mv_type = MV_TYPE_FIELD;
  2486. s->mb_intra= 0;
  2487. for(i=0; i<2; i++){
  2488. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2489. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2490. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2491. }
  2492. break;
  2493. case CANDIDATE_MB_TYPE_INTER4V:
  2494. s->mv_dir = MV_DIR_FORWARD;
  2495. s->mv_type = MV_TYPE_8X8;
  2496. s->mb_intra= 0;
  2497. for(i=0; i<4; i++){
  2498. s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
  2499. s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
  2500. }
  2501. break;
  2502. case CANDIDATE_MB_TYPE_DIRECT:
  2503. if (CONFIG_MPEG4_ENCODER) {
  2504. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2505. s->mb_intra= 0;
  2506. motion_x=s->b_direct_mv_table[xy][0];
  2507. motion_y=s->b_direct_mv_table[xy][1];
  2508. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2509. }
  2510. break;
  2511. case CANDIDATE_MB_TYPE_DIRECT0:
  2512. if (CONFIG_MPEG4_ENCODER) {
  2513. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2514. s->mb_intra= 0;
  2515. ff_mpeg4_set_direct_mv(s, 0, 0);
  2516. }
  2517. break;
  2518. case CANDIDATE_MB_TYPE_BIDIR:
  2519. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2520. s->mb_intra= 0;
  2521. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2522. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2523. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2524. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2525. break;
  2526. case CANDIDATE_MB_TYPE_BACKWARD:
  2527. s->mv_dir = MV_DIR_BACKWARD;
  2528. s->mb_intra= 0;
  2529. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2530. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2531. break;
  2532. case CANDIDATE_MB_TYPE_FORWARD:
  2533. s->mv_dir = MV_DIR_FORWARD;
  2534. s->mb_intra= 0;
  2535. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2536. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2537. // printf(" %d %d ", motion_x, motion_y);
  2538. break;
  2539. case CANDIDATE_MB_TYPE_FORWARD_I:
  2540. s->mv_dir = MV_DIR_FORWARD;
  2541. s->mv_type = MV_TYPE_FIELD;
  2542. s->mb_intra= 0;
  2543. for(i=0; i<2; i++){
  2544. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2545. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2546. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2547. }
  2548. break;
  2549. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2550. s->mv_dir = MV_DIR_BACKWARD;
  2551. s->mv_type = MV_TYPE_FIELD;
  2552. s->mb_intra= 0;
  2553. for(i=0; i<2; i++){
  2554. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2555. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2556. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2557. }
  2558. break;
  2559. case CANDIDATE_MB_TYPE_BIDIR_I:
  2560. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2561. s->mv_type = MV_TYPE_FIELD;
  2562. s->mb_intra= 0;
  2563. for(dir=0; dir<2; dir++){
  2564. for(i=0; i<2; i++){
  2565. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2566. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2567. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2568. }
  2569. }
  2570. break;
  2571. default:
  2572. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2573. }
  2574. encode_mb(s, motion_x, motion_y);
  2575. // RAL: Update last macroblock type
  2576. s->last_mv_dir = s->mv_dir;
  2577. if (CONFIG_H263_ENCODER &&
  2578. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2579. ff_h263_update_motion_val(s);
  2580. MPV_decode_mb(s, s->block);
  2581. }
  2582. /* clean the MV table in IPS frames for direct mode in B frames */
  2583. if(s->mb_intra /* && I,P,S_TYPE */){
  2584. s->p_mv_table[xy][0]=0;
  2585. s->p_mv_table[xy][1]=0;
  2586. }
  2587. if(s->flags&CODEC_FLAG_PSNR){
  2588. int w= 16;
  2589. int h= 16;
  2590. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2591. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2592. s->current_picture.f.error[0] += sse(
  2593. s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2594. s->dest[0], w, h, s->linesize);
  2595. s->current_picture.f.error[1] += sse(
  2596. s, s->new_picture.f.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2597. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2598. s->current_picture.f.error[2] += sse(
  2599. s, s->new_picture.f.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2600. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2601. }
  2602. if(s->loop_filter){
  2603. if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  2604. ff_h263_loop_filter(s);
  2605. }
  2606. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
  2607. }
  2608. }
  2609. //not beautiful here but we must write it before flushing so it has to be here
  2610. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
  2611. msmpeg4_encode_ext_header(s);
  2612. write_slice_end(s);
  2613. /* Send the last GOB if RTP */
  2614. if (s->avctx->rtp_callback) {
  2615. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2616. pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2617. /* Call the RTP callback to send the last GOB */
  2618. emms_c();
  2619. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2620. }
  2621. return 0;
  2622. }
  2623. #define MERGE(field) dst->field += src->field; src->field=0
  2624. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2625. MERGE(me.scene_change_score);
  2626. MERGE(me.mc_mb_var_sum_temp);
  2627. MERGE(me.mb_var_sum_temp);
  2628. }
  2629. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2630. int i;
  2631. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2632. MERGE(dct_count[1]);
  2633. MERGE(mv_bits);
  2634. MERGE(i_tex_bits);
  2635. MERGE(p_tex_bits);
  2636. MERGE(i_count);
  2637. MERGE(f_count);
  2638. MERGE(b_count);
  2639. MERGE(skip_count);
  2640. MERGE(misc_bits);
  2641. MERGE(error_count);
  2642. MERGE(padding_bug_score);
  2643. MERGE(current_picture.f.error[0]);
  2644. MERGE(current_picture.f.error[1]);
  2645. MERGE(current_picture.f.error[2]);
  2646. if(dst->avctx->noise_reduction){
  2647. for(i=0; i<64; i++){
  2648. MERGE(dct_error_sum[0][i]);
  2649. MERGE(dct_error_sum[1][i]);
  2650. }
  2651. }
  2652. assert(put_bits_count(&src->pb) % 8 ==0);
  2653. assert(put_bits_count(&dst->pb) % 8 ==0);
  2654. avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2655. flush_put_bits(&dst->pb);
  2656. }
  2657. static int estimate_qp(MpegEncContext *s, int dry_run){
  2658. if (s->next_lambda){
  2659. s->current_picture_ptr->f.quality =
  2660. s->current_picture.f.quality = s->next_lambda;
  2661. if(!dry_run) s->next_lambda= 0;
  2662. } else if (!s->fixed_qscale) {
  2663. s->current_picture_ptr->f.quality =
  2664. s->current_picture.f.quality = ff_rate_estimate_qscale(s, dry_run);
  2665. if (s->current_picture.f.quality < 0)
  2666. return -1;
  2667. }
  2668. if(s->adaptive_quant){
  2669. switch(s->codec_id){
  2670. case CODEC_ID_MPEG4:
  2671. if (CONFIG_MPEG4_ENCODER)
  2672. ff_clean_mpeg4_qscales(s);
  2673. break;
  2674. case CODEC_ID_H263:
  2675. case CODEC_ID_H263P:
  2676. case CODEC_ID_FLV1:
  2677. if (CONFIG_H263_ENCODER)
  2678. ff_clean_h263_qscales(s);
  2679. break;
  2680. default:
  2681. ff_init_qscale_tab(s);
  2682. }
  2683. s->lambda= s->lambda_table[0];
  2684. //FIXME broken
  2685. }else
  2686. s->lambda = s->current_picture.f.quality;
  2687. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  2688. update_qscale(s);
  2689. return 0;
  2690. }
  2691. /* must be called before writing the header */
  2692. static void set_frame_distances(MpegEncContext * s){
  2693. assert(s->current_picture_ptr->f.pts != AV_NOPTS_VALUE);
  2694. s->time = s->current_picture_ptr->f.pts * s->avctx->time_base.num;
  2695. if(s->pict_type==AV_PICTURE_TYPE_B){
  2696. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  2697. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  2698. }else{
  2699. s->pp_time= s->time - s->last_non_b_time;
  2700. s->last_non_b_time= s->time;
  2701. assert(s->picture_number==0 || s->pp_time > 0);
  2702. }
  2703. }
  2704. static int encode_picture(MpegEncContext *s, int picture_number)
  2705. {
  2706. int i;
  2707. int bits;
  2708. int context_count = s->slice_context_count;
  2709. s->picture_number = picture_number;
  2710. /* Reset the average MB variance */
  2711. s->me.mb_var_sum_temp =
  2712. s->me.mc_mb_var_sum_temp = 0;
  2713. /* we need to initialize some time vars before we can encode b-frames */
  2714. // RAL: Condition added for MPEG1VIDEO
  2715. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
  2716. set_frame_distances(s);
  2717. if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
  2718. ff_set_mpeg4_time(s);
  2719. s->me.scene_change_score=0;
  2720. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  2721. if(s->pict_type==AV_PICTURE_TYPE_I){
  2722. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2723. else s->no_rounding=0;
  2724. }else if(s->pict_type!=AV_PICTURE_TYPE_B){
  2725. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2726. s->no_rounding ^= 1;
  2727. }
  2728. if(s->flags & CODEC_FLAG_PASS2){
  2729. if (estimate_qp(s,1) < 0)
  2730. return -1;
  2731. ff_get_2pass_fcode(s);
  2732. }else if(!(s->flags & CODEC_FLAG_QSCALE)){
  2733. if(s->pict_type==AV_PICTURE_TYPE_B)
  2734. s->lambda= s->last_lambda_for[s->pict_type];
  2735. else
  2736. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  2737. update_qscale(s);
  2738. }
  2739. if(s->codec_id != CODEC_ID_AMV){
  2740. if(s->q_chroma_intra_matrix != s->q_intra_matrix ) av_freep(&s->q_chroma_intra_matrix);
  2741. if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
  2742. s->q_chroma_intra_matrix = s->q_intra_matrix;
  2743. s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
  2744. }
  2745. s->mb_intra=0; //for the rate distortion & bit compare functions
  2746. for(i=1; i<context_count; i++){
  2747. ff_update_duplicate_context(s->thread_context[i], s);
  2748. }
  2749. if(ff_init_me(s)<0)
  2750. return -1;
  2751. /* Estimate motion for every MB */
  2752. if(s->pict_type != AV_PICTURE_TYPE_I){
  2753. s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  2754. s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  2755. if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
  2756. if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
  2757. s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2758. }
  2759. }
  2760. s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2761. }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
  2762. /* I-Frame */
  2763. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2764. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2765. if(!s->fixed_qscale){
  2766. /* finding spatial complexity for I-frame rate control */
  2767. s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2768. }
  2769. }
  2770. for(i=1; i<context_count; i++){
  2771. merge_context_after_me(s, s->thread_context[i]);
  2772. }
  2773. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  2774. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  2775. emms_c();
  2776. if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
  2777. s->pict_type= AV_PICTURE_TYPE_I;
  2778. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2779. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2780. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2781. }
  2782. if(!s->umvplus){
  2783. if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
  2784. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  2785. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2786. int a,b;
  2787. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  2788. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  2789. s->f_code= FFMAX3(s->f_code, a, b);
  2790. }
  2791. ff_fix_long_p_mvs(s);
  2792. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  2793. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2794. int j;
  2795. for(i=0; i<2; i++){
  2796. for(j=0; j<2; j++)
  2797. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  2798. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  2799. }
  2800. }
  2801. }
  2802. if(s->pict_type==AV_PICTURE_TYPE_B){
  2803. int a, b;
  2804. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  2805. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2806. s->f_code = FFMAX(a, b);
  2807. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  2808. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2809. s->b_code = FFMAX(a, b);
  2810. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  2811. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  2812. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2813. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2814. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2815. int dir, j;
  2816. for(dir=0; dir<2; dir++){
  2817. for(i=0; i<2; i++){
  2818. for(j=0; j<2; j++){
  2819. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  2820. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  2821. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  2822. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  2823. }
  2824. }
  2825. }
  2826. }
  2827. }
  2828. }
  2829. if (estimate_qp(s, 0) < 0)
  2830. return -1;
  2831. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
  2832. s->qscale= 3; //reduce clipping problems
  2833. if (s->out_format == FMT_MJPEG) {
  2834. /* for mjpeg, we do include qscale in the matrix */
  2835. for(i=1;i<64;i++){
  2836. int j= s->dsp.idct_permutation[i];
  2837. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  2838. }
  2839. s->y_dc_scale_table=
  2840. s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
  2841. s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
  2842. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2843. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2844. s->qscale= 8;
  2845. }
  2846. if(s->codec_id == CODEC_ID_AMV){
  2847. 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};
  2848. 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};
  2849. for(i=1;i<64;i++){
  2850. int j= s->dsp.idct_permutation[ff_zigzag_direct[i]];
  2851. s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];
  2852. s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];
  2853. }
  2854. s->y_dc_scale_table= y;
  2855. s->c_dc_scale_table= c;
  2856. s->intra_matrix[0] = 13;
  2857. s->chroma_intra_matrix[0] = 14;
  2858. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2859. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2860. ff_convert_matrix(&s->dsp, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
  2861. s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2862. s->qscale= 8;
  2863. }
  2864. //FIXME var duplication
  2865. s->current_picture_ptr->f.key_frame =
  2866. s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
  2867. s->current_picture_ptr->f.pict_type =
  2868. s->current_picture.f.pict_type = s->pict_type;
  2869. if (s->current_picture.f.key_frame)
  2870. s->picture_in_gop_number=0;
  2871. s->last_bits= put_bits_count(&s->pb);
  2872. switch(s->out_format) {
  2873. case FMT_MJPEG:
  2874. if (CONFIG_MJPEG_ENCODER)
  2875. ff_mjpeg_encode_picture_header(s);
  2876. break;
  2877. case FMT_H261:
  2878. if (CONFIG_H261_ENCODER)
  2879. ff_h261_encode_picture_header(s, picture_number);
  2880. break;
  2881. case FMT_H263:
  2882. if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
  2883. ff_wmv2_encode_picture_header(s, picture_number);
  2884. else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  2885. msmpeg4_encode_picture_header(s, picture_number);
  2886. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  2887. mpeg4_encode_picture_header(s, picture_number);
  2888. else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
  2889. rv10_encode_picture_header(s, picture_number);
  2890. else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
  2891. rv20_encode_picture_header(s, picture_number);
  2892. else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
  2893. ff_flv_encode_picture_header(s, picture_number);
  2894. else if (CONFIG_H263_ENCODER)
  2895. h263_encode_picture_header(s, picture_number);
  2896. break;
  2897. case FMT_MPEG1:
  2898. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2899. mpeg1_encode_picture_header(s, picture_number);
  2900. break;
  2901. case FMT_H264:
  2902. break;
  2903. default:
  2904. assert(0);
  2905. }
  2906. bits= put_bits_count(&s->pb);
  2907. s->header_bits= bits - s->last_bits;
  2908. for(i=1; i<context_count; i++){
  2909. update_duplicate_context_after_me(s->thread_context[i], s);
  2910. }
  2911. s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2912. for(i=1; i<context_count; i++){
  2913. merge_context_after_encode(s, s->thread_context[i]);
  2914. }
  2915. emms_c();
  2916. return 0;
  2917. }
  2918. static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
  2919. const int intra= s->mb_intra;
  2920. int i;
  2921. s->dct_count[intra]++;
  2922. for(i=0; i<64; i++){
  2923. int level= block[i];
  2924. if(level){
  2925. if(level>0){
  2926. s->dct_error_sum[intra][i] += level;
  2927. level -= s->dct_offset[intra][i];
  2928. if(level<0) level=0;
  2929. }else{
  2930. s->dct_error_sum[intra][i] -= level;
  2931. level += s->dct_offset[intra][i];
  2932. if(level>0) level=0;
  2933. }
  2934. block[i]= level;
  2935. }
  2936. }
  2937. }
  2938. static int dct_quantize_trellis_c(MpegEncContext *s,
  2939. DCTELEM *block, int n,
  2940. int qscale, int *overflow){
  2941. const int *qmat;
  2942. const uint8_t *scantable= s->intra_scantable.scantable;
  2943. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2944. int max=0;
  2945. unsigned int threshold1, threshold2;
  2946. int bias=0;
  2947. int run_tab[65];
  2948. int level_tab[65];
  2949. int score_tab[65];
  2950. int survivor[65];
  2951. int survivor_count;
  2952. int last_run=0;
  2953. int last_level=0;
  2954. int last_score= 0;
  2955. int last_i;
  2956. int coeff[2][64];
  2957. int coeff_count[64];
  2958. int qmul, qadd, start_i, last_non_zero, i, dc;
  2959. const int esc_length= s->ac_esc_length;
  2960. uint8_t * length;
  2961. uint8_t * last_length;
  2962. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  2963. s->dsp.fdct (block);
  2964. if(s->dct_error_sum)
  2965. s->denoise_dct(s, block);
  2966. qmul= qscale*16;
  2967. qadd= ((qscale-1)|1)*8;
  2968. if (s->mb_intra) {
  2969. int q;
  2970. if (!s->h263_aic) {
  2971. if (n < 4)
  2972. q = s->y_dc_scale;
  2973. else
  2974. q = s->c_dc_scale;
  2975. q = q << 3;
  2976. } else{
  2977. /* For AIC we skip quant/dequant of INTRADC */
  2978. q = 1 << 3;
  2979. qadd=0;
  2980. }
  2981. /* note: block[0] is assumed to be positive */
  2982. block[0] = (block[0] + (q >> 1)) / q;
  2983. start_i = 1;
  2984. last_non_zero = 0;
  2985. qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  2986. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2987. bias= 1<<(QMAT_SHIFT-1);
  2988. length = s->intra_ac_vlc_length;
  2989. last_length= s->intra_ac_vlc_last_length;
  2990. } else {
  2991. start_i = 0;
  2992. last_non_zero = -1;
  2993. qmat = s->q_inter_matrix[qscale];
  2994. length = s->inter_ac_vlc_length;
  2995. last_length= s->inter_ac_vlc_last_length;
  2996. }
  2997. last_i= start_i;
  2998. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  2999. threshold2= (threshold1<<1);
  3000. for(i=63; i>=start_i; i--) {
  3001. const int j = scantable[i];
  3002. int level = block[j] * qmat[j];
  3003. if(((unsigned)(level+threshold1))>threshold2){
  3004. last_non_zero = i;
  3005. break;
  3006. }
  3007. }
  3008. for(i=start_i; i<=last_non_zero; i++) {
  3009. const int j = scantable[i];
  3010. int level = block[j] * qmat[j];
  3011. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  3012. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  3013. if(((unsigned)(level+threshold1))>threshold2){
  3014. if(level>0){
  3015. level= (bias + level)>>QMAT_SHIFT;
  3016. coeff[0][i]= level;
  3017. coeff[1][i]= level-1;
  3018. // coeff[2][k]= level-2;
  3019. }else{
  3020. level= (bias - level)>>QMAT_SHIFT;
  3021. coeff[0][i]= -level;
  3022. coeff[1][i]= -level+1;
  3023. // coeff[2][k]= -level+2;
  3024. }
  3025. coeff_count[i]= FFMIN(level, 2);
  3026. assert(coeff_count[i]);
  3027. max |=level;
  3028. }else{
  3029. coeff[0][i]= (level>>31)|1;
  3030. coeff_count[i]= 1;
  3031. }
  3032. }
  3033. *overflow= s->max_qcoeff < max; //overflow might have happened
  3034. if(last_non_zero < start_i){
  3035. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  3036. return last_non_zero;
  3037. }
  3038. score_tab[start_i]= 0;
  3039. survivor[0]= start_i;
  3040. survivor_count= 1;
  3041. for(i=start_i; i<=last_non_zero; i++){
  3042. int level_index, j, zero_distortion;
  3043. int dct_coeff= FFABS(block[ scantable[i] ]);
  3044. int best_score=256*256*256*120;
  3045. if ( s->dsp.fdct == fdct_ifast
  3046. #ifndef FAAN_POSTSCALE
  3047. || s->dsp.fdct == ff_faandct
  3048. #endif
  3049. )
  3050. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  3051. zero_distortion= dct_coeff*dct_coeff;
  3052. for(level_index=0; level_index < coeff_count[i]; level_index++){
  3053. int distortion;
  3054. int level= coeff[level_index][i];
  3055. const int alevel= FFABS(level);
  3056. int unquant_coeff;
  3057. assert(level);
  3058. if(s->out_format == FMT_H263){
  3059. unquant_coeff= alevel*qmul + qadd;
  3060. }else{ //MPEG1
  3061. j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
  3062. if(s->mb_intra){
  3063. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  3064. unquant_coeff = (unquant_coeff - 1) | 1;
  3065. }else{
  3066. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  3067. unquant_coeff = (unquant_coeff - 1) | 1;
  3068. }
  3069. unquant_coeff<<= 3;
  3070. }
  3071. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  3072. level+=64;
  3073. if((level&(~127)) == 0){
  3074. for(j=survivor_count-1; j>=0; j--){
  3075. int run= i - survivor[j];
  3076. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3077. score += score_tab[i-run];
  3078. if(score < best_score){
  3079. best_score= score;
  3080. run_tab[i+1]= run;
  3081. level_tab[i+1]= level-64;
  3082. }
  3083. }
  3084. if(s->out_format == FMT_H263){
  3085. for(j=survivor_count-1; j>=0; j--){
  3086. int run= i - survivor[j];
  3087. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3088. score += score_tab[i-run];
  3089. if(score < last_score){
  3090. last_score= score;
  3091. last_run= run;
  3092. last_level= level-64;
  3093. last_i= i+1;
  3094. }
  3095. }
  3096. }
  3097. }else{
  3098. distortion += esc_length*lambda;
  3099. for(j=survivor_count-1; j>=0; j--){
  3100. int run= i - survivor[j];
  3101. int score= distortion + score_tab[i-run];
  3102. if(score < best_score){
  3103. best_score= score;
  3104. run_tab[i+1]= run;
  3105. level_tab[i+1]= level-64;
  3106. }
  3107. }
  3108. if(s->out_format == FMT_H263){
  3109. for(j=survivor_count-1; j>=0; j--){
  3110. int run= i - survivor[j];
  3111. int score= distortion + score_tab[i-run];
  3112. if(score < last_score){
  3113. last_score= score;
  3114. last_run= run;
  3115. last_level= level-64;
  3116. last_i= i+1;
  3117. }
  3118. }
  3119. }
  3120. }
  3121. }
  3122. score_tab[i+1]= best_score;
  3123. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  3124. if(last_non_zero <= 27){
  3125. for(; survivor_count; survivor_count--){
  3126. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  3127. break;
  3128. }
  3129. }else{
  3130. for(; survivor_count; survivor_count--){
  3131. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  3132. break;
  3133. }
  3134. }
  3135. survivor[ survivor_count++ ]= i+1;
  3136. }
  3137. if(s->out_format != FMT_H263){
  3138. last_score= 256*256*256*120;
  3139. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  3140. int score= score_tab[i];
  3141. if(i) score += lambda*2; //FIXME exacter?
  3142. if(score < last_score){
  3143. last_score= score;
  3144. last_i= i;
  3145. last_level= level_tab[i];
  3146. last_run= run_tab[i];
  3147. }
  3148. }
  3149. }
  3150. s->coded_score[n] = last_score;
  3151. dc= FFABS(block[0]);
  3152. last_non_zero= last_i - 1;
  3153. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  3154. if(last_non_zero < start_i)
  3155. return last_non_zero;
  3156. if(last_non_zero == 0 && start_i == 0){
  3157. int best_level= 0;
  3158. int best_score= dc * dc;
  3159. for(i=0; i<coeff_count[0]; i++){
  3160. int level= coeff[i][0];
  3161. int alevel= FFABS(level);
  3162. int unquant_coeff, score, distortion;
  3163. if(s->out_format == FMT_H263){
  3164. unquant_coeff= (alevel*qmul + qadd)>>3;
  3165. }else{ //MPEG1
  3166. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  3167. unquant_coeff = (unquant_coeff - 1) | 1;
  3168. }
  3169. unquant_coeff = (unquant_coeff + 4) >> 3;
  3170. unquant_coeff<<= 3 + 3;
  3171. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  3172. level+=64;
  3173. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  3174. else score= distortion + esc_length*lambda;
  3175. if(score < best_score){
  3176. best_score= score;
  3177. best_level= level - 64;
  3178. }
  3179. }
  3180. block[0]= best_level;
  3181. s->coded_score[n] = best_score - dc*dc;
  3182. if(best_level == 0) return -1;
  3183. else return last_non_zero;
  3184. }
  3185. i= last_i;
  3186. assert(last_level);
  3187. block[ perm_scantable[last_non_zero] ]= last_level;
  3188. i -= last_run + 1;
  3189. for(; i>start_i; i -= run_tab[i] + 1){
  3190. block[ perm_scantable[i-1] ]= level_tab[i];
  3191. }
  3192. return last_non_zero;
  3193. }
  3194. //#define REFINE_STATS 1
  3195. static int16_t basis[64][64];
  3196. static void build_basis(uint8_t *perm){
  3197. int i, j, x, y;
  3198. emms_c();
  3199. for(i=0; i<8; i++){
  3200. for(j=0; j<8; j++){
  3201. for(y=0; y<8; y++){
  3202. for(x=0; x<8; x++){
  3203. double s= 0.25*(1<<BASIS_SHIFT);
  3204. int index= 8*i + j;
  3205. int perm_index= perm[index];
  3206. if(i==0) s*= sqrt(0.5);
  3207. if(j==0) s*= sqrt(0.5);
  3208. 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)));
  3209. }
  3210. }
  3211. }
  3212. }
  3213. }
  3214. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  3215. DCTELEM *block, int16_t *weight, DCTELEM *orig,
  3216. int n, int qscale){
  3217. int16_t rem[64];
  3218. LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
  3219. const uint8_t *scantable= s->intra_scantable.scantable;
  3220. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  3221. // unsigned int threshold1, threshold2;
  3222. // int bias=0;
  3223. int run_tab[65];
  3224. int prev_run=0;
  3225. int prev_level=0;
  3226. int qmul, qadd, start_i, last_non_zero, i, dc;
  3227. uint8_t * length;
  3228. uint8_t * last_length;
  3229. int lambda;
  3230. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  3231. #ifdef REFINE_STATS
  3232. static int count=0;
  3233. static int after_last=0;
  3234. static int to_zero=0;
  3235. static int from_zero=0;
  3236. static int raise=0;
  3237. static int lower=0;
  3238. static int messed_sign=0;
  3239. #endif
  3240. if(basis[0][0] == 0)
  3241. build_basis(s->dsp.idct_permutation);
  3242. qmul= qscale*2;
  3243. qadd= (qscale-1)|1;
  3244. if (s->mb_intra) {
  3245. if (!s->h263_aic) {
  3246. if (n < 4)
  3247. q = s->y_dc_scale;
  3248. else
  3249. q = s->c_dc_scale;
  3250. } else{
  3251. /* For AIC we skip quant/dequant of INTRADC */
  3252. q = 1;
  3253. qadd=0;
  3254. }
  3255. q <<= RECON_SHIFT-3;
  3256. /* note: block[0] is assumed to be positive */
  3257. dc= block[0]*q;
  3258. // block[0] = (block[0] + (q >> 1)) / q;
  3259. start_i = 1;
  3260. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  3261. // bias= 1<<(QMAT_SHIFT-1);
  3262. length = s->intra_ac_vlc_length;
  3263. last_length= s->intra_ac_vlc_last_length;
  3264. } else {
  3265. dc= 0;
  3266. start_i = 0;
  3267. length = s->inter_ac_vlc_length;
  3268. last_length= s->inter_ac_vlc_last_length;
  3269. }
  3270. last_non_zero = s->block_last_index[n];
  3271. #ifdef REFINE_STATS
  3272. {START_TIMER
  3273. #endif
  3274. dc += (1<<(RECON_SHIFT-1));
  3275. for(i=0; i<64; i++){
  3276. rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
  3277. }
  3278. #ifdef REFINE_STATS
  3279. STOP_TIMER("memset rem[]")}
  3280. #endif
  3281. sum=0;
  3282. for(i=0; i<64; i++){
  3283. int one= 36;
  3284. int qns=4;
  3285. int w;
  3286. w= FFABS(weight[i]) + qns*one;
  3287. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  3288. weight[i] = w;
  3289. // w=weight[i] = (63*qns + (w/2)) / w;
  3290. assert(w>0);
  3291. assert(w<(1<<6));
  3292. sum += w*w;
  3293. }
  3294. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  3295. #ifdef REFINE_STATS
  3296. {START_TIMER
  3297. #endif
  3298. run=0;
  3299. rle_index=0;
  3300. for(i=start_i; i<=last_non_zero; i++){
  3301. int j= perm_scantable[i];
  3302. const int level= block[j];
  3303. int coeff;
  3304. if(level){
  3305. if(level<0) coeff= qmul*level - qadd;
  3306. else coeff= qmul*level + qadd;
  3307. run_tab[rle_index++]=run;
  3308. run=0;
  3309. s->dsp.add_8x8basis(rem, basis[j], coeff);
  3310. }else{
  3311. run++;
  3312. }
  3313. }
  3314. #ifdef REFINE_STATS
  3315. if(last_non_zero>0){
  3316. STOP_TIMER("init rem[]")
  3317. }
  3318. }
  3319. {START_TIMER
  3320. #endif
  3321. for(;;){
  3322. int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
  3323. int best_coeff=0;
  3324. int best_change=0;
  3325. int run2, best_unquant_change=0, analyze_gradient;
  3326. #ifdef REFINE_STATS
  3327. {START_TIMER
  3328. #endif
  3329. analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
  3330. if(analyze_gradient){
  3331. #ifdef REFINE_STATS
  3332. {START_TIMER
  3333. #endif
  3334. for(i=0; i<64; i++){
  3335. int w= weight[i];
  3336. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  3337. }
  3338. #ifdef REFINE_STATS
  3339. STOP_TIMER("rem*w*w")}
  3340. {START_TIMER
  3341. #endif
  3342. s->dsp.fdct(d1);
  3343. #ifdef REFINE_STATS
  3344. STOP_TIMER("dct")}
  3345. #endif
  3346. }
  3347. if(start_i){
  3348. const int level= block[0];
  3349. int change, old_coeff;
  3350. assert(s->mb_intra);
  3351. old_coeff= q*level;
  3352. for(change=-1; change<=1; change+=2){
  3353. int new_level= level + change;
  3354. int score, new_coeff;
  3355. new_coeff= q*new_level;
  3356. if(new_coeff >= 2048 || new_coeff < 0)
  3357. continue;
  3358. score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
  3359. if(score<best_score){
  3360. best_score= score;
  3361. best_coeff= 0;
  3362. best_change= change;
  3363. best_unquant_change= new_coeff - old_coeff;
  3364. }
  3365. }
  3366. }
  3367. run=0;
  3368. rle_index=0;
  3369. run2= run_tab[rle_index++];
  3370. prev_level=0;
  3371. prev_run=0;
  3372. for(i=start_i; i<64; i++){
  3373. int j= perm_scantable[i];
  3374. const int level= block[j];
  3375. int change, old_coeff;
  3376. if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  3377. break;
  3378. if(level){
  3379. if(level<0) old_coeff= qmul*level - qadd;
  3380. else old_coeff= qmul*level + qadd;
  3381. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3382. }else{
  3383. old_coeff=0;
  3384. run2--;
  3385. assert(run2>=0 || i >= last_non_zero );
  3386. }
  3387. for(change=-1; change<=1; change+=2){
  3388. int new_level= level + change;
  3389. int score, new_coeff, unquant_change;
  3390. score=0;
  3391. if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3392. continue;
  3393. if(new_level){
  3394. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3395. else new_coeff= qmul*new_level + qadd;
  3396. if(new_coeff >= 2048 || new_coeff <= -2048)
  3397. continue;
  3398. //FIXME check for overflow
  3399. if(level){
  3400. if(level < 63 && level > -63){
  3401. if(i < last_non_zero)
  3402. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3403. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3404. else
  3405. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3406. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3407. }
  3408. }else{
  3409. assert(FFABS(new_level)==1);
  3410. if(analyze_gradient){
  3411. int g= d1[ scantable[i] ];
  3412. if(g && (g^new_level) >= 0)
  3413. continue;
  3414. }
  3415. if(i < last_non_zero){
  3416. int next_i= i + run2 + 1;
  3417. int next_level= block[ perm_scantable[next_i] ] + 64;
  3418. if(next_level&(~127))
  3419. next_level= 0;
  3420. if(next_i < last_non_zero)
  3421. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3422. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3423. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3424. else
  3425. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3426. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3427. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3428. }else{
  3429. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3430. if(prev_level){
  3431. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3432. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3433. }
  3434. }
  3435. }
  3436. }else{
  3437. new_coeff=0;
  3438. assert(FFABS(level)==1);
  3439. if(i < last_non_zero){
  3440. int next_i= i + run2 + 1;
  3441. int next_level= block[ perm_scantable[next_i] ] + 64;
  3442. if(next_level&(~127))
  3443. next_level= 0;
  3444. if(next_i < last_non_zero)
  3445. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3446. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3447. - length[UNI_AC_ENC_INDEX(run, 65)];
  3448. else
  3449. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3450. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3451. - length[UNI_AC_ENC_INDEX(run, 65)];
  3452. }else{
  3453. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3454. if(prev_level){
  3455. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3456. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3457. }
  3458. }
  3459. }
  3460. score *= lambda;
  3461. unquant_change= new_coeff - old_coeff;
  3462. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3463. score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
  3464. if(score<best_score){
  3465. best_score= score;
  3466. best_coeff= i;
  3467. best_change= change;
  3468. best_unquant_change= unquant_change;
  3469. }
  3470. }
  3471. if(level){
  3472. prev_level= level + 64;
  3473. if(prev_level&(~127))
  3474. prev_level= 0;
  3475. prev_run= run;
  3476. run=0;
  3477. }else{
  3478. run++;
  3479. }
  3480. }
  3481. #ifdef REFINE_STATS
  3482. STOP_TIMER("iterative step")}
  3483. #endif
  3484. if(best_change){
  3485. int j= perm_scantable[ best_coeff ];
  3486. block[j] += best_change;
  3487. if(best_coeff > last_non_zero){
  3488. last_non_zero= best_coeff;
  3489. assert(block[j]);
  3490. #ifdef REFINE_STATS
  3491. after_last++;
  3492. #endif
  3493. }else{
  3494. #ifdef REFINE_STATS
  3495. if(block[j]){
  3496. if(block[j] - best_change){
  3497. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3498. raise++;
  3499. }else{
  3500. lower++;
  3501. }
  3502. }else{
  3503. from_zero++;
  3504. }
  3505. }else{
  3506. to_zero++;
  3507. }
  3508. #endif
  3509. for(; last_non_zero>=start_i; last_non_zero--){
  3510. if(block[perm_scantable[last_non_zero]])
  3511. break;
  3512. }
  3513. }
  3514. #ifdef REFINE_STATS
  3515. count++;
  3516. if(256*256*256*64 % count == 0){
  3517. 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);
  3518. }
  3519. #endif
  3520. run=0;
  3521. rle_index=0;
  3522. for(i=start_i; i<=last_non_zero; i++){
  3523. int j= perm_scantable[i];
  3524. const int level= block[j];
  3525. if(level){
  3526. run_tab[rle_index++]=run;
  3527. run=0;
  3528. }else{
  3529. run++;
  3530. }
  3531. }
  3532. s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3533. }else{
  3534. break;
  3535. }
  3536. }
  3537. #ifdef REFINE_STATS
  3538. if(last_non_zero>0){
  3539. STOP_TIMER("iterative search")
  3540. }
  3541. }
  3542. #endif
  3543. return last_non_zero;
  3544. }
  3545. int dct_quantize_c(MpegEncContext *s,
  3546. DCTELEM *block, int n,
  3547. int qscale, int *overflow)
  3548. {
  3549. int i, j, level, last_non_zero, q, start_i;
  3550. const int *qmat;
  3551. const uint8_t *scantable= s->intra_scantable.scantable;
  3552. int bias;
  3553. int max=0;
  3554. unsigned int threshold1, threshold2;
  3555. s->dsp.fdct (block);
  3556. if(s->dct_error_sum)
  3557. s->denoise_dct(s, block);
  3558. if (s->mb_intra) {
  3559. if (!s->h263_aic) {
  3560. if (n < 4)
  3561. q = s->y_dc_scale;
  3562. else
  3563. q = s->c_dc_scale;
  3564. q = q << 3;
  3565. } else
  3566. /* For AIC we skip quant/dequant of INTRADC */
  3567. q = 1 << 3;
  3568. /* note: block[0] is assumed to be positive */
  3569. block[0] = (block[0] + (q >> 1)) / q;
  3570. start_i = 1;
  3571. last_non_zero = 0;
  3572. qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  3573. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3574. } else {
  3575. start_i = 0;
  3576. last_non_zero = -1;
  3577. qmat = s->q_inter_matrix[qscale];
  3578. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3579. }
  3580. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3581. threshold2= (threshold1<<1);
  3582. for(i=63;i>=start_i;i--) {
  3583. j = scantable[i];
  3584. level = block[j] * qmat[j];
  3585. if(((unsigned)(level+threshold1))>threshold2){
  3586. last_non_zero = i;
  3587. break;
  3588. }else{
  3589. block[j]=0;
  3590. }
  3591. }
  3592. for(i=start_i; i<=last_non_zero; i++) {
  3593. j = scantable[i];
  3594. level = block[j] * qmat[j];
  3595. // if( bias+level >= (1<<QMAT_SHIFT)
  3596. // || bias-level >= (1<<QMAT_SHIFT)){
  3597. if(((unsigned)(level+threshold1))>threshold2){
  3598. if(level>0){
  3599. level= (bias + level)>>QMAT_SHIFT;
  3600. block[j]= level;
  3601. }else{
  3602. level= (bias - level)>>QMAT_SHIFT;
  3603. block[j]= -level;
  3604. }
  3605. max |=level;
  3606. }else{
  3607. block[j]=0;
  3608. }
  3609. }
  3610. *overflow= s->max_qcoeff < max; //overflow might have happened
  3611. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3612. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3613. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3614. return last_non_zero;
  3615. }
  3616. #define OFFSET(x) offsetof(MpegEncContext, x)
  3617. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  3618. static const AVOption h263_options[] = {
  3619. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3620. { "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},
  3621. { NULL },
  3622. };
  3623. static const AVClass h263_class = {
  3624. .class_name = "H.263 encoder",
  3625. .item_name = av_default_item_name,
  3626. .option = h263_options,
  3627. .version = LIBAVUTIL_VERSION_INT,
  3628. };
  3629. AVCodec ff_h263_encoder = {
  3630. .name = "h263",
  3631. .type = AVMEDIA_TYPE_VIDEO,
  3632. .id = CODEC_ID_H263,
  3633. .priv_data_size = sizeof(MpegEncContext),
  3634. .init = MPV_encode_init,
  3635. .encode = MPV_encode_picture,
  3636. .close = MPV_encode_end,
  3637. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3638. .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3639. .priv_class = &h263_class,
  3640. };
  3641. static const AVOption h263p_options[] = {
  3642. { "umv", "Use unlimited motion vectors.", OFFSET(umvplus), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3643. { "aiv", "Use alternative inter VLC.", OFFSET(alt_inter_vlc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3644. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3645. { "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},
  3646. { NULL },
  3647. };
  3648. static const AVClass h263p_class = {
  3649. .class_name = "H.263p encoder",
  3650. .item_name = av_default_item_name,
  3651. .option = h263p_options,
  3652. .version = LIBAVUTIL_VERSION_INT,
  3653. };
  3654. AVCodec ff_h263p_encoder = {
  3655. .name = "h263p",
  3656. .type = AVMEDIA_TYPE_VIDEO,
  3657. .id = CODEC_ID_H263P,
  3658. .priv_data_size = sizeof(MpegEncContext),
  3659. .init = MPV_encode_init,
  3660. .encode = MPV_encode_picture,
  3661. .close = MPV_encode_end,
  3662. .capabilities = CODEC_CAP_SLICE_THREADS,
  3663. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3664. .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  3665. .priv_class = &h263p_class,
  3666. };
  3667. AVCodec ff_msmpeg4v2_encoder = {
  3668. .name = "msmpeg4v2",
  3669. .type = AVMEDIA_TYPE_VIDEO,
  3670. .id = CODEC_ID_MSMPEG4V2,
  3671. .priv_data_size = sizeof(MpegEncContext),
  3672. .init = MPV_encode_init,
  3673. .encode = MPV_encode_picture,
  3674. .close = MPV_encode_end,
  3675. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3676. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  3677. };
  3678. AVCodec ff_msmpeg4v3_encoder = {
  3679. .name = "msmpeg4",
  3680. .type = AVMEDIA_TYPE_VIDEO,
  3681. .id = CODEC_ID_MSMPEG4V3,
  3682. .priv_data_size = sizeof(MpegEncContext),
  3683. .init = MPV_encode_init,
  3684. .encode = MPV_encode_picture,
  3685. .close = MPV_encode_end,
  3686. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3687. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  3688. };
  3689. AVCodec ff_wmv1_encoder = {
  3690. .name = "wmv1",
  3691. .type = AVMEDIA_TYPE_VIDEO,
  3692. .id = CODEC_ID_WMV1,
  3693. .priv_data_size = sizeof(MpegEncContext),
  3694. .init = MPV_encode_init,
  3695. .encode = MPV_encode_picture,
  3696. .close = MPV_encode_end,
  3697. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3698. .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  3699. };