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.

4236 lines
152KB

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