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.

4226 lines
153KB

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