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.

4542 lines
165KB

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