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.

4311 lines
155KB

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