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.

4148 lines
149KB

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