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.

4510 lines
164KB

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