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.

4135 lines
149KB

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