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.

4298 lines
156KB

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