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.

3926 lines
145KB

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