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.

4566 lines
166KB

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