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

3830 lines
140KB

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