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.

4152 lines
151KB

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