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.

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