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.

4273 lines
155KB

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