You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4298 lines
154KB

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