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.

4206 lines
151KB

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