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.

4488 lines
163KB

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