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.

3830 lines
140KB

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