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.

4157 lines
151KB

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