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.

4212 lines
152KB

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