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.

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