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.

4429 lines
162KB

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