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.

4502 lines
164KB

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