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

3855 lines
140KB

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