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.

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