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.

4550 lines
166KB

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