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.

4301 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 "avcodec.h"
  35. #include "dct.h"
  36. #include "dsputil.h"
  37. #include "mpeg12.h"
  38. #include "mpegvideo.h"
  39. #include "h261.h"
  40. #include "h263.h"
  41. #include "mathops.h"
  42. #include "mjpegenc.h"
  43. #include "msmpeg4.h"
  44. #include "faandct.h"
  45. #include "thread.h"
  46. #include "aandcttab.h"
  47. #include "flv.h"
  48. #include "mpeg4video.h"
  49. #include "internal.h"
  50. #include "bytestream.h"
  51. #include <limits.h>
  52. static int encode_picture(MpegEncContext *s, int picture_number);
  53. static int dct_quantize_refine(MpegEncContext *s, int16_t *block, int16_t *weight, int16_t *orig, int n, int qscale);
  54. static int sse_mb(MpegEncContext *s);
  55. static void denoise_dct_c(MpegEncContext *s, int16_t *block);
  56. static int dct_quantize_trellis_c(MpegEncContext *s, int16_t *block, int n, int qscale, int *overflow);
  57. static uint8_t default_mv_penalty[MAX_FCODE + 1][MAX_MV * 2 + 1];
  58. static uint8_t default_fcode_tab[MAX_MV * 2 + 1];
  59. const AVOption ff_mpv_generic_options[] = {
  60. FF_MPV_COMMON_OPTS
  61. { NULL },
  62. };
  63. void ff_convert_matrix(DSPContext *dsp, int (*qmat)[64],
  64. uint16_t (*qmat16)[2][64],
  65. const uint16_t *quant_matrix,
  66. int bias, int qmin, int qmax, int intra)
  67. {
  68. int qscale;
  69. int shift = 0;
  70. for (qscale = qmin; qscale <= qmax; qscale++) {
  71. int i;
  72. if (dsp->fdct == ff_jpeg_fdct_islow_8 ||
  73. dsp->fdct == ff_jpeg_fdct_islow_10 ||
  74. dsp->fdct == ff_faandct) {
  75. for (i = 0; i < 64; i++) {
  76. const int j = dsp->idct_permutation[i];
  77. /* 16 <= qscale * quant_matrix[i] <= 7905
  78. * Assume x = ff_aanscales[i] * qscale * quant_matrix[i]
  79. * 19952 <= x <= 249205026
  80. * (1 << 36) / 19952 >= (1 << 36) / (x) >= (1 << 36) / 249205026
  81. * 3444240 >= (1 << 36) / (x) >= 275 */
  82. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
  83. (qscale * quant_matrix[j]));
  84. }
  85. } else if (dsp->fdct == ff_fdct_ifast) {
  86. for (i = 0; i < 64; i++) {
  87. const int j = dsp->idct_permutation[i];
  88. /* 16 <= qscale * quant_matrix[i] <= 7905
  89. * Assume x = ff_aanscales[i] * qscale * quant_matrix[i]
  90. * 19952 <= x <= 249205026
  91. * (1 << 36) / 19952 >= (1 << 36) / (x) >= (1 << 36) / 249205026
  92. * 3444240 >= (1 << 36) / (x) >= 275 */
  93. qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) /
  94. (ff_aanscales[i] * qscale *
  95. quant_matrix[j]));
  96. }
  97. } else {
  98. for (i = 0; i < 64; i++) {
  99. const int j = dsp->idct_permutation[i];
  100. /* We can safely suppose that 16 <= quant_matrix[i] <= 255
  101. * Assume x = qscale * quant_matrix[i]
  102. * So 16 <= x <= 7905
  103. * so (1 << 19) / 16 >= (1 << 19) / (x) >= (1 << 19) / 7905
  104. * so 32768 >= (1 << 19) / (x) >= 67 */
  105. qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) /
  106. (qscale * quant_matrix[j]));
  107. //qmat [qscale][i] = (1 << QMAT_SHIFT_MMX) /
  108. // (qscale * quant_matrix[i]);
  109. qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) /
  110. (qscale * quant_matrix[j]);
  111. if (qmat16[qscale][0][i] == 0 ||
  112. qmat16[qscale][0][i] == 128 * 256)
  113. qmat16[qscale][0][i] = 128 * 256 - 1;
  114. qmat16[qscale][1][i] =
  115. ROUNDED_DIV(bias << (16 - QUANT_BIAS_SHIFT),
  116. qmat16[qscale][0][i]);
  117. }
  118. }
  119. for (i = intra; i < 64; i++) {
  120. int64_t max = 8191;
  121. if (dsp->fdct == ff_fdct_ifast) {
  122. max = (8191LL * ff_aanscales[i]) >> 14;
  123. }
  124. while (((max * qmat[qscale][i]) >> shift) > INT_MAX) {
  125. shift++;
  126. }
  127. }
  128. }
  129. if (shift) {
  130. av_log(NULL, AV_LOG_INFO,
  131. "Warning, QMAT_SHIFT is larger than %d, overflows possible\n",
  132. QMAT_SHIFT - shift);
  133. }
  134. }
  135. static inline void update_qscale(MpegEncContext *s)
  136. {
  137. s->qscale = (s->lambda * 139 + FF_LAMBDA_SCALE * 64) >>
  138. (FF_LAMBDA_SHIFT + 7);
  139. s->qscale = av_clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
  140. s->lambda2 = (s->lambda * s->lambda + FF_LAMBDA_SCALE / 2) >>
  141. FF_LAMBDA_SHIFT;
  142. }
  143. void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix)
  144. {
  145. int i;
  146. if (matrix) {
  147. put_bits(pb, 1, 1);
  148. for (i = 0; i < 64; i++) {
  149. put_bits(pb, 8, matrix[ff_zigzag_direct[i]]);
  150. }
  151. } else
  152. put_bits(pb, 1, 0);
  153. }
  154. /**
  155. * init s->current_picture.qscale_table from s->lambda_table
  156. */
  157. void ff_init_qscale_tab(MpegEncContext *s)
  158. {
  159. int8_t * const qscale_table = s->current_picture.qscale_table;
  160. int i;
  161. for (i = 0; i < s->mb_num; i++) {
  162. unsigned int lam = s->lambda_table[s->mb_index2xy[i]];
  163. int qp = (lam * 139 + FF_LAMBDA_SCALE * 64) >> (FF_LAMBDA_SHIFT + 7);
  164. qscale_table[s->mb_index2xy[i]] = av_clip(qp, s->avctx->qmin,
  165. s->avctx->qmax);
  166. }
  167. }
  168. static void update_duplicate_context_after_me(MpegEncContext *dst,
  169. MpegEncContext *src)
  170. {
  171. #define COPY(a) dst->a= src->a
  172. COPY(pict_type);
  173. COPY(current_picture);
  174. COPY(f_code);
  175. COPY(b_code);
  176. COPY(qscale);
  177. COPY(lambda);
  178. COPY(lambda2);
  179. COPY(picture_in_gop_number);
  180. COPY(gop_picture_number);
  181. COPY(frame_pred_frame_dct); // FIXME don't set in encode_header
  182. COPY(progressive_frame); // FIXME don't set in encode_header
  183. COPY(partitioned_frame); // FIXME don't set in encode_header
  184. #undef COPY
  185. }
  186. /**
  187. * Set the given MpegEncContext to defaults for encoding.
  188. * the changed fields will not depend upon the prior state of the MpegEncContext.
  189. */
  190. static void MPV_encode_defaults(MpegEncContext *s)
  191. {
  192. int i;
  193. ff_MPV_common_defaults(s);
  194. for (i = -16; i < 16; i++) {
  195. default_fcode_tab[i + MAX_MV] = 1;
  196. }
  197. s->me.mv_penalty = default_mv_penalty;
  198. s->fcode_tab = default_fcode_tab;
  199. s->input_picture_number = 0;
  200. s->picture_in_gop_number = 0;
  201. }
  202. /* init video encoder */
  203. av_cold int ff_MPV_encode_init(AVCodecContext *avctx)
  204. {
  205. MpegEncContext *s = avctx->priv_data;
  206. int i, ret;
  207. MPV_encode_defaults(s);
  208. switch (avctx->codec_id) {
  209. case AV_CODEC_ID_MPEG2VIDEO:
  210. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
  211. avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
  212. av_log(avctx, AV_LOG_ERROR,
  213. "only YUV420 and YUV422 are supported\n");
  214. return -1;
  215. }
  216. break;
  217. case AV_CODEC_ID_MJPEG:
  218. if (avctx->pix_fmt != AV_PIX_FMT_YUVJ420P &&
  219. avctx->pix_fmt != AV_PIX_FMT_YUVJ422P &&
  220. ((avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
  221. avctx->pix_fmt != AV_PIX_FMT_YUV422P) ||
  222. avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)) {
  223. av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
  224. return -1;
  225. }
  226. break;
  227. default:
  228. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  229. av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
  230. return -1;
  231. }
  232. }
  233. switch (avctx->pix_fmt) {
  234. case AV_PIX_FMT_YUVJ422P:
  235. case AV_PIX_FMT_YUV422P:
  236. s->chroma_format = CHROMA_422;
  237. break;
  238. case AV_PIX_FMT_YUVJ420P:
  239. case AV_PIX_FMT_YUV420P:
  240. default:
  241. s->chroma_format = CHROMA_420;
  242. break;
  243. }
  244. s->bit_rate = avctx->bit_rate;
  245. s->width = avctx->width;
  246. s->height = avctx->height;
  247. if (avctx->gop_size > 600 &&
  248. avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  249. av_log(avctx, AV_LOG_ERROR,
  250. "Warning keyframe interval too large! reducing it ...\n");
  251. avctx->gop_size = 600;
  252. }
  253. s->gop_size = avctx->gop_size;
  254. s->avctx = avctx;
  255. s->flags = avctx->flags;
  256. s->flags2 = avctx->flags2;
  257. if (avctx->max_b_frames > MAX_B_FRAMES) {
  258. av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "
  259. "is %d.\n", MAX_B_FRAMES);
  260. }
  261. s->max_b_frames = avctx->max_b_frames;
  262. s->codec_id = avctx->codec->id;
  263. s->strict_std_compliance = avctx->strict_std_compliance;
  264. s->quarter_sample = (avctx->flags & CODEC_FLAG_QPEL) != 0;
  265. s->mpeg_quant = avctx->mpeg_quant;
  266. s->rtp_mode = !!avctx->rtp_payload_size;
  267. s->intra_dc_precision = avctx->intra_dc_precision;
  268. s->user_specified_pts = AV_NOPTS_VALUE;
  269. if (s->gop_size <= 1) {
  270. s->intra_only = 1;
  271. s->gop_size = 12;
  272. } else {
  273. s->intra_only = 0;
  274. }
  275. s->me_method = avctx->me_method;
  276. /* Fixed QSCALE */
  277. s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);
  278. s->adaptive_quant = (s->avctx->lumi_masking ||
  279. s->avctx->dark_masking ||
  280. s->avctx->temporal_cplx_masking ||
  281. s->avctx->spatial_cplx_masking ||
  282. s->avctx->p_masking ||
  283. s->avctx->border_masking ||
  284. (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&
  285. !s->fixed_qscale;
  286. s->loop_filter = !!(s->flags & CODEC_FLAG_LOOP_FILTER);
  287. if (avctx->rc_max_rate && !avctx->rc_buffer_size) {
  288. av_log(avctx, AV_LOG_ERROR,
  289. "a vbv buffer size is needed, "
  290. "for encoding with a maximum bitrate\n");
  291. return -1;
  292. }
  293. if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {
  294. av_log(avctx, AV_LOG_INFO,
  295. "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
  296. }
  297. if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {
  298. av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
  299. return -1;
  300. }
  301. if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
  302. av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");
  303. return -1;
  304. }
  305. if (avctx->rc_max_rate &&
  306. avctx->rc_max_rate == avctx->bit_rate &&
  307. avctx->rc_max_rate != avctx->rc_min_rate) {
  308. av_log(avctx, AV_LOG_INFO,
  309. "impossible bitrate constraints, this will fail\n");
  310. }
  311. if (avctx->rc_buffer_size &&
  312. avctx->bit_rate * (int64_t)avctx->time_base.num >
  313. avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {
  314. av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
  315. return -1;
  316. }
  317. if (!s->fixed_qscale &&
  318. avctx->bit_rate * av_q2d(avctx->time_base) >
  319. avctx->bit_rate_tolerance) {
  320. av_log(avctx, AV_LOG_ERROR,
  321. "bitrate tolerance too small for bitrate\n");
  322. return -1;
  323. }
  324. if (s->avctx->rc_max_rate &&
  325. s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  326. (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
  327. s->codec_id == AV_CODEC_ID_MPEG2VIDEO) &&
  328. 90000LL * (avctx->rc_buffer_size - 1) >
  329. s->avctx->rc_max_rate * 0xFFFFLL) {
  330. av_log(avctx, AV_LOG_INFO,
  331. "Warning vbv_delay will be set to 0xFFFF (=VBR) as the "
  332. "specified vbv buffer is too large for the given bitrate!\n");
  333. }
  334. if ((s->flags & CODEC_FLAG_4MV) && s->codec_id != AV_CODEC_ID_MPEG4 &&
  335. s->codec_id != AV_CODEC_ID_H263 && s->codec_id != AV_CODEC_ID_H263P &&
  336. s->codec_id != AV_CODEC_ID_FLV1) {
  337. av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
  338. return -1;
  339. }
  340. if (s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE) {
  341. av_log(avctx, AV_LOG_ERROR,
  342. "OBMC is only supported with simple mb decision\n");
  343. return -1;
  344. }
  345. if (s->quarter_sample && s->codec_id != AV_CODEC_ID_MPEG4) {
  346. av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
  347. return -1;
  348. }
  349. if (s->max_b_frames &&
  350. s->codec_id != AV_CODEC_ID_MPEG4 &&
  351. s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
  352. s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  353. av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
  354. return -1;
  355. }
  356. if ((s->codec_id == AV_CODEC_ID_MPEG4 ||
  357. s->codec_id == AV_CODEC_ID_H263 ||
  358. s->codec_id == AV_CODEC_ID_H263P) &&
  359. (avctx->sample_aspect_ratio.num > 255 ||
  360. avctx->sample_aspect_ratio.den > 255)) {
  361. av_log(avctx, AV_LOG_ERROR,
  362. "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",
  363. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  364. return -1;
  365. }
  366. if ((s->flags & (CODEC_FLAG_INTERLACED_DCT | CODEC_FLAG_INTERLACED_ME)) &&
  367. s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  368. av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
  369. return -1;
  370. }
  371. // FIXME mpeg2 uses that too
  372. if (s->mpeg_quant && s->codec_id != AV_CODEC_ID_MPEG4) {
  373. av_log(avctx, AV_LOG_ERROR,
  374. "mpeg2 style quantization not supported by codec\n");
  375. return -1;
  376. }
  377. if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {
  378. av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
  379. return -1;
  380. }
  381. if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&
  382. s->avctx->mb_decision != FF_MB_DECISION_RD) {
  383. av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
  384. return -1;
  385. }
  386. if (s->avctx->scenechange_threshold < 1000000000 &&
  387. (s->flags & CODEC_FLAG_CLOSED_GOP)) {
  388. av_log(avctx, AV_LOG_ERROR,
  389. "closed gop with scene change detection are not supported yet, "
  390. "set threshold to 1000000000\n");
  391. return -1;
  392. }
  393. if (s->flags & CODEC_FLAG_LOW_DELAY) {
  394. if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  395. av_log(avctx, AV_LOG_ERROR,
  396. "low delay forcing is only available for mpeg2\n");
  397. return -1;
  398. }
  399. if (s->max_b_frames != 0) {
  400. av_log(avctx, AV_LOG_ERROR,
  401. "b frames cannot be used with low delay\n");
  402. return -1;
  403. }
  404. }
  405. if (s->q_scale_type == 1) {
  406. if (avctx->qmax > 12) {
  407. av_log(avctx, AV_LOG_ERROR,
  408. "non linear quant only supports qmax <= 12 currently\n");
  409. return -1;
  410. }
  411. }
  412. if (s->avctx->thread_count > 1 &&
  413. s->codec_id != AV_CODEC_ID_MPEG4 &&
  414. s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
  415. s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&
  416. (s->codec_id != AV_CODEC_ID_H263P)) {
  417. av_log(avctx, AV_LOG_ERROR,
  418. "multi threaded encoding not supported by codec\n");
  419. return -1;
  420. }
  421. if (s->avctx->thread_count < 1) {
  422. av_log(avctx, AV_LOG_ERROR,
  423. "automatic thread number detection not supported by codec,"
  424. "patch welcome\n");
  425. return -1;
  426. }
  427. if (s->avctx->thread_count > 1)
  428. s->rtp_mode = 1;
  429. if (!avctx->time_base.den || !avctx->time_base.num) {
  430. av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
  431. return -1;
  432. }
  433. i = (INT_MAX / 2 + 128) >> 8;
  434. if (avctx->mb_threshold >= i) {
  435. av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n",
  436. i - 1);
  437. return -1;
  438. }
  439. if (avctx->b_frame_strategy && (avctx->flags & CODEC_FLAG_PASS2)) {
  440. av_log(avctx, AV_LOG_INFO,
  441. "notice: b_frame_strategy only affects the first pass\n");
  442. avctx->b_frame_strategy = 0;
  443. }
  444. i = av_gcd(avctx->time_base.den, avctx->time_base.num);
  445. if (i > 1) {
  446. av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
  447. avctx->time_base.den /= i;
  448. avctx->time_base.num /= i;
  449. //return -1;
  450. }
  451. if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
  452. s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG) {
  453. // (a + x * 3 / 8) / x
  454. s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);
  455. s->inter_quant_bias = 0;
  456. } else {
  457. s->intra_quant_bias = 0;
  458. // (a - x / 4) / x
  459. s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));
  460. }
  461. if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
  462. s->intra_quant_bias = avctx->intra_quant_bias;
  463. if (avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
  464. s->inter_quant_bias = avctx->inter_quant_bias;
  465. if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&
  466. s->avctx->time_base.den > (1 << 16) - 1) {
  467. av_log(avctx, AV_LOG_ERROR,
  468. "timebase %d/%d not supported by MPEG 4 standard, "
  469. "the maximum admitted value for the timebase denominator "
  470. "is %d\n", s->avctx->time_base.num, s->avctx->time_base.den,
  471. (1 << 16) - 1);
  472. return -1;
  473. }
  474. s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
  475. switch (avctx->codec->id) {
  476. case AV_CODEC_ID_MPEG1VIDEO:
  477. s->out_format = FMT_MPEG1;
  478. s->low_delay = !!(s->flags & CODEC_FLAG_LOW_DELAY);
  479. avctx->delay = s->low_delay ? 0 : (s->max_b_frames + 1);
  480. break;
  481. case AV_CODEC_ID_MPEG2VIDEO:
  482. s->out_format = FMT_MPEG1;
  483. s->low_delay = !!(s->flags & CODEC_FLAG_LOW_DELAY);
  484. avctx->delay = s->low_delay ? 0 : (s->max_b_frames + 1);
  485. s->rtp_mode = 1;
  486. break;
  487. case AV_CODEC_ID_MJPEG:
  488. s->out_format = FMT_MJPEG;
  489. s->intra_only = 1; /* force intra only for jpeg */
  490. if (!CONFIG_MJPEG_ENCODER ||
  491. ff_mjpeg_encode_init(s) < 0)
  492. return -1;
  493. avctx->delay = 0;
  494. s->low_delay = 1;
  495. break;
  496. case AV_CODEC_ID_H261:
  497. if (!CONFIG_H261_ENCODER)
  498. return -1;
  499. if (ff_h261_get_picture_format(s->width, s->height) < 0) {
  500. av_log(avctx, AV_LOG_ERROR,
  501. "The specified picture size of %dx%d is not valid for the "
  502. "H.261 codec.\nValid sizes are 176x144, 352x288\n",
  503. s->width, s->height);
  504. return -1;
  505. }
  506. s->out_format = FMT_H261;
  507. avctx->delay = 0;
  508. s->low_delay = 1;
  509. break;
  510. case AV_CODEC_ID_H263:
  511. if (!CONFIG_H263_ENCODER)
  512. return -1;
  513. if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),
  514. s->width, s->height) == 8) {
  515. av_log(avctx, AV_LOG_INFO,
  516. "The specified picture size of %dx%d is not valid for "
  517. "the H.263 codec.\nValid sizes are 128x96, 176x144, "
  518. "352x288, 704x576, and 1408x1152."
  519. "Try H.263+.\n", s->width, s->height);
  520. return -1;
  521. }
  522. s->out_format = FMT_H263;
  523. avctx->delay = 0;
  524. s->low_delay = 1;
  525. break;
  526. case AV_CODEC_ID_H263P:
  527. s->out_format = FMT_H263;
  528. s->h263_plus = 1;
  529. /* Fx */
  530. s->h263_aic = (avctx->flags & CODEC_FLAG_AC_PRED) ? 1 : 0;
  531. s->modified_quant = s->h263_aic;
  532. s->loop_filter = (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1 : 0;
  533. s->unrestricted_mv = s->obmc || s->loop_filter || s->umvplus;
  534. /* /Fx */
  535. /* These are just to be sure */
  536. avctx->delay = 0;
  537. s->low_delay = 1;
  538. break;
  539. case AV_CODEC_ID_FLV1:
  540. s->out_format = FMT_H263;
  541. s->h263_flv = 2; /* format = 1; 11-bit codes */
  542. s->unrestricted_mv = 1;
  543. s->rtp_mode = 0; /* don't allow GOB */
  544. avctx->delay = 0;
  545. s->low_delay = 1;
  546. break;
  547. case AV_CODEC_ID_RV10:
  548. s->out_format = FMT_H263;
  549. avctx->delay = 0;
  550. s->low_delay = 1;
  551. break;
  552. case AV_CODEC_ID_RV20:
  553. s->out_format = FMT_H263;
  554. avctx->delay = 0;
  555. s->low_delay = 1;
  556. s->modified_quant = 1;
  557. s->h263_aic = 1;
  558. s->h263_plus = 1;
  559. s->loop_filter = 1;
  560. s->unrestricted_mv = 0;
  561. break;
  562. case AV_CODEC_ID_MPEG4:
  563. s->out_format = FMT_H263;
  564. s->h263_pred = 1;
  565. s->unrestricted_mv = 1;
  566. s->low_delay = s->max_b_frames ? 0 : 1;
  567. avctx->delay = s->low_delay ? 0 : (s->max_b_frames + 1);
  568. break;
  569. case AV_CODEC_ID_MSMPEG4V2:
  570. s->out_format = FMT_H263;
  571. s->h263_pred = 1;
  572. s->unrestricted_mv = 1;
  573. s->msmpeg4_version = 2;
  574. avctx->delay = 0;
  575. s->low_delay = 1;
  576. break;
  577. case AV_CODEC_ID_MSMPEG4V3:
  578. s->out_format = FMT_H263;
  579. s->h263_pred = 1;
  580. s->unrestricted_mv = 1;
  581. s->msmpeg4_version = 3;
  582. s->flipflop_rounding = 1;
  583. avctx->delay = 0;
  584. s->low_delay = 1;
  585. break;
  586. case AV_CODEC_ID_WMV1:
  587. s->out_format = FMT_H263;
  588. s->h263_pred = 1;
  589. s->unrestricted_mv = 1;
  590. s->msmpeg4_version = 4;
  591. s->flipflop_rounding = 1;
  592. avctx->delay = 0;
  593. s->low_delay = 1;
  594. break;
  595. case AV_CODEC_ID_WMV2:
  596. s->out_format = FMT_H263;
  597. s->h263_pred = 1;
  598. s->unrestricted_mv = 1;
  599. s->msmpeg4_version = 5;
  600. s->flipflop_rounding = 1;
  601. avctx->delay = 0;
  602. s->low_delay = 1;
  603. break;
  604. default:
  605. return -1;
  606. }
  607. avctx->has_b_frames = !s->low_delay;
  608. s->encoding = 1;
  609. s->progressive_frame =
  610. s->progressive_sequence = !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT |
  611. CODEC_FLAG_INTERLACED_ME) ||
  612. s->alternate_scan);
  613. /* init */
  614. if (ff_MPV_common_init(s) < 0)
  615. return -1;
  616. if (ARCH_X86)
  617. ff_MPV_encode_init_x86(s);
  618. s->avctx->coded_frame = &s->current_picture.f;
  619. if (s->msmpeg4_version) {
  620. FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,
  621. 2 * 2 * (MAX_LEVEL + 1) *
  622. (MAX_RUN + 1) * 2 * sizeof(int), fail);
  623. }
  624. FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);
  625. FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix, 64 * 32 * sizeof(int), fail);
  626. FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix, 64 * 32 * sizeof(int), fail);
  627. FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
  628. FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
  629. FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,
  630. MAX_PICTURE_COUNT * sizeof(Picture *), fail);
  631. FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,
  632. MAX_PICTURE_COUNT * sizeof(Picture *), fail);
  633. if (s->avctx->noise_reduction) {
  634. FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,
  635. 2 * 64 * sizeof(uint16_t), fail);
  636. }
  637. ff_h263dsp_init(&s->h263dsp);
  638. if (!s->dct_quantize)
  639. s->dct_quantize = ff_dct_quantize_c;
  640. if (!s->denoise_dct)
  641. s->denoise_dct = denoise_dct_c;
  642. s->fast_dct_quantize = s->dct_quantize;
  643. if (avctx->trellis)
  644. s->dct_quantize = dct_quantize_trellis_c;
  645. if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
  646. s->chroma_qscale_table = ff_h263_chroma_qscale_table;
  647. s->quant_precision = 5;
  648. ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);
  649. ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);
  650. if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
  651. ff_h261_encode_init(s);
  652. if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  653. ff_h263_encode_init(s);
  654. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  655. ff_msmpeg4_encode_init(s);
  656. if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  657. && s->out_format == FMT_MPEG1)
  658. ff_mpeg1_encode_init(s);
  659. /* init q matrix */
  660. for (i = 0; i < 64; i++) {
  661. int j = s->dsp.idct_permutation[i];
  662. if (CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4 &&
  663. s->mpeg_quant) {
  664. s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
  665. s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
  666. } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
  667. s->intra_matrix[j] =
  668. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  669. } else {
  670. /* mpeg1/2 */
  671. s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
  672. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  673. }
  674. if (s->avctx->intra_matrix)
  675. s->intra_matrix[j] = s->avctx->intra_matrix[i];
  676. if (s->avctx->inter_matrix)
  677. s->inter_matrix[j] = s->avctx->inter_matrix[i];
  678. }
  679. /* precompute matrix */
  680. /* for mjpeg, we do include qscale in the matrix */
  681. if (s->out_format != FMT_MJPEG) {
  682. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  683. s->intra_matrix, s->intra_quant_bias, avctx->qmin,
  684. 31, 1);
  685. ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
  686. s->inter_matrix, s->inter_quant_bias, avctx->qmin,
  687. 31, 0);
  688. }
  689. if (ff_rate_control_init(s) < 0)
  690. return -1;
  691. #if FF_API_ERROR_RATE
  692. FF_DISABLE_DEPRECATION_WARNINGS
  693. if (avctx->error_rate)
  694. s->error_rate = avctx->error_rate;
  695. FF_ENABLE_DEPRECATION_WARNINGS;
  696. #endif
  697. if (avctx->b_frame_strategy == 2) {
  698. for (i = 0; i < s->max_b_frames + 2; i++) {
  699. s->tmp_frames[i] = av_frame_alloc();
  700. if (!s->tmp_frames[i])
  701. return AVERROR(ENOMEM);
  702. s->tmp_frames[i]->format = AV_PIX_FMT_YUV420P;
  703. s->tmp_frames[i]->width = s->width >> avctx->brd_scale;
  704. s->tmp_frames[i]->height = s->height >> avctx->brd_scale;
  705. ret = av_frame_get_buffer(s->tmp_frames[i], 32);
  706. if (ret < 0)
  707. return ret;
  708. }
  709. }
  710. return 0;
  711. fail:
  712. ff_MPV_encode_end(avctx);
  713. return AVERROR_UNKNOWN;
  714. }
  715. av_cold int ff_MPV_encode_end(AVCodecContext *avctx)
  716. {
  717. MpegEncContext *s = avctx->priv_data;
  718. int i;
  719. ff_rate_control_uninit(s);
  720. ff_MPV_common_end(s);
  721. if (CONFIG_MJPEG_ENCODER &&
  722. s->out_format == FMT_MJPEG)
  723. ff_mjpeg_encode_close(s);
  724. av_freep(&avctx->extradata);
  725. for (i = 0; i < FF_ARRAY_ELEMS(s->tmp_frames); i++)
  726. av_frame_free(&s->tmp_frames[i]);
  727. ff_free_picture_tables(&s->new_picture);
  728. ff_mpeg_unref_picture(s, &s->new_picture);
  729. av_freep(&s->avctx->stats_out);
  730. av_freep(&s->ac_stats);
  731. av_freep(&s->q_intra_matrix);
  732. av_freep(&s->q_inter_matrix);
  733. av_freep(&s->q_intra_matrix16);
  734. av_freep(&s->q_inter_matrix16);
  735. av_freep(&s->input_picture);
  736. av_freep(&s->reordered_input_picture);
  737. av_freep(&s->dct_offset);
  738. return 0;
  739. }
  740. static int get_sae(uint8_t *src, int ref, int stride)
  741. {
  742. int x,y;
  743. int acc = 0;
  744. for (y = 0; y < 16; y++) {
  745. for (x = 0; x < 16; x++) {
  746. acc += FFABS(src[x + y * stride] - ref);
  747. }
  748. }
  749. return acc;
  750. }
  751. static int get_intra_count(MpegEncContext *s, uint8_t *src,
  752. uint8_t *ref, int stride)
  753. {
  754. int x, y, w, h;
  755. int acc = 0;
  756. w = s->width & ~15;
  757. h = s->height & ~15;
  758. for (y = 0; y < h; y += 16) {
  759. for (x = 0; x < w; x += 16) {
  760. int offset = x + y * stride;
  761. int sad = s->dsp.sad[0](NULL, src + offset, ref + offset, stride,
  762. 16);
  763. int mean = (s->dsp.pix_sum(src + offset, stride) + 128) >> 8;
  764. int sae = get_sae(src + offset, mean, stride);
  765. acc += sae + 500 < sad;
  766. }
  767. }
  768. return acc;
  769. }
  770. static int load_input_picture(MpegEncContext *s, const AVFrame *pic_arg)
  771. {
  772. Picture *pic = NULL;
  773. int64_t pts;
  774. int i, display_picture_number = 0, ret;
  775. const int encoding_delay = s->max_b_frames ? s->max_b_frames :
  776. (s->low_delay ? 0 : 1);
  777. int direct = 1;
  778. if (pic_arg) {
  779. pts = pic_arg->pts;
  780. display_picture_number = s->input_picture_number++;
  781. if (pts != AV_NOPTS_VALUE) {
  782. if (s->user_specified_pts != AV_NOPTS_VALUE) {
  783. int64_t time = pts;
  784. int64_t last = s->user_specified_pts;
  785. if (time <= last) {
  786. av_log(s->avctx, AV_LOG_ERROR,
  787. "Error, Invalid timestamp=%"PRId64", "
  788. "last=%"PRId64"\n", pts, s->user_specified_pts);
  789. return -1;
  790. }
  791. if (!s->low_delay && display_picture_number == 1)
  792. s->dts_delta = time - last;
  793. }
  794. s->user_specified_pts = pts;
  795. } else {
  796. if (s->user_specified_pts != AV_NOPTS_VALUE) {
  797. s->user_specified_pts =
  798. pts = s->user_specified_pts + 1;
  799. av_log(s->avctx, AV_LOG_INFO,
  800. "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n",
  801. pts);
  802. } else {
  803. pts = display_picture_number;
  804. }
  805. }
  806. }
  807. if (pic_arg) {
  808. if (!pic_arg->buf[0]);
  809. direct = 0;
  810. if (pic_arg->linesize[0] != s->linesize)
  811. direct = 0;
  812. if (pic_arg->linesize[1] != s->uvlinesize)
  813. direct = 0;
  814. if (pic_arg->linesize[2] != s->uvlinesize)
  815. direct = 0;
  816. av_dlog(s->avctx, "%d %d %td %td\n", pic_arg->linesize[0],
  817. pic_arg->linesize[1], s->linesize, s->uvlinesize);
  818. if (direct) {
  819. i = ff_find_unused_picture(s, 1);
  820. if (i < 0)
  821. return i;
  822. pic = &s->picture[i];
  823. pic->reference = 3;
  824. if ((ret = av_frame_ref(&pic->f, pic_arg)) < 0)
  825. return ret;
  826. if (ff_alloc_picture(s, pic, 1) < 0) {
  827. return -1;
  828. }
  829. } else {
  830. i = ff_find_unused_picture(s, 0);
  831. if (i < 0)
  832. return i;
  833. pic = &s->picture[i];
  834. pic->reference = 3;
  835. if (ff_alloc_picture(s, pic, 0) < 0) {
  836. return -1;
  837. }
  838. if (pic->f.data[0] + INPLACE_OFFSET == pic_arg->data[0] &&
  839. pic->f.data[1] + INPLACE_OFFSET == pic_arg->data[1] &&
  840. pic->f.data[2] + INPLACE_OFFSET == pic_arg->data[2]) {
  841. // empty
  842. } else {
  843. int h_chroma_shift, v_chroma_shift;
  844. av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
  845. &h_chroma_shift,
  846. &v_chroma_shift);
  847. for (i = 0; i < 3; i++) {
  848. int src_stride = pic_arg->linesize[i];
  849. int dst_stride = i ? s->uvlinesize : s->linesize;
  850. int h_shift = i ? h_chroma_shift : 0;
  851. int v_shift = i ? v_chroma_shift : 0;
  852. int w = s->width >> h_shift;
  853. int h = s->height >> v_shift;
  854. uint8_t *src = pic_arg->data[i];
  855. uint8_t *dst = pic->f.data[i];
  856. if (!s->avctx->rc_buffer_size)
  857. dst += INPLACE_OFFSET;
  858. if (src_stride == dst_stride)
  859. memcpy(dst, src, src_stride * h);
  860. else {
  861. while (h--) {
  862. memcpy(dst, src, w);
  863. dst += dst_stride;
  864. src += src_stride;
  865. }
  866. }
  867. }
  868. }
  869. }
  870. ret = av_frame_copy_props(&pic->f, pic_arg);
  871. if (ret < 0)
  872. return ret;
  873. pic->f.display_picture_number = display_picture_number;
  874. pic->f.pts = pts; // we set this here to avoid modifiying pic_arg
  875. }
  876. /* shift buffer entries */
  877. for (i = 1; i < MAX_PICTURE_COUNT /*s->encoding_delay + 1*/; i++)
  878. s->input_picture[i - 1] = s->input_picture[i];
  879. s->input_picture[encoding_delay] = (Picture*) pic;
  880. return 0;
  881. }
  882. static int skip_check(MpegEncContext *s, Picture *p, Picture *ref)
  883. {
  884. int x, y, plane;
  885. int score = 0;
  886. int64_t score64 = 0;
  887. for (plane = 0; plane < 3; plane++) {
  888. const int stride = p->f.linesize[plane];
  889. const int bw = plane ? 1 : 2;
  890. for (y = 0; y < s->mb_height * bw; y++) {
  891. for (x = 0; x < s->mb_width * bw; x++) {
  892. int off = p->shared ? 0 : 16;
  893. uint8_t *dptr = p->f.data[plane] + 8 * (x + y * stride) + off;
  894. uint8_t *rptr = ref->f.data[plane] + 8 * (x + y * stride);
  895. int v = s->dsp.frame_skip_cmp[1](s, dptr, rptr, stride, 8);
  896. switch (s->avctx->frame_skip_exp) {
  897. case 0: score = FFMAX(score, v); break;
  898. case 1: score += FFABS(v); break;
  899. case 2: score += v * v; break;
  900. case 3: score64 += FFABS(v * v * (int64_t)v); break;
  901. case 4: score64 += v * v * (int64_t)(v * v); break;
  902. }
  903. }
  904. }
  905. }
  906. if (score)
  907. score64 = score;
  908. if (score64 < s->avctx->frame_skip_threshold)
  909. return 1;
  910. if (score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda) >> 8))
  911. return 1;
  912. return 0;
  913. }
  914. static int encode_frame(AVCodecContext *c, AVFrame *frame)
  915. {
  916. AVPacket pkt = { 0 };
  917. int ret, got_output;
  918. av_init_packet(&pkt);
  919. ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  920. if (ret < 0)
  921. return ret;
  922. ret = pkt.size;
  923. av_free_packet(&pkt);
  924. return ret;
  925. }
  926. static int estimate_best_b_count(MpegEncContext *s)
  927. {
  928. AVCodec *codec = avcodec_find_encoder(s->avctx->codec_id);
  929. AVCodecContext *c = avcodec_alloc_context3(NULL);
  930. const int scale = s->avctx->brd_scale;
  931. int i, j, out_size, p_lambda, b_lambda, lambda2;
  932. int64_t best_rd = INT64_MAX;
  933. int best_b_count = -1;
  934. assert(scale >= 0 && scale <= 3);
  935. //emms_c();
  936. //s->next_picture_ptr->quality;
  937. p_lambda = s->last_lambda_for[AV_PICTURE_TYPE_P];
  938. //p_lambda * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  939. b_lambda = s->last_lambda_for[AV_PICTURE_TYPE_B];
  940. if (!b_lambda) // FIXME we should do this somewhere else
  941. b_lambda = p_lambda;
  942. lambda2 = (b_lambda * b_lambda + (1 << FF_LAMBDA_SHIFT) / 2) >>
  943. FF_LAMBDA_SHIFT;
  944. c->width = s->width >> scale;
  945. c->height = s->height >> scale;
  946. c->flags = CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR |
  947. CODEC_FLAG_INPUT_PRESERVED;
  948. c->flags |= s->avctx->flags & CODEC_FLAG_QPEL;
  949. c->mb_decision = s->avctx->mb_decision;
  950. c->me_cmp = s->avctx->me_cmp;
  951. c->mb_cmp = s->avctx->mb_cmp;
  952. c->me_sub_cmp = s->avctx->me_sub_cmp;
  953. c->pix_fmt = AV_PIX_FMT_YUV420P;
  954. c->time_base = s->avctx->time_base;
  955. c->max_b_frames = s->max_b_frames;
  956. if (avcodec_open2(c, codec, NULL) < 0)
  957. return -1;
  958. for (i = 0; i < s->max_b_frames + 2; i++) {
  959. Picture pre_input, *pre_input_ptr = i ? s->input_picture[i - 1] :
  960. s->next_picture_ptr;
  961. if (pre_input_ptr && (!i || s->input_picture[i - 1])) {
  962. pre_input = *pre_input_ptr;
  963. if (!pre_input.shared && i) {
  964. pre_input.f.data[0] += INPLACE_OFFSET;
  965. pre_input.f.data[1] += INPLACE_OFFSET;
  966. pre_input.f.data[2] += INPLACE_OFFSET;
  967. }
  968. s->dsp.shrink[scale](s->tmp_frames[i]->data[0], s->tmp_frames[i]->linesize[0],
  969. pre_input.f.data[0], pre_input.f.linesize[0],
  970. c->width, c->height);
  971. s->dsp.shrink[scale](s->tmp_frames[i]->data[1], s->tmp_frames[i]->linesize[1],
  972. pre_input.f.data[1], pre_input.f.linesize[1],
  973. c->width >> 1, c->height >> 1);
  974. s->dsp.shrink[scale](s->tmp_frames[i]->data[2], s->tmp_frames[i]->linesize[2],
  975. pre_input.f.data[2], pre_input.f.linesize[2],
  976. c->width >> 1, c->height >> 1);
  977. }
  978. }
  979. for (j = 0; j < s->max_b_frames + 1; j++) {
  980. int64_t rd = 0;
  981. if (!s->input_picture[j])
  982. break;
  983. c->error[0] = c->error[1] = c->error[2] = 0;
  984. s->tmp_frames[0]->pict_type = AV_PICTURE_TYPE_I;
  985. s->tmp_frames[0]->quality = 1 * FF_QP2LAMBDA;
  986. out_size = encode_frame(c, s->tmp_frames[0]);
  987. //rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  988. for (i = 0; i < s->max_b_frames + 1; i++) {
  989. int is_p = i % (j + 1) == j || i == s->max_b_frames;
  990. s->tmp_frames[i + 1]->pict_type = is_p ?
  991. AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
  992. s->tmp_frames[i + 1]->quality = is_p ? p_lambda : b_lambda;
  993. out_size = encode_frame(c, s->tmp_frames[i + 1]);
  994. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  995. }
  996. /* get the delayed frames */
  997. while (out_size) {
  998. out_size = encode_frame(c, NULL);
  999. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  1000. }
  1001. rd += c->error[0] + c->error[1] + c->error[2];
  1002. if (rd < best_rd) {
  1003. best_rd = rd;
  1004. best_b_count = j;
  1005. }
  1006. }
  1007. avcodec_close(c);
  1008. av_freep(&c);
  1009. return best_b_count;
  1010. }
  1011. static int select_input_picture(MpegEncContext *s)
  1012. {
  1013. int i, ret;
  1014. for (i = 1; i < MAX_PICTURE_COUNT; i++)
  1015. s->reordered_input_picture[i - 1] = s->reordered_input_picture[i];
  1016. s->reordered_input_picture[MAX_PICTURE_COUNT - 1] = NULL;
  1017. /* set next picture type & ordering */
  1018. if (s->reordered_input_picture[0] == NULL && s->input_picture[0]) {
  1019. if (/*s->picture_in_gop_number >= s->gop_size ||*/
  1020. s->next_picture_ptr == NULL || s->intra_only) {
  1021. s->reordered_input_picture[0] = s->input_picture[0];
  1022. s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_I;
  1023. s->reordered_input_picture[0]->f.coded_picture_number =
  1024. s->coded_picture_number++;
  1025. } else {
  1026. int b_frames;
  1027. if (s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor) {
  1028. if (s->picture_in_gop_number < s->gop_size &&
  1029. skip_check(s, s->input_picture[0], s->next_picture_ptr)) {
  1030. // FIXME check that te gop check above is +-1 correct
  1031. av_frame_unref(&s->input_picture[0]->f);
  1032. emms_c();
  1033. ff_vbv_update(s, 0);
  1034. goto no_output_pic;
  1035. }
  1036. }
  1037. if (s->flags & CODEC_FLAG_PASS2) {
  1038. for (i = 0; i < s->max_b_frames + 1; i++) {
  1039. int pict_num = s->input_picture[0]->f.display_picture_number + i;
  1040. if (pict_num >= s->rc_context.num_entries)
  1041. break;
  1042. if (!s->input_picture[i]) {
  1043. s->rc_context.entry[pict_num - 1].new_pict_type = AV_PICTURE_TYPE_P;
  1044. break;
  1045. }
  1046. s->input_picture[i]->f.pict_type =
  1047. s->rc_context.entry[pict_num].new_pict_type;
  1048. }
  1049. }
  1050. if (s->avctx->b_frame_strategy == 0) {
  1051. b_frames = s->max_b_frames;
  1052. while (b_frames && !s->input_picture[b_frames])
  1053. b_frames--;
  1054. } else if (s->avctx->b_frame_strategy == 1) {
  1055. for (i = 1; i < s->max_b_frames + 1; i++) {
  1056. if (s->input_picture[i] &&
  1057. s->input_picture[i]->b_frame_score == 0) {
  1058. s->input_picture[i]->b_frame_score =
  1059. get_intra_count(s,
  1060. s->input_picture[i ]->f.data[0],
  1061. s->input_picture[i - 1]->f.data[0],
  1062. s->linesize) + 1;
  1063. }
  1064. }
  1065. for (i = 0; i < s->max_b_frames + 1; i++) {
  1066. if (s->input_picture[i] == NULL ||
  1067. s->input_picture[i]->b_frame_score - 1 >
  1068. s->mb_num / s->avctx->b_sensitivity)
  1069. break;
  1070. }
  1071. b_frames = FFMAX(0, i - 1);
  1072. /* reset scores */
  1073. for (i = 0; i < b_frames + 1; i++) {
  1074. s->input_picture[i]->b_frame_score = 0;
  1075. }
  1076. } else if (s->avctx->b_frame_strategy == 2) {
  1077. b_frames = estimate_best_b_count(s);
  1078. } else {
  1079. av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  1080. b_frames = 0;
  1081. }
  1082. emms_c();
  1083. for (i = b_frames - 1; i >= 0; i--) {
  1084. int type = s->input_picture[i]->f.pict_type;
  1085. if (type && type != AV_PICTURE_TYPE_B)
  1086. b_frames = i;
  1087. }
  1088. if (s->input_picture[b_frames]->f.pict_type == AV_PICTURE_TYPE_B &&
  1089. b_frames == s->max_b_frames) {
  1090. av_log(s->avctx, AV_LOG_ERROR,
  1091. "warning, too many b frames in a row\n");
  1092. }
  1093. if (s->picture_in_gop_number + b_frames >= s->gop_size) {
  1094. if ((s->mpv_flags & FF_MPV_FLAG_STRICT_GOP) &&
  1095. s->gop_size > s->picture_in_gop_number) {
  1096. b_frames = s->gop_size - s->picture_in_gop_number - 1;
  1097. } else {
  1098. if (s->flags & CODEC_FLAG_CLOSED_GOP)
  1099. b_frames = 0;
  1100. s->input_picture[b_frames]->f.pict_type = AV_PICTURE_TYPE_I;
  1101. }
  1102. }
  1103. if ((s->flags & CODEC_FLAG_CLOSED_GOP) && b_frames &&
  1104. s->input_picture[b_frames]->f.pict_type == AV_PICTURE_TYPE_I)
  1105. b_frames--;
  1106. s->reordered_input_picture[0] = s->input_picture[b_frames];
  1107. if (s->reordered_input_picture[0]->f.pict_type != AV_PICTURE_TYPE_I)
  1108. s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_P;
  1109. s->reordered_input_picture[0]->f.coded_picture_number =
  1110. s->coded_picture_number++;
  1111. for (i = 0; i < b_frames; i++) {
  1112. s->reordered_input_picture[i + 1] = s->input_picture[i];
  1113. s->reordered_input_picture[i + 1]->f.pict_type =
  1114. AV_PICTURE_TYPE_B;
  1115. s->reordered_input_picture[i + 1]->f.coded_picture_number =
  1116. s->coded_picture_number++;
  1117. }
  1118. }
  1119. }
  1120. no_output_pic:
  1121. if (s->reordered_input_picture[0]) {
  1122. s->reordered_input_picture[0]->reference =
  1123. s->reordered_input_picture[0]->f.pict_type !=
  1124. AV_PICTURE_TYPE_B ? 3 : 0;
  1125. ff_mpeg_unref_picture(s, &s->new_picture);
  1126. if ((ret = ff_mpeg_ref_picture(s, &s->new_picture, s->reordered_input_picture[0])))
  1127. return ret;
  1128. if (s->reordered_input_picture[0]->shared || s->avctx->rc_buffer_size) {
  1129. // input is a shared pix, so we can't modifiy it -> alloc a new
  1130. // one & ensure that the shared one is reuseable
  1131. Picture *pic;
  1132. int i = ff_find_unused_picture(s, 0);
  1133. if (i < 0)
  1134. return i;
  1135. pic = &s->picture[i];
  1136. pic->reference = s->reordered_input_picture[0]->reference;
  1137. if (ff_alloc_picture(s, pic, 0) < 0) {
  1138. return -1;
  1139. }
  1140. ret = av_frame_copy_props(&pic->f, &s->reordered_input_picture[0]->f);
  1141. if (ret < 0)
  1142. return ret;
  1143. /* mark us unused / free shared pic */
  1144. av_frame_unref(&s->reordered_input_picture[0]->f);
  1145. s->reordered_input_picture[0]->shared = 0;
  1146. s->current_picture_ptr = pic;
  1147. } else {
  1148. // input is not a shared pix -> reuse buffer for current_pix
  1149. s->current_picture_ptr = s->reordered_input_picture[0];
  1150. for (i = 0; i < 4; i++) {
  1151. s->new_picture.f.data[i] += INPLACE_OFFSET;
  1152. }
  1153. }
  1154. ff_mpeg_unref_picture(s, &s->current_picture);
  1155. if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,
  1156. s->current_picture_ptr)) < 0)
  1157. return ret;
  1158. s->picture_number = s->new_picture.f.display_picture_number;
  1159. } else {
  1160. ff_mpeg_unref_picture(s, &s->new_picture);
  1161. }
  1162. return 0;
  1163. }
  1164. static void frame_end(MpegEncContext *s)
  1165. {
  1166. int i;
  1167. if (s->unrestricted_mv &&
  1168. s->current_picture.reference &&
  1169. !s->intra_only) {
  1170. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  1171. int hshift = desc->log2_chroma_w;
  1172. int vshift = desc->log2_chroma_h;
  1173. s->dsp.draw_edges(s->current_picture.f.data[0], s->linesize,
  1174. s->h_edge_pos, s->v_edge_pos,
  1175. EDGE_WIDTH, EDGE_WIDTH,
  1176. EDGE_TOP | EDGE_BOTTOM);
  1177. s->dsp.draw_edges(s->current_picture.f.data[1], s->uvlinesize,
  1178. s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,
  1179. EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
  1180. EDGE_TOP | EDGE_BOTTOM);
  1181. s->dsp.draw_edges(s->current_picture.f.data[2], s->uvlinesize,
  1182. s->h_edge_pos >> hshift, s->v_edge_pos >> vshift,
  1183. EDGE_WIDTH >> hshift, EDGE_WIDTH >> vshift,
  1184. EDGE_TOP | EDGE_BOTTOM);
  1185. }
  1186. emms_c();
  1187. s->last_pict_type = s->pict_type;
  1188. s->last_lambda_for [s->pict_type] = s->current_picture_ptr->f.quality;
  1189. if (s->pict_type!= AV_PICTURE_TYPE_B)
  1190. s->last_non_b_pict_type = s->pict_type;
  1191. if (s->encoding) {
  1192. /* release non-reference frames */
  1193. for (i = 0; i < MAX_PICTURE_COUNT; i++) {
  1194. if (!s->picture[i].reference)
  1195. ff_mpeg_unref_picture(s, &s->picture[i]);
  1196. }
  1197. }
  1198. s->avctx->coded_frame = &s->current_picture_ptr->f;
  1199. }
  1200. static void update_noise_reduction(MpegEncContext *s)
  1201. {
  1202. int intra, i;
  1203. for (intra = 0; intra < 2; intra++) {
  1204. if (s->dct_count[intra] > (1 << 16)) {
  1205. for (i = 0; i < 64; i++) {
  1206. s->dct_error_sum[intra][i] >>= 1;
  1207. }
  1208. s->dct_count[intra] >>= 1;
  1209. }
  1210. for (i = 0; i < 64; i++) {
  1211. s->dct_offset[intra][i] = (s->avctx->noise_reduction *
  1212. s->dct_count[intra] +
  1213. s->dct_error_sum[intra][i] / 2) /
  1214. (s->dct_error_sum[intra][i] + 1);
  1215. }
  1216. }
  1217. }
  1218. static int frame_start(MpegEncContext *s)
  1219. {
  1220. int ret;
  1221. /* mark & release old frames */
  1222. if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
  1223. s->last_picture_ptr != s->next_picture_ptr &&
  1224. s->last_picture_ptr->f.buf[0]) {
  1225. ff_mpeg_unref_picture(s, s->last_picture_ptr);
  1226. }
  1227. s->current_picture_ptr->f.pict_type = s->pict_type;
  1228. s->current_picture_ptr->f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
  1229. ff_mpeg_unref_picture(s, &s->current_picture);
  1230. if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,
  1231. s->current_picture_ptr)) < 0)
  1232. return ret;
  1233. if (s->pict_type != AV_PICTURE_TYPE_B) {
  1234. s->last_picture_ptr = s->next_picture_ptr;
  1235. if (!s->droppable)
  1236. s->next_picture_ptr = s->current_picture_ptr;
  1237. }
  1238. if (s->last_picture_ptr) {
  1239. ff_mpeg_unref_picture(s, &s->last_picture);
  1240. if (s->last_picture_ptr->f.buf[0] &&
  1241. (ret = ff_mpeg_ref_picture(s, &s->last_picture,
  1242. s->last_picture_ptr)) < 0)
  1243. return ret;
  1244. }
  1245. if (s->next_picture_ptr) {
  1246. ff_mpeg_unref_picture(s, &s->next_picture);
  1247. if (s->next_picture_ptr->f.buf[0] &&
  1248. (ret = ff_mpeg_ref_picture(s, &s->next_picture,
  1249. s->next_picture_ptr)) < 0)
  1250. return ret;
  1251. }
  1252. if (s->picture_structure!= PICT_FRAME) {
  1253. int i;
  1254. for (i = 0; i < 4; i++) {
  1255. if (s->picture_structure == PICT_BOTTOM_FIELD) {
  1256. s->current_picture.f.data[i] +=
  1257. s->current_picture.f.linesize[i];
  1258. }
  1259. s->current_picture.f.linesize[i] *= 2;
  1260. s->last_picture.f.linesize[i] *= 2;
  1261. s->next_picture.f.linesize[i] *= 2;
  1262. }
  1263. }
  1264. if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  1265. s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
  1266. s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
  1267. } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
  1268. s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
  1269. s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
  1270. } else {
  1271. s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
  1272. s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
  1273. }
  1274. if (s->dct_error_sum) {
  1275. assert(s->avctx->noise_reduction && s->encoding);
  1276. update_noise_reduction(s);
  1277. }
  1278. return 0;
  1279. }
  1280. int ff_MPV_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
  1281. const AVFrame *pic_arg, int *got_packet)
  1282. {
  1283. MpegEncContext *s = avctx->priv_data;
  1284. int i, stuffing_count, ret;
  1285. int context_count = s->slice_context_count;
  1286. s->picture_in_gop_number++;
  1287. if (load_input_picture(s, pic_arg) < 0)
  1288. return -1;
  1289. if (select_input_picture(s) < 0) {
  1290. return -1;
  1291. }
  1292. /* output? */
  1293. if (s->new_picture.f.data[0]) {
  1294. if (!pkt->data &&
  1295. (ret = ff_alloc_packet(pkt, s->mb_width*s->mb_height*MAX_MB_BYTES)) < 0)
  1296. return ret;
  1297. if (s->mb_info) {
  1298. s->mb_info_ptr = av_packet_new_side_data(pkt,
  1299. AV_PKT_DATA_H263_MB_INFO,
  1300. s->mb_width*s->mb_height*12);
  1301. s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;
  1302. }
  1303. for (i = 0; i < context_count; i++) {
  1304. int start_y = s->thread_context[i]->start_mb_y;
  1305. int end_y = s->thread_context[i]-> end_mb_y;
  1306. int h = s->mb_height;
  1307. uint8_t *start = pkt->data + (size_t)(((int64_t) pkt->size) * start_y / h);
  1308. uint8_t *end = pkt->data + (size_t)(((int64_t) pkt->size) * end_y / h);
  1309. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1310. }
  1311. s->pict_type = s->new_picture.f.pict_type;
  1312. //emms_c();
  1313. ret = frame_start(s);
  1314. if (ret < 0)
  1315. return ret;
  1316. vbv_retry:
  1317. if (encode_picture(s, s->picture_number) < 0)
  1318. return -1;
  1319. avctx->header_bits = s->header_bits;
  1320. avctx->mv_bits = s->mv_bits;
  1321. avctx->misc_bits = s->misc_bits;
  1322. avctx->i_tex_bits = s->i_tex_bits;
  1323. avctx->p_tex_bits = s->p_tex_bits;
  1324. avctx->i_count = s->i_count;
  1325. // FIXME f/b_count in avctx
  1326. avctx->p_count = s->mb_num - s->i_count - s->skip_count;
  1327. avctx->skip_count = s->skip_count;
  1328. frame_end(s);
  1329. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1330. ff_mjpeg_encode_picture_trailer(&s->pb, s->header_bits);
  1331. if (avctx->rc_buffer_size) {
  1332. RateControlContext *rcc = &s->rc_context;
  1333. int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1334. if (put_bits_count(&s->pb) > max_size &&
  1335. s->lambda < s->avctx->lmax) {
  1336. s->next_lambda = FFMAX(s->lambda + 1, s->lambda *
  1337. (s->qscale + 1) / s->qscale);
  1338. if (s->adaptive_quant) {
  1339. int i;
  1340. for (i = 0; i < s->mb_height * s->mb_stride; i++)
  1341. s->lambda_table[i] =
  1342. FFMAX(s->lambda_table[i] + 1,
  1343. s->lambda_table[i] * (s->qscale + 1) /
  1344. s->qscale);
  1345. }
  1346. s->mb_skipped = 0; // done in frame_start()
  1347. // done in encode_picture() so we must undo it
  1348. if (s->pict_type == AV_PICTURE_TYPE_P) {
  1349. if (s->flipflop_rounding ||
  1350. s->codec_id == AV_CODEC_ID_H263P ||
  1351. s->codec_id == AV_CODEC_ID_MPEG4)
  1352. s->no_rounding ^= 1;
  1353. }
  1354. if (s->pict_type != AV_PICTURE_TYPE_B) {
  1355. s->time_base = s->last_time_base;
  1356. s->last_non_b_time = s->time - s->pp_time;
  1357. }
  1358. for (i = 0; i < context_count; i++) {
  1359. PutBitContext *pb = &s->thread_context[i]->pb;
  1360. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1361. }
  1362. goto vbv_retry;
  1363. }
  1364. assert(s->avctx->rc_max_rate);
  1365. }
  1366. if (s->flags & CODEC_FLAG_PASS1)
  1367. ff_write_pass1_stats(s);
  1368. for (i = 0; i < 4; i++) {
  1369. s->current_picture_ptr->f.error[i] = s->current_picture.f.error[i];
  1370. avctx->error[i] += s->current_picture_ptr->f.error[i];
  1371. }
  1372. if (s->flags & CODEC_FLAG_PASS1)
  1373. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits +
  1374. avctx->i_tex_bits + avctx->p_tex_bits ==
  1375. put_bits_count(&s->pb));
  1376. flush_put_bits(&s->pb);
  1377. s->frame_bits = put_bits_count(&s->pb);
  1378. stuffing_count = ff_vbv_update(s, s->frame_bits);
  1379. if (stuffing_count) {
  1380. if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
  1381. stuffing_count + 50) {
  1382. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1383. return -1;
  1384. }
  1385. switch (s->codec_id) {
  1386. case AV_CODEC_ID_MPEG1VIDEO:
  1387. case AV_CODEC_ID_MPEG2VIDEO:
  1388. while (stuffing_count--) {
  1389. put_bits(&s->pb, 8, 0);
  1390. }
  1391. break;
  1392. case AV_CODEC_ID_MPEG4:
  1393. put_bits(&s->pb, 16, 0);
  1394. put_bits(&s->pb, 16, 0x1C3);
  1395. stuffing_count -= 4;
  1396. while (stuffing_count--) {
  1397. put_bits(&s->pb, 8, 0xFF);
  1398. }
  1399. break;
  1400. default:
  1401. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1402. }
  1403. flush_put_bits(&s->pb);
  1404. s->frame_bits = put_bits_count(&s->pb);
  1405. }
  1406. /* update mpeg1/2 vbv_delay for CBR */
  1407. if (s->avctx->rc_max_rate &&
  1408. s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  1409. s->out_format == FMT_MPEG1 &&
  1410. 90000LL * (avctx->rc_buffer_size - 1) <=
  1411. s->avctx->rc_max_rate * 0xFFFFLL) {
  1412. int vbv_delay, min_delay;
  1413. double inbits = s->avctx->rc_max_rate *
  1414. av_q2d(s->avctx->time_base);
  1415. int minbits = s->frame_bits - 8 *
  1416. (s->vbv_delay_ptr - s->pb.buf - 1);
  1417. double bits = s->rc_context.buffer_index + minbits - inbits;
  1418. if (bits < 0)
  1419. av_log(s->avctx, AV_LOG_ERROR,
  1420. "Internal error, negative bits\n");
  1421. assert(s->repeat_first_field == 0);
  1422. vbv_delay = bits * 90000 / s->avctx->rc_max_rate;
  1423. min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /
  1424. s->avctx->rc_max_rate;
  1425. vbv_delay = FFMAX(vbv_delay, min_delay);
  1426. assert(vbv_delay < 0xFFFF);
  1427. s->vbv_delay_ptr[0] &= 0xF8;
  1428. s->vbv_delay_ptr[0] |= vbv_delay >> 13;
  1429. s->vbv_delay_ptr[1] = vbv_delay >> 5;
  1430. s->vbv_delay_ptr[2] &= 0x07;
  1431. s->vbv_delay_ptr[2] |= vbv_delay << 3;
  1432. avctx->vbv_delay = vbv_delay * 300;
  1433. }
  1434. s->total_bits += s->frame_bits;
  1435. avctx->frame_bits = s->frame_bits;
  1436. pkt->pts = s->current_picture.f.pts;
  1437. if (!s->low_delay) {
  1438. if (!s->current_picture.f.coded_picture_number)
  1439. pkt->dts = pkt->pts - s->dts_delta;
  1440. else
  1441. pkt->dts = s->reordered_pts;
  1442. s->reordered_pts = s->input_picture[0]->f.pts;
  1443. } else
  1444. pkt->dts = pkt->pts;
  1445. if (s->current_picture.f.key_frame)
  1446. pkt->flags |= AV_PKT_FLAG_KEY;
  1447. if (s->mb_info)
  1448. av_packet_shrink_side_data(pkt, AV_PKT_DATA_H263_MB_INFO, s->mb_info_size);
  1449. } else {
  1450. s->frame_bits = 0;
  1451. }
  1452. assert((s->frame_bits & 7) == 0);
  1453. pkt->size = s->frame_bits / 8;
  1454. *got_packet = !!pkt->size;
  1455. return 0;
  1456. }
  1457. static inline void dct_single_coeff_elimination(MpegEncContext *s,
  1458. int n, int threshold)
  1459. {
  1460. static const char tab[64] = {
  1461. 3, 2, 2, 1, 1, 1, 1, 1,
  1462. 1, 1, 1, 1, 1, 1, 1, 1,
  1463. 1, 1, 1, 1, 1, 1, 1, 1,
  1464. 0, 0, 0, 0, 0, 0, 0, 0,
  1465. 0, 0, 0, 0, 0, 0, 0, 0,
  1466. 0, 0, 0, 0, 0, 0, 0, 0,
  1467. 0, 0, 0, 0, 0, 0, 0, 0,
  1468. 0, 0, 0, 0, 0, 0, 0, 0
  1469. };
  1470. int score = 0;
  1471. int run = 0;
  1472. int i;
  1473. int16_t *block = s->block[n];
  1474. const int last_index = s->block_last_index[n];
  1475. int skip_dc;
  1476. if (threshold < 0) {
  1477. skip_dc = 0;
  1478. threshold = -threshold;
  1479. } else
  1480. skip_dc = 1;
  1481. /* Are all we could set to zero already zero? */
  1482. if (last_index <= skip_dc - 1)
  1483. return;
  1484. for (i = 0; i <= last_index; i++) {
  1485. const int j = s->intra_scantable.permutated[i];
  1486. const int level = FFABS(block[j]);
  1487. if (level == 1) {
  1488. if (skip_dc && i == 0)
  1489. continue;
  1490. score += tab[run];
  1491. run = 0;
  1492. } else if (level > 1) {
  1493. return;
  1494. } else {
  1495. run++;
  1496. }
  1497. }
  1498. if (score >= threshold)
  1499. return;
  1500. for (i = skip_dc; i <= last_index; i++) {
  1501. const int j = s->intra_scantable.permutated[i];
  1502. block[j] = 0;
  1503. }
  1504. if (block[0])
  1505. s->block_last_index[n] = 0;
  1506. else
  1507. s->block_last_index[n] = -1;
  1508. }
  1509. static inline void clip_coeffs(MpegEncContext *s, int16_t *block,
  1510. int last_index)
  1511. {
  1512. int i;
  1513. const int maxlevel = s->max_qcoeff;
  1514. const int minlevel = s->min_qcoeff;
  1515. int overflow = 0;
  1516. if (s->mb_intra) {
  1517. i = 1; // skip clipping of intra dc
  1518. } else
  1519. i = 0;
  1520. for (; i <= last_index; i++) {
  1521. const int j = s->intra_scantable.permutated[i];
  1522. int level = block[j];
  1523. if (level > maxlevel) {
  1524. level = maxlevel;
  1525. overflow++;
  1526. } else if (level < minlevel) {
  1527. level = minlevel;
  1528. overflow++;
  1529. }
  1530. block[j] = level;
  1531. }
  1532. if (overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1533. av_log(s->avctx, AV_LOG_INFO,
  1534. "warning, clipping %d dct coefficients to %d..%d\n",
  1535. overflow, minlevel, maxlevel);
  1536. }
  1537. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride)
  1538. {
  1539. int x, y;
  1540. // FIXME optimize
  1541. for (y = 0; y < 8; y++) {
  1542. for (x = 0; x < 8; x++) {
  1543. int x2, y2;
  1544. int sum = 0;
  1545. int sqr = 0;
  1546. int count = 0;
  1547. for (y2 = FFMAX(y - 1, 0); y2 < FFMIN(8, y + 2); y2++) {
  1548. for (x2= FFMAX(x - 1, 0); x2 < FFMIN(8, x + 2); x2++) {
  1549. int v = ptr[x2 + y2 * stride];
  1550. sum += v;
  1551. sqr += v * v;
  1552. count++;
  1553. }
  1554. }
  1555. weight[x + 8 * y]= (36 * ff_sqrt(count * sqr - sum * sum)) / count;
  1556. }
  1557. }
  1558. }
  1559. static av_always_inline void encode_mb_internal(MpegEncContext *s,
  1560. int motion_x, int motion_y,
  1561. int mb_block_height,
  1562. int mb_block_count)
  1563. {
  1564. int16_t weight[8][64];
  1565. int16_t orig[8][64];
  1566. const int mb_x = s->mb_x;
  1567. const int mb_y = s->mb_y;
  1568. int i;
  1569. int skip_dct[8];
  1570. int dct_offset = s->linesize * 8; // default for progressive frames
  1571. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1572. ptrdiff_t wrap_y, wrap_c;
  1573. for (i = 0; i < mb_block_count; i++)
  1574. skip_dct[i] = s->skipdct;
  1575. if (s->adaptive_quant) {
  1576. const int last_qp = s->qscale;
  1577. const int mb_xy = mb_x + mb_y * s->mb_stride;
  1578. s->lambda = s->lambda_table[mb_xy];
  1579. update_qscale(s);
  1580. if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {
  1581. s->qscale = s->current_picture_ptr->qscale_table[mb_xy];
  1582. s->dquant = s->qscale - last_qp;
  1583. if (s->out_format == FMT_H263) {
  1584. s->dquant = av_clip(s->dquant, -2, 2);
  1585. if (s->codec_id == AV_CODEC_ID_MPEG4) {
  1586. if (!s->mb_intra) {
  1587. if (s->pict_type == AV_PICTURE_TYPE_B) {
  1588. if (s->dquant & 1 || s->mv_dir & MV_DIRECT)
  1589. s->dquant = 0;
  1590. }
  1591. if (s->mv_type == MV_TYPE_8X8)
  1592. s->dquant = 0;
  1593. }
  1594. }
  1595. }
  1596. }
  1597. ff_set_qscale(s, last_qp + s->dquant);
  1598. } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)
  1599. ff_set_qscale(s, s->qscale + s->dquant);
  1600. wrap_y = s->linesize;
  1601. wrap_c = s->uvlinesize;
  1602. ptr_y = s->new_picture.f.data[0] +
  1603. (mb_y * 16 * wrap_y) + mb_x * 16;
  1604. ptr_cb = s->new_picture.f.data[1] +
  1605. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1606. ptr_cr = s->new_picture.f.data[2] +
  1607. (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1608. if (mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) {
  1609. uint8_t *ebuf = s->edge_emu_buffer + 32;
  1610. s->vdsp.emulated_edge_mc(ebuf, ptr_y,
  1611. wrap_y, wrap_y,
  1612. 16, 16, mb_x * 16, mb_y * 16,
  1613. s->width, s->height);
  1614. ptr_y = ebuf;
  1615. s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y, ptr_cb,
  1616. wrap_c, wrap_c,
  1617. 8, mb_block_height, mb_x * 8, mb_y * 8,
  1618. s->width >> 1, s->height >> 1);
  1619. ptr_cb = ebuf + 18 * wrap_y;
  1620. s->vdsp.emulated_edge_mc(ebuf + 18 * wrap_y + 8, ptr_cr,
  1621. wrap_c, wrap_c,
  1622. 8, mb_block_height, mb_x * 8, mb_y * 8,
  1623. s->width >> 1, s->height >> 1);
  1624. ptr_cr = ebuf + 18 * wrap_y + 8;
  1625. }
  1626. if (s->mb_intra) {
  1627. if (s->flags & CODEC_FLAG_INTERLACED_DCT) {
  1628. int progressive_score, interlaced_score;
  1629. s->interlaced_dct = 0;
  1630. progressive_score = s->dsp.ildct_cmp[4](s, ptr_y,
  1631. NULL, wrap_y, 8) +
  1632. s->dsp.ildct_cmp[4](s, ptr_y + wrap_y * 8,
  1633. NULL, wrap_y, 8) - 400;
  1634. if (progressive_score > 0) {
  1635. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y,
  1636. NULL, wrap_y * 2, 8) +
  1637. s->dsp.ildct_cmp[4](s, ptr_y + wrap_y,
  1638. NULL, wrap_y * 2, 8);
  1639. if (progressive_score > interlaced_score) {
  1640. s->interlaced_dct = 1;
  1641. dct_offset = wrap_y;
  1642. wrap_y <<= 1;
  1643. if (s->chroma_format == CHROMA_422)
  1644. wrap_c <<= 1;
  1645. }
  1646. }
  1647. }
  1648. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1649. s->dsp.get_pixels(s->block[1], ptr_y + 8 , wrap_y);
  1650. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1651. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8 , wrap_y);
  1652. if (s->flags & CODEC_FLAG_GRAY) {
  1653. skip_dct[4] = 1;
  1654. skip_dct[5] = 1;
  1655. } else {
  1656. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1657. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1658. if (!s->chroma_y_shift) { /* 422 */
  1659. s->dsp.get_pixels(s->block[6],
  1660. ptr_cb + (dct_offset >> 1), wrap_c);
  1661. s->dsp.get_pixels(s->block[7],
  1662. ptr_cr + (dct_offset >> 1), wrap_c);
  1663. }
  1664. }
  1665. } else {
  1666. op_pixels_func (*op_pix)[4];
  1667. qpel_mc_func (*op_qpix)[16];
  1668. uint8_t *dest_y, *dest_cb, *dest_cr;
  1669. dest_y = s->dest[0];
  1670. dest_cb = s->dest[1];
  1671. dest_cr = s->dest[2];
  1672. if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {
  1673. op_pix = s->hdsp.put_pixels_tab;
  1674. op_qpix = s->dsp.put_qpel_pixels_tab;
  1675. } else {
  1676. op_pix = s->hdsp.put_no_rnd_pixels_tab;
  1677. op_qpix = s->dsp.put_no_rnd_qpel_pixels_tab;
  1678. }
  1679. if (s->mv_dir & MV_DIR_FORWARD) {
  1680. ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 0,
  1681. s->last_picture.f.data,
  1682. op_pix, op_qpix);
  1683. op_pix = s->hdsp.avg_pixels_tab;
  1684. op_qpix = s->dsp.avg_qpel_pixels_tab;
  1685. }
  1686. if (s->mv_dir & MV_DIR_BACKWARD) {
  1687. ff_MPV_motion(s, dest_y, dest_cb, dest_cr, 1,
  1688. s->next_picture.f.data,
  1689. op_pix, op_qpix);
  1690. }
  1691. if (s->flags & CODEC_FLAG_INTERLACED_DCT) {
  1692. int progressive_score, interlaced_score;
  1693. s->interlaced_dct = 0;
  1694. progressive_score = s->dsp.ildct_cmp[0](s, dest_y,
  1695. ptr_y, wrap_y,
  1696. 8) +
  1697. s->dsp.ildct_cmp[0](s, dest_y + wrap_y * 8,
  1698. ptr_y + wrap_y * 8, wrap_y,
  1699. 8) - 400;
  1700. if (s->avctx->ildct_cmp == FF_CMP_VSSE)
  1701. progressive_score -= 400;
  1702. if (progressive_score > 0) {
  1703. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y,
  1704. ptr_y,
  1705. wrap_y * 2, 8) +
  1706. s->dsp.ildct_cmp[0](s, dest_y + wrap_y,
  1707. ptr_y + wrap_y,
  1708. wrap_y * 2, 8);
  1709. if (progressive_score > interlaced_score) {
  1710. s->interlaced_dct = 1;
  1711. dct_offset = wrap_y;
  1712. wrap_y <<= 1;
  1713. if (s->chroma_format == CHROMA_422)
  1714. wrap_c <<= 1;
  1715. }
  1716. }
  1717. }
  1718. s->dsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);
  1719. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1720. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset,
  1721. dest_y + dct_offset, wrap_y);
  1722. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,
  1723. dest_y + dct_offset + 8, wrap_y);
  1724. if (s->flags & CODEC_FLAG_GRAY) {
  1725. skip_dct[4] = 1;
  1726. skip_dct[5] = 1;
  1727. } else {
  1728. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1729. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1730. if (!s->chroma_y_shift) { /* 422 */
  1731. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset >> 1),
  1732. dest_cb + (dct_offset >> 1), wrap_c);
  1733. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset >> 1),
  1734. dest_cr + (dct_offset >> 1), wrap_c);
  1735. }
  1736. }
  1737. /* pre quantization */
  1738. if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <
  1739. 2 * s->qscale * s->qscale) {
  1740. // FIXME optimize
  1741. if (s->dsp.sad[1](NULL, ptr_y , dest_y,
  1742. wrap_y, 8) < 20 * s->qscale)
  1743. skip_dct[0] = 1;
  1744. if (s->dsp.sad[1](NULL, ptr_y + 8,
  1745. dest_y + 8, wrap_y, 8) < 20 * s->qscale)
  1746. skip_dct[1] = 1;
  1747. if (s->dsp.sad[1](NULL, ptr_y + dct_offset,
  1748. dest_y + dct_offset, wrap_y, 8) < 20 * s->qscale)
  1749. skip_dct[2] = 1;
  1750. if (s->dsp.sad[1](NULL, ptr_y + dct_offset + 8,
  1751. dest_y + dct_offset + 8,
  1752. wrap_y, 8) < 20 * s->qscale)
  1753. skip_dct[3] = 1;
  1754. if (s->dsp.sad[1](NULL, ptr_cb, dest_cb,
  1755. wrap_c, 8) < 20 * s->qscale)
  1756. skip_dct[4] = 1;
  1757. if (s->dsp.sad[1](NULL, ptr_cr, dest_cr,
  1758. wrap_c, 8) < 20 * s->qscale)
  1759. skip_dct[5] = 1;
  1760. if (!s->chroma_y_shift) { /* 422 */
  1761. if (s->dsp.sad[1](NULL, ptr_cb + (dct_offset >> 1),
  1762. dest_cb + (dct_offset >> 1),
  1763. wrap_c, 8) < 20 * s->qscale)
  1764. skip_dct[6] = 1;
  1765. if (s->dsp.sad[1](NULL, ptr_cr + (dct_offset >> 1),
  1766. dest_cr + (dct_offset >> 1),
  1767. wrap_c, 8) < 20 * s->qscale)
  1768. skip_dct[7] = 1;
  1769. }
  1770. }
  1771. }
  1772. if (s->quantizer_noise_shaping) {
  1773. if (!skip_dct[0])
  1774. get_visual_weight(weight[0], ptr_y , wrap_y);
  1775. if (!skip_dct[1])
  1776. get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1777. if (!skip_dct[2])
  1778. get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1779. if (!skip_dct[3])
  1780. get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1781. if (!skip_dct[4])
  1782. get_visual_weight(weight[4], ptr_cb , wrap_c);
  1783. if (!skip_dct[5])
  1784. get_visual_weight(weight[5], ptr_cr , wrap_c);
  1785. if (!s->chroma_y_shift) { /* 422 */
  1786. if (!skip_dct[6])
  1787. get_visual_weight(weight[6], ptr_cb + (dct_offset >> 1),
  1788. wrap_c);
  1789. if (!skip_dct[7])
  1790. get_visual_weight(weight[7], ptr_cr + (dct_offset >> 1),
  1791. wrap_c);
  1792. }
  1793. memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);
  1794. }
  1795. /* DCT & quantize */
  1796. assert(s->out_format != FMT_MJPEG || s->qscale == 8);
  1797. {
  1798. for (i = 0; i < mb_block_count; i++) {
  1799. if (!skip_dct[i]) {
  1800. int overflow;
  1801. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1802. // FIXME we could decide to change to quantizer instead of
  1803. // clipping
  1804. // JS: I don't think that would be a good idea it could lower
  1805. // quality instead of improve it. Just INTRADC clipping
  1806. // deserves changes in quantizer
  1807. if (overflow)
  1808. clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1809. } else
  1810. s->block_last_index[i] = -1;
  1811. }
  1812. if (s->quantizer_noise_shaping) {
  1813. for (i = 0; i < mb_block_count; i++) {
  1814. if (!skip_dct[i]) {
  1815. s->block_last_index[i] =
  1816. dct_quantize_refine(s, s->block[i], weight[i],
  1817. orig[i], i, s->qscale);
  1818. }
  1819. }
  1820. }
  1821. if (s->luma_elim_threshold && !s->mb_intra)
  1822. for (i = 0; i < 4; i++)
  1823. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1824. if (s->chroma_elim_threshold && !s->mb_intra)
  1825. for (i = 4; i < mb_block_count; i++)
  1826. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1827. if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
  1828. for (i = 0; i < mb_block_count; i++) {
  1829. if (s->block_last_index[i] == -1)
  1830. s->coded_score[i] = INT_MAX / 256;
  1831. }
  1832. }
  1833. }
  1834. if ((s->flags & CODEC_FLAG_GRAY) && s->mb_intra) {
  1835. s->block_last_index[4] =
  1836. s->block_last_index[5] = 0;
  1837. s->block[4][0] =
  1838. s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;
  1839. }
  1840. // non c quantize code returns incorrect block_last_index FIXME
  1841. if (s->alternate_scan && s->dct_quantize != ff_dct_quantize_c) {
  1842. for (i = 0; i < mb_block_count; i++) {
  1843. int j;
  1844. if (s->block_last_index[i] > 0) {
  1845. for (j = 63; j > 0; j--) {
  1846. if (s->block[i][s->intra_scantable.permutated[j]])
  1847. break;
  1848. }
  1849. s->block_last_index[i] = j;
  1850. }
  1851. }
  1852. }
  1853. /* huffman encode */
  1854. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1855. case AV_CODEC_ID_MPEG1VIDEO:
  1856. case AV_CODEC_ID_MPEG2VIDEO:
  1857. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1858. ff_mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1859. break;
  1860. case AV_CODEC_ID_MPEG4:
  1861. if (CONFIG_MPEG4_ENCODER)
  1862. ff_mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1863. break;
  1864. case AV_CODEC_ID_MSMPEG4V2:
  1865. case AV_CODEC_ID_MSMPEG4V3:
  1866. case AV_CODEC_ID_WMV1:
  1867. if (CONFIG_MSMPEG4_ENCODER)
  1868. ff_msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1869. break;
  1870. case AV_CODEC_ID_WMV2:
  1871. if (CONFIG_WMV2_ENCODER)
  1872. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1873. break;
  1874. case AV_CODEC_ID_H261:
  1875. if (CONFIG_H261_ENCODER)
  1876. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1877. break;
  1878. case AV_CODEC_ID_H263:
  1879. case AV_CODEC_ID_H263P:
  1880. case AV_CODEC_ID_FLV1:
  1881. case AV_CODEC_ID_RV10:
  1882. case AV_CODEC_ID_RV20:
  1883. if (CONFIG_H263_ENCODER)
  1884. ff_h263_encode_mb(s, s->block, motion_x, motion_y);
  1885. break;
  1886. case AV_CODEC_ID_MJPEG:
  1887. if (CONFIG_MJPEG_ENCODER)
  1888. ff_mjpeg_encode_mb(s, s->block);
  1889. break;
  1890. default:
  1891. assert(0);
  1892. }
  1893. }
  1894. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1895. {
  1896. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1897. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1898. }
  1899. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1900. int i;
  1901. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1902. /* mpeg1 */
  1903. d->mb_skip_run= s->mb_skip_run;
  1904. for(i=0; i<3; i++)
  1905. d->last_dc[i] = s->last_dc[i];
  1906. /* statistics */
  1907. d->mv_bits= s->mv_bits;
  1908. d->i_tex_bits= s->i_tex_bits;
  1909. d->p_tex_bits= s->p_tex_bits;
  1910. d->i_count= s->i_count;
  1911. d->f_count= s->f_count;
  1912. d->b_count= s->b_count;
  1913. d->skip_count= s->skip_count;
  1914. d->misc_bits= s->misc_bits;
  1915. d->last_bits= 0;
  1916. d->mb_skipped= 0;
  1917. d->qscale= s->qscale;
  1918. d->dquant= s->dquant;
  1919. d->esc3_level_length= s->esc3_level_length;
  1920. }
  1921. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1922. int i;
  1923. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1924. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1925. /* mpeg1 */
  1926. d->mb_skip_run= s->mb_skip_run;
  1927. for(i=0; i<3; i++)
  1928. d->last_dc[i] = s->last_dc[i];
  1929. /* statistics */
  1930. d->mv_bits= s->mv_bits;
  1931. d->i_tex_bits= s->i_tex_bits;
  1932. d->p_tex_bits= s->p_tex_bits;
  1933. d->i_count= s->i_count;
  1934. d->f_count= s->f_count;
  1935. d->b_count= s->b_count;
  1936. d->skip_count= s->skip_count;
  1937. d->misc_bits= s->misc_bits;
  1938. d->mb_intra= s->mb_intra;
  1939. d->mb_skipped= s->mb_skipped;
  1940. d->mv_type= s->mv_type;
  1941. d->mv_dir= s->mv_dir;
  1942. d->pb= s->pb;
  1943. if(s->data_partitioning){
  1944. d->pb2= s->pb2;
  1945. d->tex_pb= s->tex_pb;
  1946. }
  1947. d->block= s->block;
  1948. for(i=0; i<8; i++)
  1949. d->block_last_index[i]= s->block_last_index[i];
  1950. d->interlaced_dct= s->interlaced_dct;
  1951. d->qscale= s->qscale;
  1952. d->esc3_level_length= s->esc3_level_length;
  1953. }
  1954. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1955. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1956. int *dmin, int *next_block, int motion_x, int motion_y)
  1957. {
  1958. int score;
  1959. uint8_t *dest_backup[3];
  1960. copy_context_before_encode(s, backup, type);
  1961. s->block= s->blocks[*next_block];
  1962. s->pb= pb[*next_block];
  1963. if(s->data_partitioning){
  1964. s->pb2 = pb2 [*next_block];
  1965. s->tex_pb= tex_pb[*next_block];
  1966. }
  1967. if(*next_block){
  1968. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1969. s->dest[0] = s->rd_scratchpad;
  1970. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1971. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1972. assert(s->linesize >= 32); //FIXME
  1973. }
  1974. encode_mb(s, motion_x, motion_y);
  1975. score= put_bits_count(&s->pb);
  1976. if(s->data_partitioning){
  1977. score+= put_bits_count(&s->pb2);
  1978. score+= put_bits_count(&s->tex_pb);
  1979. }
  1980. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1981. ff_MPV_decode_mb(s, s->block);
  1982. score *= s->lambda2;
  1983. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1984. }
  1985. if(*next_block){
  1986. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1987. }
  1988. if(score<*dmin){
  1989. *dmin= score;
  1990. *next_block^=1;
  1991. copy_context_after_encode(best, s, type);
  1992. }
  1993. }
  1994. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1995. uint32_t *sq = ff_squareTbl + 256;
  1996. int acc=0;
  1997. int x,y;
  1998. if(w==16 && h==16)
  1999. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  2000. else if(w==8 && h==8)
  2001. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  2002. for(y=0; y<h; y++){
  2003. for(x=0; x<w; x++){
  2004. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  2005. }
  2006. }
  2007. assert(acc>=0);
  2008. return acc;
  2009. }
  2010. static int sse_mb(MpegEncContext *s){
  2011. int w= 16;
  2012. int h= 16;
  2013. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2014. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2015. if(w==16 && h==16)
  2016. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  2017. 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)
  2018. +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)
  2019. +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);
  2020. }else{
  2021. 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)
  2022. +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)
  2023. +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);
  2024. }
  2025. else
  2026. 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)
  2027. +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)
  2028. +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);
  2029. }
  2030. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  2031. MpegEncContext *s= *(void**)arg;
  2032. s->me.pre_pass=1;
  2033. s->me.dia_size= s->avctx->pre_dia_size;
  2034. s->first_slice_line=1;
  2035. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  2036. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  2037. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2038. }
  2039. s->first_slice_line=0;
  2040. }
  2041. s->me.pre_pass=0;
  2042. return 0;
  2043. }
  2044. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  2045. MpegEncContext *s= *(void**)arg;
  2046. ff_check_alignment();
  2047. s->me.dia_size= s->avctx->dia_size;
  2048. s->first_slice_line=1;
  2049. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  2050. s->mb_x=0; //for block init below
  2051. ff_init_block_index(s);
  2052. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  2053. s->block_index[0]+=2;
  2054. s->block_index[1]+=2;
  2055. s->block_index[2]+=2;
  2056. s->block_index[3]+=2;
  2057. /* compute motion vector & mb_type and store in context */
  2058. if(s->pict_type==AV_PICTURE_TYPE_B)
  2059. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  2060. else
  2061. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2062. }
  2063. s->first_slice_line=0;
  2064. }
  2065. return 0;
  2066. }
  2067. static int mb_var_thread(AVCodecContext *c, void *arg){
  2068. MpegEncContext *s= *(void**)arg;
  2069. int mb_x, mb_y;
  2070. ff_check_alignment();
  2071. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2072. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2073. int xx = mb_x * 16;
  2074. int yy = mb_y * 16;
  2075. uint8_t *pix = s->new_picture.f.data[0] + (yy * s->linesize) + xx;
  2076. int varc;
  2077. int sum = s->dsp.pix_sum(pix, s->linesize);
  2078. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500 + 128)>>8;
  2079. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  2080. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  2081. s->me.mb_var_sum_temp += varc;
  2082. }
  2083. }
  2084. return 0;
  2085. }
  2086. static void write_slice_end(MpegEncContext *s){
  2087. if(CONFIG_MPEG4_ENCODER && s->codec_id==AV_CODEC_ID_MPEG4){
  2088. if(s->partitioned_frame){
  2089. ff_mpeg4_merge_partitions(s);
  2090. }
  2091. ff_mpeg4_stuffing(&s->pb);
  2092. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  2093. ff_mjpeg_encode_stuffing(&s->pb);
  2094. }
  2095. avpriv_align_put_bits(&s->pb);
  2096. flush_put_bits(&s->pb);
  2097. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  2098. s->misc_bits+= get_bits_diff(s);
  2099. }
  2100. static void write_mb_info(MpegEncContext *s)
  2101. {
  2102. uint8_t *ptr = s->mb_info_ptr + s->mb_info_size - 12;
  2103. int offset = put_bits_count(&s->pb);
  2104. int mba = s->mb_x + s->mb_width * (s->mb_y % s->gob_index);
  2105. int gobn = s->mb_y / s->gob_index;
  2106. int pred_x, pred_y;
  2107. if (CONFIG_H263_ENCODER)
  2108. ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  2109. bytestream_put_le32(&ptr, offset);
  2110. bytestream_put_byte(&ptr, s->qscale);
  2111. bytestream_put_byte(&ptr, gobn);
  2112. bytestream_put_le16(&ptr, mba);
  2113. bytestream_put_byte(&ptr, pred_x); /* hmv1 */
  2114. bytestream_put_byte(&ptr, pred_y); /* vmv1 */
  2115. /* 4MV not implemented */
  2116. bytestream_put_byte(&ptr, 0); /* hmv2 */
  2117. bytestream_put_byte(&ptr, 0); /* vmv2 */
  2118. }
  2119. static void update_mb_info(MpegEncContext *s, int startcode)
  2120. {
  2121. if (!s->mb_info)
  2122. return;
  2123. if (put_bits_count(&s->pb) - s->prev_mb_info*8 >= s->mb_info*8) {
  2124. s->mb_info_size += 12;
  2125. s->prev_mb_info = s->last_mb_info;
  2126. }
  2127. if (startcode) {
  2128. s->prev_mb_info = put_bits_count(&s->pb)/8;
  2129. /* This might have incremented mb_info_size above, and we return without
  2130. * actually writing any info into that slot yet. But in that case,
  2131. * this will be called again at the start of the after writing the
  2132. * start code, actually writing the mb info. */
  2133. return;
  2134. }
  2135. s->last_mb_info = put_bits_count(&s->pb)/8;
  2136. if (!s->mb_info_size)
  2137. s->mb_info_size += 12;
  2138. write_mb_info(s);
  2139. }
  2140. static int encode_thread(AVCodecContext *c, void *arg){
  2141. MpegEncContext *s= *(void**)arg;
  2142. int mb_x, mb_y, pdif = 0;
  2143. int chr_h= 16>>s->chroma_y_shift;
  2144. int i, j;
  2145. MpegEncContext best_s, backup_s;
  2146. uint8_t bit_buf[2][MAX_MB_BYTES];
  2147. uint8_t bit_buf2[2][MAX_MB_BYTES];
  2148. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  2149. PutBitContext pb[2], pb2[2], tex_pb[2];
  2150. ff_check_alignment();
  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. };