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.

4304 lines
155KB

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