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.

4065 lines
148KB

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