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.

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