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.

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