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.

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