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.

3920 lines
144KB

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