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.

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