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.

4114 lines
148KB

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