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.

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