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.

4172 lines
150KB

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