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.

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