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.

4547 lines
165KB

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