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.

3844 lines
139KB

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