You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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