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.

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