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.

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