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.

4187 lines
151KB

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