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.

3927 lines
145KB

  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. * Set 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. if (i < 0)
  759. return i;
  760. pic= (AVFrame*)&s->picture[i];
  761. pic->reference= 3;
  762. for(i=0; i<4; i++){
  763. pic->data[i]= pic_arg->data[i];
  764. pic->linesize[i]= pic_arg->linesize[i];
  765. }
  766. if(ff_alloc_picture(s, (Picture*)pic, 1) < 0){
  767. return -1;
  768. }
  769. }else{
  770. i= ff_find_unused_picture(s, 0);
  771. if (i < 0)
  772. return i;
  773. pic= (AVFrame*)&s->picture[i];
  774. pic->reference= 3;
  775. if(ff_alloc_picture(s, (Picture*)pic, 0) < 0){
  776. return -1;
  777. }
  778. if( pic->data[0] + INPLACE_OFFSET == pic_arg->data[0]
  779. && pic->data[1] + INPLACE_OFFSET == pic_arg->data[1]
  780. && pic->data[2] + INPLACE_OFFSET == pic_arg->data[2]){
  781. // empty
  782. }else{
  783. int h_chroma_shift, v_chroma_shift;
  784. avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  785. for(i=0; i<3; i++){
  786. int src_stride= pic_arg->linesize[i];
  787. int dst_stride= i ? s->uvlinesize : s->linesize;
  788. int h_shift= i ? h_chroma_shift : 0;
  789. int v_shift= i ? v_chroma_shift : 0;
  790. int w= s->width >>h_shift;
  791. int h= s->height>>v_shift;
  792. uint8_t *src= pic_arg->data[i];
  793. uint8_t *dst= pic->data[i];
  794. if(s->codec_id == CODEC_ID_AMV && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)){
  795. h= ((s->height+15)/16*16)>>v_shift;
  796. }
  797. if(!s->avctx->rc_buffer_size)
  798. dst +=INPLACE_OFFSET;
  799. if(src_stride==dst_stride)
  800. memcpy(dst, src, src_stride*h);
  801. else{
  802. while(h--){
  803. memcpy(dst, src, w);
  804. dst += dst_stride;
  805. src += src_stride;
  806. }
  807. }
  808. }
  809. }
  810. }
  811. copy_picture_attributes(s, pic, pic_arg);
  812. pic->pts= pts; //we set this here to avoid modifiying pic_arg
  813. }
  814. /* shift buffer entries */
  815. for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
  816. s->input_picture[i-1]= s->input_picture[i];
  817. s->input_picture[encoding_delay]= (Picture*)pic;
  818. return 0;
  819. }
  820. static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){
  821. int x, y, plane;
  822. int score=0;
  823. int64_t score64=0;
  824. for(plane=0; plane<3; plane++){
  825. const int stride = p->f.linesize[plane];
  826. const int bw= plane ? 1 : 2;
  827. for(y=0; y<s->mb_height*bw; y++){
  828. for(x=0; x<s->mb_width*bw; x++){
  829. int off = p->f.type == FF_BUFFER_TYPE_SHARED ? 0: 16;
  830. 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);
  831. switch(s->avctx->frame_skip_exp){
  832. case 0: score= FFMAX(score, v); break;
  833. case 1: score+= FFABS(v);break;
  834. case 2: score+= v*v;break;
  835. case 3: score64+= FFABS(v*v*(int64_t)v);break;
  836. case 4: score64+= v*v*(int64_t)(v*v);break;
  837. }
  838. }
  839. }
  840. }
  841. if(score) score64= score;
  842. if(score64 < s->avctx->frame_skip_threshold)
  843. return 1;
  844. if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))
  845. return 1;
  846. return 0;
  847. }
  848. static int estimate_best_b_count(MpegEncContext *s){
  849. AVCodec *codec= avcodec_find_encoder(s->avctx->codec_id);
  850. AVCodecContext *c = avcodec_alloc_context3(NULL);
  851. AVFrame input[FF_MAX_B_FRAMES+2];
  852. const int scale= s->avctx->brd_scale;
  853. int i, j, out_size, p_lambda, b_lambda, lambda2;
  854. int outbuf_size= s->width * s->height; //FIXME
  855. uint8_t *outbuf= av_malloc(outbuf_size);
  856. int64_t best_rd= INT64_MAX;
  857. int best_b_count= -1;
  858. assert(scale>=0 && scale <=3);
  859. // emms_c();
  860. p_lambda= s->last_lambda_for[AV_PICTURE_TYPE_P]; //s->next_picture_ptr->quality;
  861. b_lambda= s->last_lambda_for[AV_PICTURE_TYPE_B]; //p_lambda *FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  862. if(!b_lambda) b_lambda= p_lambda; //FIXME we should do this somewhere else
  863. lambda2= (b_lambda*b_lambda + (1<<FF_LAMBDA_SHIFT)/2 ) >> FF_LAMBDA_SHIFT;
  864. c->width = s->width >> scale;
  865. c->height= s->height>> scale;
  866. c->flags= CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR | CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;
  867. c->flags|= s->avctx->flags & CODEC_FLAG_QPEL;
  868. c->mb_decision= s->avctx->mb_decision;
  869. c->me_cmp= s->avctx->me_cmp;
  870. c->mb_cmp= s->avctx->mb_cmp;
  871. c->me_sub_cmp= s->avctx->me_sub_cmp;
  872. c->pix_fmt = PIX_FMT_YUV420P;
  873. c->time_base= s->avctx->time_base;
  874. c->max_b_frames= s->max_b_frames;
  875. if (avcodec_open2(c, codec, NULL) < 0)
  876. return -1;
  877. for(i=0; i<s->max_b_frames+2; i++){
  878. int ysize= c->width*c->height;
  879. int csize= (c->width/2)*(c->height/2);
  880. Picture pre_input, *pre_input_ptr= i ? s->input_picture[i-1] : s->next_picture_ptr;
  881. avcodec_get_frame_defaults(&input[i]);
  882. input[i].data[0]= av_malloc(ysize + 2*csize);
  883. input[i].data[1]= input[i].data[0] + ysize;
  884. input[i].data[2]= input[i].data[1] + csize;
  885. input[i].linesize[0]= c->width;
  886. input[i].linesize[1]=
  887. input[i].linesize[2]= c->width/2;
  888. if(pre_input_ptr && (!i || s->input_picture[i-1])) {
  889. pre_input= *pre_input_ptr;
  890. if (pre_input.f.type != FF_BUFFER_TYPE_SHARED && i) {
  891. pre_input.f.data[0] += INPLACE_OFFSET;
  892. pre_input.f.data[1] += INPLACE_OFFSET;
  893. pre_input.f.data[2] += INPLACE_OFFSET;
  894. }
  895. 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);
  896. 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);
  897. 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);
  898. }
  899. }
  900. for(j=0; j<s->max_b_frames+1; j++){
  901. int64_t rd=0;
  902. if(!s->input_picture[j])
  903. break;
  904. c->error[0]= c->error[1]= c->error[2]= 0;
  905. input[0].pict_type= AV_PICTURE_TYPE_I;
  906. input[0].quality= 1 * FF_QP2LAMBDA;
  907. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[0]);
  908. // rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  909. for(i=0; i<s->max_b_frames+1; i++){
  910. int is_p= i % (j+1) == j || i==s->max_b_frames;
  911. input[i+1].pict_type= is_p ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
  912. input[i+1].quality= is_p ? p_lambda : b_lambda;
  913. out_size = avcodec_encode_video(c, outbuf, outbuf_size, &input[i+1]);
  914. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  915. }
  916. /* get the delayed frames */
  917. while(out_size){
  918. out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
  919. rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  920. }
  921. rd += c->error[0] + c->error[1] + c->error[2];
  922. if(rd < best_rd){
  923. best_rd= rd;
  924. best_b_count= j;
  925. }
  926. }
  927. av_freep(&outbuf);
  928. avcodec_close(c);
  929. av_freep(&c);
  930. for(i=0; i<s->max_b_frames+2; i++){
  931. av_freep(&input[i].data[0]);
  932. }
  933. return best_b_count;
  934. }
  935. static int select_input_picture(MpegEncContext *s){
  936. int i;
  937. for(i=1; i<MAX_PICTURE_COUNT; i++)
  938. s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
  939. s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
  940. /* set next picture type & ordering */
  941. if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
  942. if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
  943. s->reordered_input_picture[0]= s->input_picture[0];
  944. s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_I;
  945. s->reordered_input_picture[0]->f.coded_picture_number = s->coded_picture_number++;
  946. }else{
  947. int b_frames;
  948. if(s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor){
  949. if(s->picture_in_gop_number < s->gop_size && skip_check(s, s->input_picture[0], s->next_picture_ptr)){
  950. //FIXME check that te gop check above is +-1 correct
  951. //av_log(NULL, AV_LOG_DEBUG, "skip %p %"PRId64"\n", s->input_picture[0]->f.data[0], s->input_picture[0]->pts);
  952. if (s->input_picture[0]->f.type == FF_BUFFER_TYPE_SHARED) {
  953. for(i=0; i<4; i++)
  954. s->input_picture[0]->f.data[i] = NULL;
  955. s->input_picture[0]->f.type = 0;
  956. }else{
  957. assert( s->input_picture[0]->f.type == FF_BUFFER_TYPE_USER
  958. || s->input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL);
  959. s->avctx->release_buffer(s->avctx, (AVFrame*)s->input_picture[0]);
  960. }
  961. emms_c();
  962. ff_vbv_update(s, 0);
  963. goto no_output_pic;
  964. }
  965. }
  966. if(s->flags&CODEC_FLAG_PASS2){
  967. for(i=0; i<s->max_b_frames+1; i++){
  968. int pict_num = s->input_picture[0]->f.display_picture_number + i;
  969. if(pict_num >= s->rc_context.num_entries)
  970. break;
  971. if(!s->input_picture[i]){
  972. s->rc_context.entry[pict_num-1].new_pict_type = AV_PICTURE_TYPE_P;
  973. break;
  974. }
  975. s->input_picture[i]->f.pict_type =
  976. s->rc_context.entry[pict_num].new_pict_type;
  977. }
  978. }
  979. if(s->avctx->b_frame_strategy==0){
  980. b_frames= s->max_b_frames;
  981. while(b_frames && !s->input_picture[b_frames]) b_frames--;
  982. }else if(s->avctx->b_frame_strategy==1){
  983. for(i=1; i<s->max_b_frames+1; i++){
  984. if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
  985. s->input_picture[i]->b_frame_score=
  986. get_intra_count(s, s->input_picture[i ]->f.data[0],
  987. s->input_picture[i-1]->f.data[0], s->linesize) + 1;
  988. }
  989. }
  990. for(i=0; i<s->max_b_frames+1; i++){
  991. if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/s->avctx->b_sensitivity) break;
  992. }
  993. b_frames= FFMAX(0, i-1);
  994. /* reset scores */
  995. for(i=0; i<b_frames+1; i++){
  996. s->input_picture[i]->b_frame_score=0;
  997. }
  998. }else if(s->avctx->b_frame_strategy==2){
  999. b_frames= estimate_best_b_count(s);
  1000. }else{
  1001. av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  1002. b_frames=0;
  1003. }
  1004. emms_c();
  1005. //static int b_count=0;
  1006. //b_count+= b_frames;
  1007. //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
  1008. for(i= b_frames - 1; i>=0; i--){
  1009. int type = s->input_picture[i]->f.pict_type;
  1010. if(type && type != AV_PICTURE_TYPE_B)
  1011. b_frames= i;
  1012. }
  1013. if (s->input_picture[b_frames]->f.pict_type == AV_PICTURE_TYPE_B && b_frames == s->max_b_frames){
  1014. av_log(s->avctx, AV_LOG_ERROR, "warning, too many b frames in a row\n");
  1015. }
  1016. if(s->picture_in_gop_number + b_frames >= s->gop_size){
  1017. if((s->flags2 & CODEC_FLAG2_STRICT_GOP) && s->gop_size > s->picture_in_gop_number){
  1018. b_frames= s->gop_size - s->picture_in_gop_number - 1;
  1019. }else{
  1020. if(s->flags & CODEC_FLAG_CLOSED_GOP)
  1021. b_frames=0;
  1022. s->input_picture[b_frames]->f.pict_type = AV_PICTURE_TYPE_I;
  1023. }
  1024. }
  1025. if( (s->flags & CODEC_FLAG_CLOSED_GOP)
  1026. && b_frames
  1027. && s->input_picture[b_frames]->f.pict_type== AV_PICTURE_TYPE_I)
  1028. b_frames--;
  1029. s->reordered_input_picture[0]= s->input_picture[b_frames];
  1030. if (s->reordered_input_picture[0]->f.pict_type != AV_PICTURE_TYPE_I)
  1031. s->reordered_input_picture[0]->f.pict_type = AV_PICTURE_TYPE_P;
  1032. s->reordered_input_picture[0]->f.coded_picture_number = s->coded_picture_number++;
  1033. for(i=0; i<b_frames; i++){
  1034. s->reordered_input_picture[i + 1] = s->input_picture[i];
  1035. s->reordered_input_picture[i + 1]->f.pict_type = AV_PICTURE_TYPE_B;
  1036. s->reordered_input_picture[i + 1]->f.coded_picture_number = s->coded_picture_number++;
  1037. }
  1038. }
  1039. }
  1040. no_output_pic:
  1041. if(s->reordered_input_picture[0]){
  1042. s->reordered_input_picture[0]->f.reference = s->reordered_input_picture[0]->f.pict_type!=AV_PICTURE_TYPE_B ? 3 : 0;
  1043. ff_copy_picture(&s->new_picture, s->reordered_input_picture[0]);
  1044. if (s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_SHARED || s->avctx->rc_buffer_size) {
  1045. // input is a shared pix, so we can't modifiy it -> alloc a new one & ensure that the shared one is reuseable
  1046. Picture *pic;
  1047. int i= ff_find_unused_picture(s, 0);
  1048. if (i < 0)
  1049. return i;
  1050. pic = &s->picture[i];
  1051. pic->f.reference = s->reordered_input_picture[0]->f.reference;
  1052. if(ff_alloc_picture(s, pic, 0) < 0){
  1053. return -1;
  1054. }
  1055. /* mark us unused / free shared pic */
  1056. if (s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL)
  1057. s->avctx->release_buffer(s->avctx, (AVFrame*)s->reordered_input_picture[0]);
  1058. for(i=0; i<4; i++)
  1059. s->reordered_input_picture[0]->f.data[i] = NULL;
  1060. s->reordered_input_picture[0]->f.type = 0;
  1061. copy_picture_attributes(s, (AVFrame*)pic, (AVFrame*)s->reordered_input_picture[0]);
  1062. s->current_picture_ptr= pic;
  1063. }else{
  1064. // input is not a shared pix -> reuse buffer for current_pix
  1065. assert( s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_USER
  1066. || s->reordered_input_picture[0]->f.type == FF_BUFFER_TYPE_INTERNAL);
  1067. s->current_picture_ptr= s->reordered_input_picture[0];
  1068. for(i=0; i<4; i++){
  1069. s->new_picture.f.data[i] += INPLACE_OFFSET;
  1070. }
  1071. }
  1072. ff_copy_picture(&s->current_picture, s->current_picture_ptr);
  1073. s->picture_number = s->new_picture.f.display_picture_number;
  1074. //printf("dpn:%d\n", s->picture_number);
  1075. }else{
  1076. memset(&s->new_picture, 0, sizeof(Picture));
  1077. }
  1078. return 0;
  1079. }
  1080. int MPV_encode_picture(AVCodecContext *avctx,
  1081. unsigned char *buf, int buf_size, void *data)
  1082. {
  1083. MpegEncContext *s = avctx->priv_data;
  1084. AVFrame *pic_arg = data;
  1085. int i, stuffing_count, context_count = avctx->thread_count;
  1086. for(i=0; i<context_count; i++){
  1087. int start_y= s->thread_context[i]->start_mb_y;
  1088. int end_y= s->thread_context[i]-> end_mb_y;
  1089. int h= s->mb_height;
  1090. uint8_t *start= buf + (size_t)(((int64_t) buf_size)*start_y/h);
  1091. uint8_t *end = buf + (size_t)(((int64_t) buf_size)* end_y/h);
  1092. init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1093. }
  1094. s->picture_in_gop_number++;
  1095. if(load_input_picture(s, pic_arg) < 0)
  1096. return -1;
  1097. if(select_input_picture(s) < 0){
  1098. return -1;
  1099. }
  1100. /* output? */
  1101. if (s->new_picture.f.data[0]) {
  1102. s->pict_type = s->new_picture.f.pict_type;
  1103. //emms_c();
  1104. //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
  1105. MPV_frame_start(s, avctx);
  1106. vbv_retry:
  1107. if (encode_picture(s, s->picture_number) < 0)
  1108. return -1;
  1109. avctx->header_bits = s->header_bits;
  1110. avctx->mv_bits = s->mv_bits;
  1111. avctx->misc_bits = s->misc_bits;
  1112. avctx->i_tex_bits = s->i_tex_bits;
  1113. avctx->p_tex_bits = s->p_tex_bits;
  1114. avctx->i_count = s->i_count;
  1115. avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
  1116. avctx->skip_count = s->skip_count;
  1117. MPV_frame_end(s);
  1118. if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1119. ff_mjpeg_encode_picture_trailer(s);
  1120. if(avctx->rc_buffer_size){
  1121. RateControlContext *rcc= &s->rc_context;
  1122. int max_size= rcc->buffer_index * avctx->rc_max_available_vbv_use;
  1123. if(put_bits_count(&s->pb) > max_size && s->lambda < s->avctx->lmax){
  1124. s->next_lambda= FFMAX(s->lambda+1, s->lambda*(s->qscale+1) / s->qscale);
  1125. if(s->adaptive_quant){
  1126. int i;
  1127. for(i=0; i<s->mb_height*s->mb_stride; i++)
  1128. s->lambda_table[i]= FFMAX(s->lambda_table[i]+1, s->lambda_table[i]*(s->qscale+1) / s->qscale);
  1129. }
  1130. s->mb_skipped = 0; //done in MPV_frame_start()
  1131. if(s->pict_type==AV_PICTURE_TYPE_P){ //done in encode_picture() so we must undo it
  1132. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  1133. s->no_rounding ^= 1;
  1134. }
  1135. if(s->pict_type!=AV_PICTURE_TYPE_B){
  1136. s->time_base= s->last_time_base;
  1137. s->last_non_b_time= s->time - s->pp_time;
  1138. }
  1139. // av_log(NULL, AV_LOG_ERROR, "R:%d ", s->next_lambda);
  1140. for(i=0; i<context_count; i++){
  1141. PutBitContext *pb= &s->thread_context[i]->pb;
  1142. init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1143. }
  1144. goto vbv_retry;
  1145. }
  1146. assert(s->avctx->rc_max_rate);
  1147. }
  1148. if(s->flags&CODEC_FLAG_PASS1)
  1149. ff_write_pass1_stats(s);
  1150. for(i=0; i<4; i++){
  1151. s->current_picture_ptr->f.error[i] = s->current_picture.f.error[i];
  1152. avctx->error[i] += s->current_picture_ptr->f.error[i];
  1153. }
  1154. if(s->flags&CODEC_FLAG_PASS1)
  1155. assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits + avctx->i_tex_bits + avctx->p_tex_bits == put_bits_count(&s->pb));
  1156. flush_put_bits(&s->pb);
  1157. s->frame_bits = put_bits_count(&s->pb);
  1158. stuffing_count= ff_vbv_update(s, s->frame_bits);
  1159. if(stuffing_count){
  1160. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < stuffing_count + 50){
  1161. av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1162. return -1;
  1163. }
  1164. switch(s->codec_id){
  1165. case CODEC_ID_MPEG1VIDEO:
  1166. case CODEC_ID_MPEG2VIDEO:
  1167. while(stuffing_count--){
  1168. put_bits(&s->pb, 8, 0);
  1169. }
  1170. break;
  1171. case CODEC_ID_MPEG4:
  1172. put_bits(&s->pb, 16, 0);
  1173. put_bits(&s->pb, 16, 0x1C3);
  1174. stuffing_count -= 4;
  1175. while(stuffing_count--){
  1176. put_bits(&s->pb, 8, 0xFF);
  1177. }
  1178. break;
  1179. default:
  1180. av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1181. }
  1182. flush_put_bits(&s->pb);
  1183. s->frame_bits = put_bits_count(&s->pb);
  1184. }
  1185. /* update mpeg1/2 vbv_delay for CBR */
  1186. if(s->avctx->rc_max_rate && s->avctx->rc_min_rate == s->avctx->rc_max_rate && s->out_format == FMT_MPEG1
  1187. && 90000LL * (avctx->rc_buffer_size-1) <= s->avctx->rc_max_rate*0xFFFFLL){
  1188. int vbv_delay, min_delay;
  1189. double inbits = s->avctx->rc_max_rate*av_q2d(s->avctx->time_base);
  1190. int minbits= s->frame_bits - 8*(s->vbv_delay_ptr - s->pb.buf - 1);
  1191. double bits = s->rc_context.buffer_index + minbits - inbits;
  1192. if(bits<0)
  1193. av_log(s->avctx, AV_LOG_ERROR, "Internal error, negative bits\n");
  1194. assert(s->repeat_first_field==0);
  1195. vbv_delay= bits * 90000 / s->avctx->rc_max_rate;
  1196. min_delay= (minbits * 90000LL + s->avctx->rc_max_rate - 1)/ s->avctx->rc_max_rate;
  1197. vbv_delay= FFMAX(vbv_delay, min_delay);
  1198. assert(vbv_delay < 0xFFFF);
  1199. s->vbv_delay_ptr[0] &= 0xF8;
  1200. s->vbv_delay_ptr[0] |= vbv_delay>>13;
  1201. s->vbv_delay_ptr[1] = vbv_delay>>5;
  1202. s->vbv_delay_ptr[2] &= 0x07;
  1203. s->vbv_delay_ptr[2] |= vbv_delay<<3;
  1204. avctx->vbv_delay = vbv_delay*300;
  1205. }
  1206. s->total_bits += s->frame_bits;
  1207. avctx->frame_bits = s->frame_bits;
  1208. }else{
  1209. assert((put_bits_ptr(&s->pb) == s->pb.buf));
  1210. s->frame_bits=0;
  1211. }
  1212. assert((s->frame_bits&7)==0);
  1213. return s->frame_bits/8;
  1214. }
  1215. static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
  1216. {
  1217. static const char tab[64]=
  1218. {3,2,2,1,1,1,1,1,
  1219. 1,1,1,1,1,1,1,1,
  1220. 1,1,1,1,1,1,1,1,
  1221. 0,0,0,0,0,0,0,0,
  1222. 0,0,0,0,0,0,0,0,
  1223. 0,0,0,0,0,0,0,0,
  1224. 0,0,0,0,0,0,0,0,
  1225. 0,0,0,0,0,0,0,0};
  1226. int score=0;
  1227. int run=0;
  1228. int i;
  1229. DCTELEM *block= s->block[n];
  1230. const int last_index= s->block_last_index[n];
  1231. int skip_dc;
  1232. if(threshold<0){
  1233. skip_dc=0;
  1234. threshold= -threshold;
  1235. }else
  1236. skip_dc=1;
  1237. /* Are all we could set to zero already zero? */
  1238. if(last_index<=skip_dc - 1) return;
  1239. for(i=0; i<=last_index; i++){
  1240. const int j = s->intra_scantable.permutated[i];
  1241. const int level = FFABS(block[j]);
  1242. if(level==1){
  1243. if(skip_dc && i==0) continue;
  1244. score+= tab[run];
  1245. run=0;
  1246. }else if(level>1){
  1247. return;
  1248. }else{
  1249. run++;
  1250. }
  1251. }
  1252. if(score >= threshold) return;
  1253. for(i=skip_dc; i<=last_index; i++){
  1254. const int j = s->intra_scantable.permutated[i];
  1255. block[j]=0;
  1256. }
  1257. if(block[0]) s->block_last_index[n]= 0;
  1258. else s->block_last_index[n]= -1;
  1259. }
  1260. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
  1261. {
  1262. int i;
  1263. const int maxlevel= s->max_qcoeff;
  1264. const int minlevel= s->min_qcoeff;
  1265. int overflow=0;
  1266. if(s->mb_intra){
  1267. i=1; //skip clipping of intra dc
  1268. }else
  1269. i=0;
  1270. for(;i<=last_index; i++){
  1271. const int j= s->intra_scantable.permutated[i];
  1272. int level = block[j];
  1273. if (level>maxlevel){
  1274. level=maxlevel;
  1275. overflow++;
  1276. }else if(level<minlevel){
  1277. level=minlevel;
  1278. overflow++;
  1279. }
  1280. block[j]= level;
  1281. }
  1282. if(overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  1283. av_log(s->avctx, AV_LOG_INFO, "warning, clipping %d dct coefficients to %d..%d\n", overflow, minlevel, maxlevel);
  1284. }
  1285. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride){
  1286. int x, y;
  1287. //FIXME optimize
  1288. for(y=0; y<8; y++){
  1289. for(x=0; x<8; x++){
  1290. int x2, y2;
  1291. int sum=0;
  1292. int sqr=0;
  1293. int count=0;
  1294. for(y2= FFMAX(y-1, 0); y2 < FFMIN(8, y+2); y2++){
  1295. for(x2= FFMAX(x-1, 0); x2 < FFMIN(8, x+2); x2++){
  1296. int v= ptr[x2 + y2*stride];
  1297. sum += v;
  1298. sqr += v*v;
  1299. count++;
  1300. }
  1301. }
  1302. weight[x + 8*y]= (36*ff_sqrt(count*sqr - sum*sum)) / count;
  1303. }
  1304. }
  1305. }
  1306. static av_always_inline void encode_mb_internal(MpegEncContext *s, int motion_x, int motion_y, int mb_block_height, int mb_block_count)
  1307. {
  1308. int16_t weight[8][64];
  1309. DCTELEM orig[8][64];
  1310. const int mb_x= s->mb_x;
  1311. const int mb_y= s->mb_y;
  1312. int i;
  1313. int skip_dct[8];
  1314. int dct_offset = s->linesize*8; //default for progressive frames
  1315. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  1316. int wrap_y, wrap_c;
  1317. for(i=0; i<mb_block_count; i++) skip_dct[i]=s->skipdct;
  1318. if(s->adaptive_quant){
  1319. const int last_qp= s->qscale;
  1320. const int mb_xy= mb_x + mb_y*s->mb_stride;
  1321. s->lambda= s->lambda_table[mb_xy];
  1322. update_qscale(s);
  1323. if(!(s->flags&CODEC_FLAG_QP_RD)){
  1324. s->qscale = s->current_picture_ptr->f.qscale_table[mb_xy];
  1325. s->dquant= s->qscale - last_qp;
  1326. if(s->out_format==FMT_H263){
  1327. s->dquant= av_clip(s->dquant, -2, 2);
  1328. if(s->codec_id==CODEC_ID_MPEG4){
  1329. if(!s->mb_intra){
  1330. if(s->pict_type == AV_PICTURE_TYPE_B){
  1331. if(s->dquant&1 || s->mv_dir&MV_DIRECT)
  1332. s->dquant= 0;
  1333. }
  1334. if(s->mv_type==MV_TYPE_8X8)
  1335. s->dquant=0;
  1336. }
  1337. }
  1338. }
  1339. }
  1340. ff_set_qscale(s, last_qp + s->dquant);
  1341. }else if(s->flags&CODEC_FLAG_QP_RD)
  1342. ff_set_qscale(s, s->qscale + s->dquant);
  1343. wrap_y = s->linesize;
  1344. wrap_c = s->uvlinesize;
  1345. ptr_y = s->new_picture.f.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  1346. ptr_cb = s->new_picture.f.data[1] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1347. ptr_cr = s->new_picture.f.data[2] + (mb_y * mb_block_height * wrap_c) + mb_x * 8;
  1348. if((mb_x*16+16 > s->width || mb_y*16+16 > s->height) && s->codec_id != CODEC_ID_AMV){
  1349. uint8_t *ebuf= s->edge_emu_buffer + 32;
  1350. s->dsp.emulated_edge_mc(ebuf , ptr_y , wrap_y,16,16,mb_x*16,mb_y*16, s->width , s->height);
  1351. ptr_y= ebuf;
  1352. 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);
  1353. ptr_cb= ebuf+18*wrap_y;
  1354. 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);
  1355. ptr_cr= ebuf+18*wrap_y+8;
  1356. }
  1357. if (s->mb_intra) {
  1358. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1359. int progressive_score, interlaced_score;
  1360. s->interlaced_dct=0;
  1361. progressive_score= s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y, 8)
  1362. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y*8, NULL, wrap_y, 8) - 400;
  1363. if(progressive_score > 0){
  1364. interlaced_score = s->dsp.ildct_cmp[4](s, ptr_y , NULL, wrap_y*2, 8)
  1365. +s->dsp.ildct_cmp[4](s, ptr_y + wrap_y , NULL, wrap_y*2, 8);
  1366. if(progressive_score > interlaced_score){
  1367. s->interlaced_dct=1;
  1368. dct_offset= wrap_y;
  1369. wrap_y<<=1;
  1370. if (s->chroma_format == CHROMA_422)
  1371. wrap_c<<=1;
  1372. }
  1373. }
  1374. }
  1375. s->dsp.get_pixels(s->block[0], ptr_y , wrap_y);
  1376. s->dsp.get_pixels(s->block[1], ptr_y + 8, wrap_y);
  1377. s->dsp.get_pixels(s->block[2], ptr_y + dct_offset , wrap_y);
  1378. s->dsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  1379. if(s->flags&CODEC_FLAG_GRAY){
  1380. skip_dct[4]= 1;
  1381. skip_dct[5]= 1;
  1382. }else{
  1383. s->dsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  1384. s->dsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  1385. if(!s->chroma_y_shift){ /* 422 */
  1386. s->dsp.get_pixels(s->block[6], ptr_cb + (dct_offset>>1), wrap_c);
  1387. s->dsp.get_pixels(s->block[7], ptr_cr + (dct_offset>>1), wrap_c);
  1388. }
  1389. }
  1390. }else{
  1391. op_pixels_func (*op_pix)[4];
  1392. qpel_mc_func (*op_qpix)[16];
  1393. uint8_t *dest_y, *dest_cb, *dest_cr;
  1394. dest_y = s->dest[0];
  1395. dest_cb = s->dest[1];
  1396. dest_cr = s->dest[2];
  1397. if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){
  1398. op_pix = s->dsp.put_pixels_tab;
  1399. op_qpix= s->dsp.put_qpel_pixels_tab;
  1400. }else{
  1401. op_pix = s->dsp.put_no_rnd_pixels_tab;
  1402. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  1403. }
  1404. if (s->mv_dir & MV_DIR_FORWARD) {
  1405. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f.data, op_pix, op_qpix);
  1406. op_pix = s->dsp.avg_pixels_tab;
  1407. op_qpix= s->dsp.avg_qpel_pixels_tab;
  1408. }
  1409. if (s->mv_dir & MV_DIR_BACKWARD) {
  1410. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f.data, op_pix, op_qpix);
  1411. }
  1412. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  1413. int progressive_score, interlaced_score;
  1414. s->interlaced_dct=0;
  1415. progressive_score= s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y, 8)
  1416. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y*8, ptr_y + wrap_y*8, wrap_y, 8) - 400;
  1417. if(s->avctx->ildct_cmp == FF_CMP_VSSE) progressive_score -= 400;
  1418. if(progressive_score>0){
  1419. interlaced_score = s->dsp.ildct_cmp[0](s, dest_y , ptr_y , wrap_y*2, 8)
  1420. +s->dsp.ildct_cmp[0](s, dest_y + wrap_y , ptr_y + wrap_y , wrap_y*2, 8);
  1421. if(progressive_score > interlaced_score){
  1422. s->interlaced_dct=1;
  1423. dct_offset= wrap_y;
  1424. wrap_y<<=1;
  1425. if (s->chroma_format == CHROMA_422)
  1426. wrap_c<<=1;
  1427. }
  1428. }
  1429. }
  1430. s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
  1431. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  1432. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
  1433. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
  1434. if(s->flags&CODEC_FLAG_GRAY){
  1435. skip_dct[4]= 1;
  1436. skip_dct[5]= 1;
  1437. }else{
  1438. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  1439. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  1440. if(!s->chroma_y_shift){ /* 422 */
  1441. s->dsp.diff_pixels(s->block[6], ptr_cb + (dct_offset>>1), dest_cb + (dct_offset>>1), wrap_c);
  1442. s->dsp.diff_pixels(s->block[7], ptr_cr + (dct_offset>>1), dest_cr + (dct_offset>>1), wrap_c);
  1443. }
  1444. }
  1445. /* pre quantization */
  1446. if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
  1447. //FIXME optimize
  1448. if(s->dsp.sad[1](NULL, ptr_y , dest_y , wrap_y, 8) < 20*s->qscale) skip_dct[0]= 1;
  1449. if(s->dsp.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20*s->qscale) skip_dct[1]= 1;
  1450. if(s->dsp.sad[1](NULL, ptr_y +dct_offset , dest_y +dct_offset , wrap_y, 8) < 20*s->qscale) skip_dct[2]= 1;
  1451. 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;
  1452. if(s->dsp.sad[1](NULL, ptr_cb , dest_cb , wrap_c, 8) < 20*s->qscale) skip_dct[4]= 1;
  1453. if(s->dsp.sad[1](NULL, ptr_cr , dest_cr , wrap_c, 8) < 20*s->qscale) skip_dct[5]= 1;
  1454. if(!s->chroma_y_shift){ /* 422 */
  1455. 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;
  1456. 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;
  1457. }
  1458. }
  1459. }
  1460. if(s->avctx->quantizer_noise_shaping){
  1461. if(!skip_dct[0]) get_visual_weight(weight[0], ptr_y , wrap_y);
  1462. if(!skip_dct[1]) get_visual_weight(weight[1], ptr_y + 8, wrap_y);
  1463. if(!skip_dct[2]) get_visual_weight(weight[2], ptr_y + dct_offset , wrap_y);
  1464. if(!skip_dct[3]) get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  1465. if(!skip_dct[4]) get_visual_weight(weight[4], ptr_cb , wrap_c);
  1466. if(!skip_dct[5]) get_visual_weight(weight[5], ptr_cr , wrap_c);
  1467. if(!s->chroma_y_shift){ /* 422 */
  1468. if(!skip_dct[6]) get_visual_weight(weight[6], ptr_cb + (dct_offset>>1), wrap_c);
  1469. if(!skip_dct[7]) get_visual_weight(weight[7], ptr_cr + (dct_offset>>1), wrap_c);
  1470. }
  1471. memcpy(orig[0], s->block[0], sizeof(DCTELEM)*64*mb_block_count);
  1472. }
  1473. /* DCT & quantize */
  1474. assert(s->out_format!=FMT_MJPEG || s->qscale==8);
  1475. {
  1476. for(i=0;i<mb_block_count;i++) {
  1477. if(!skip_dct[i]){
  1478. int overflow;
  1479. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  1480. // FIXME we could decide to change to quantizer instead of clipping
  1481. // JS: I don't think that would be a good idea it could lower quality instead
  1482. // of improve it. Just INTRADC clipping deserves changes in quantizer
  1483. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  1484. }else
  1485. s->block_last_index[i]= -1;
  1486. }
  1487. if(s->avctx->quantizer_noise_shaping){
  1488. for(i=0;i<mb_block_count;i++) {
  1489. if(!skip_dct[i]){
  1490. s->block_last_index[i] = dct_quantize_refine(s, s->block[i], weight[i], orig[i], i, s->qscale);
  1491. }
  1492. }
  1493. }
  1494. if(s->luma_elim_threshold && !s->mb_intra)
  1495. for(i=0; i<4; i++)
  1496. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  1497. if(s->chroma_elim_threshold && !s->mb_intra)
  1498. for(i=4; i<mb_block_count; i++)
  1499. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  1500. if(s->flags & CODEC_FLAG_CBP_RD){
  1501. for(i=0;i<mb_block_count;i++) {
  1502. if(s->block_last_index[i] == -1)
  1503. s->coded_score[i]= INT_MAX/256;
  1504. }
  1505. }
  1506. }
  1507. if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
  1508. s->block_last_index[4]=
  1509. s->block_last_index[5]= 0;
  1510. s->block[4][0]=
  1511. s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
  1512. }
  1513. //non c quantize code returns incorrect block_last_index FIXME
  1514. if(s->alternate_scan && s->dct_quantize != dct_quantize_c){
  1515. for(i=0; i<mb_block_count; i++){
  1516. int j;
  1517. if(s->block_last_index[i]>0){
  1518. for(j=63; j>0; j--){
  1519. if(s->block[i][ s->intra_scantable.permutated[j] ]) break;
  1520. }
  1521. s->block_last_index[i]= j;
  1522. }
  1523. }
  1524. }
  1525. /* huffman encode */
  1526. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  1527. case CODEC_ID_MPEG1VIDEO:
  1528. case CODEC_ID_MPEG2VIDEO:
  1529. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  1530. mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  1531. break;
  1532. case CODEC_ID_MPEG4:
  1533. if (CONFIG_MPEG4_ENCODER)
  1534. mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1535. break;
  1536. case CODEC_ID_MSMPEG4V2:
  1537. case CODEC_ID_MSMPEG4V3:
  1538. case CODEC_ID_WMV1:
  1539. if (CONFIG_MSMPEG4_ENCODER)
  1540. msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  1541. break;
  1542. case CODEC_ID_WMV2:
  1543. if (CONFIG_WMV2_ENCODER)
  1544. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  1545. break;
  1546. case CODEC_ID_H261:
  1547. if (CONFIG_H261_ENCODER)
  1548. ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  1549. break;
  1550. case CODEC_ID_H263:
  1551. case CODEC_ID_H263P:
  1552. case CODEC_ID_FLV1:
  1553. case CODEC_ID_RV10:
  1554. case CODEC_ID_RV20:
  1555. if (CONFIG_H263_ENCODER)
  1556. h263_encode_mb(s, s->block, motion_x, motion_y);
  1557. break;
  1558. case CODEC_ID_MJPEG:
  1559. case CODEC_ID_AMV:
  1560. if (CONFIG_MJPEG_ENCODER)
  1561. ff_mjpeg_encode_mb(s, s->block);
  1562. break;
  1563. default:
  1564. assert(0);
  1565. }
  1566. }
  1567. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  1568. {
  1569. if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y, 8, 6);
  1570. else encode_mb_internal(s, motion_x, motion_y, 16, 8);
  1571. }
  1572. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1573. int i;
  1574. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1575. /* mpeg1 */
  1576. d->mb_skip_run= s->mb_skip_run;
  1577. for(i=0; i<3; i++)
  1578. d->last_dc[i]= s->last_dc[i];
  1579. /* statistics */
  1580. d->mv_bits= s->mv_bits;
  1581. d->i_tex_bits= s->i_tex_bits;
  1582. d->p_tex_bits= s->p_tex_bits;
  1583. d->i_count= s->i_count;
  1584. d->f_count= s->f_count;
  1585. d->b_count= s->b_count;
  1586. d->skip_count= s->skip_count;
  1587. d->misc_bits= s->misc_bits;
  1588. d->last_bits= 0;
  1589. d->mb_skipped= 0;
  1590. d->qscale= s->qscale;
  1591. d->dquant= s->dquant;
  1592. d->esc3_level_length= s->esc3_level_length;
  1593. }
  1594. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  1595. int i;
  1596. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  1597. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  1598. /* mpeg1 */
  1599. d->mb_skip_run= s->mb_skip_run;
  1600. for(i=0; i<3; i++)
  1601. d->last_dc[i]= s->last_dc[i];
  1602. /* statistics */
  1603. d->mv_bits= s->mv_bits;
  1604. d->i_tex_bits= s->i_tex_bits;
  1605. d->p_tex_bits= s->p_tex_bits;
  1606. d->i_count= s->i_count;
  1607. d->f_count= s->f_count;
  1608. d->b_count= s->b_count;
  1609. d->skip_count= s->skip_count;
  1610. d->misc_bits= s->misc_bits;
  1611. d->mb_intra= s->mb_intra;
  1612. d->mb_skipped= s->mb_skipped;
  1613. d->mv_type= s->mv_type;
  1614. d->mv_dir= s->mv_dir;
  1615. d->pb= s->pb;
  1616. if(s->data_partitioning){
  1617. d->pb2= s->pb2;
  1618. d->tex_pb= s->tex_pb;
  1619. }
  1620. d->block= s->block;
  1621. for(i=0; i<8; i++)
  1622. d->block_last_index[i]= s->block_last_index[i];
  1623. d->interlaced_dct= s->interlaced_dct;
  1624. d->qscale= s->qscale;
  1625. d->esc3_level_length= s->esc3_level_length;
  1626. }
  1627. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  1628. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  1629. int *dmin, int *next_block, int motion_x, int motion_y)
  1630. {
  1631. int score;
  1632. uint8_t *dest_backup[3];
  1633. copy_context_before_encode(s, backup, type);
  1634. s->block= s->blocks[*next_block];
  1635. s->pb= pb[*next_block];
  1636. if(s->data_partitioning){
  1637. s->pb2 = pb2 [*next_block];
  1638. s->tex_pb= tex_pb[*next_block];
  1639. }
  1640. if(*next_block){
  1641. memcpy(dest_backup, s->dest, sizeof(s->dest));
  1642. s->dest[0] = s->rd_scratchpad;
  1643. s->dest[1] = s->rd_scratchpad + 16*s->linesize;
  1644. s->dest[2] = s->rd_scratchpad + 16*s->linesize + 8;
  1645. assert(s->linesize >= 32); //FIXME
  1646. }
  1647. encode_mb(s, motion_x, motion_y);
  1648. score= put_bits_count(&s->pb);
  1649. if(s->data_partitioning){
  1650. score+= put_bits_count(&s->pb2);
  1651. score+= put_bits_count(&s->tex_pb);
  1652. }
  1653. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  1654. MPV_decode_mb(s, s->block);
  1655. score *= s->lambda2;
  1656. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  1657. }
  1658. if(*next_block){
  1659. memcpy(s->dest, dest_backup, sizeof(s->dest));
  1660. }
  1661. if(score<*dmin){
  1662. *dmin= score;
  1663. *next_block^=1;
  1664. copy_context_after_encode(best, s, type);
  1665. }
  1666. }
  1667. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  1668. uint32_t *sq = ff_squareTbl + 256;
  1669. int acc=0;
  1670. int x,y;
  1671. if(w==16 && h==16)
  1672. return s->dsp.sse[0](NULL, src1, src2, stride, 16);
  1673. else if(w==8 && h==8)
  1674. return s->dsp.sse[1](NULL, src1, src2, stride, 8);
  1675. for(y=0; y<h; y++){
  1676. for(x=0; x<w; x++){
  1677. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  1678. }
  1679. }
  1680. assert(acc>=0);
  1681. return acc;
  1682. }
  1683. static int sse_mb(MpegEncContext *s){
  1684. int w= 16;
  1685. int h= 16;
  1686. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  1687. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  1688. if(w==16 && h==16)
  1689. if(s->avctx->mb_cmp == FF_CMP_NSSE){
  1690. 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)
  1691. +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)
  1692. +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);
  1693. }else{
  1694. 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)
  1695. +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)
  1696. +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);
  1697. }
  1698. else
  1699. 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)
  1700. +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)
  1701. +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);
  1702. }
  1703. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  1704. MpegEncContext *s= *(void**)arg;
  1705. s->me.pre_pass=1;
  1706. s->me.dia_size= s->avctx->pre_dia_size;
  1707. s->first_slice_line=1;
  1708. for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  1709. for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  1710. ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1711. }
  1712. s->first_slice_line=0;
  1713. }
  1714. s->me.pre_pass=0;
  1715. return 0;
  1716. }
  1717. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  1718. MpegEncContext *s= *(void**)arg;
  1719. ff_check_alignment();
  1720. s->me.dia_size= s->avctx->dia_size;
  1721. s->first_slice_line=1;
  1722. for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  1723. s->mb_x=0; //for block init below
  1724. ff_init_block_index(s);
  1725. for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  1726. s->block_index[0]+=2;
  1727. s->block_index[1]+=2;
  1728. s->block_index[2]+=2;
  1729. s->block_index[3]+=2;
  1730. /* compute motion vector & mb_type and store in context */
  1731. if(s->pict_type==AV_PICTURE_TYPE_B)
  1732. ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  1733. else
  1734. ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  1735. }
  1736. s->first_slice_line=0;
  1737. }
  1738. return 0;
  1739. }
  1740. static int mb_var_thread(AVCodecContext *c, void *arg){
  1741. MpegEncContext *s= *(void**)arg;
  1742. int mb_x, mb_y;
  1743. ff_check_alignment();
  1744. for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1745. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1746. int xx = mb_x * 16;
  1747. int yy = mb_y * 16;
  1748. uint8_t *pix = s->new_picture.f.data[0] + (yy * s->linesize) + xx;
  1749. int varc;
  1750. int sum = s->dsp.pix_sum(pix, s->linesize);
  1751. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500 + 128)>>8;
  1752. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  1753. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  1754. s->me.mb_var_sum_temp += varc;
  1755. }
  1756. }
  1757. return 0;
  1758. }
  1759. static void write_slice_end(MpegEncContext *s){
  1760. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4){
  1761. if(s->partitioned_frame){
  1762. ff_mpeg4_merge_partitions(s);
  1763. }
  1764. ff_mpeg4_stuffing(&s->pb);
  1765. }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  1766. ff_mjpeg_encode_stuffing(&s->pb);
  1767. }
  1768. avpriv_align_put_bits(&s->pb);
  1769. flush_put_bits(&s->pb);
  1770. if((s->flags&CODEC_FLAG_PASS1) && !s->partitioned_frame)
  1771. s->misc_bits+= get_bits_diff(s);
  1772. }
  1773. static int encode_thread(AVCodecContext *c, void *arg){
  1774. MpegEncContext *s= *(void**)arg;
  1775. int mb_x, mb_y, pdif = 0;
  1776. int chr_h= 16>>s->chroma_y_shift;
  1777. int i, j;
  1778. MpegEncContext best_s, backup_s;
  1779. uint8_t bit_buf[2][MAX_MB_BYTES];
  1780. uint8_t bit_buf2[2][MAX_MB_BYTES];
  1781. uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  1782. PutBitContext pb[2], pb2[2], tex_pb[2];
  1783. //printf("%d->%d\n", s->resync_mb_y, s->end_mb_y);
  1784. ff_check_alignment();
  1785. for(i=0; i<2; i++){
  1786. init_put_bits(&pb [i], bit_buf [i], MAX_MB_BYTES);
  1787. init_put_bits(&pb2 [i], bit_buf2 [i], MAX_MB_BYTES);
  1788. init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  1789. }
  1790. s->last_bits= put_bits_count(&s->pb);
  1791. s->mv_bits=0;
  1792. s->misc_bits=0;
  1793. s->i_tex_bits=0;
  1794. s->p_tex_bits=0;
  1795. s->i_count=0;
  1796. s->f_count=0;
  1797. s->b_count=0;
  1798. s->skip_count=0;
  1799. for(i=0; i<3; i++){
  1800. /* init last dc values */
  1801. /* note: quant matrix value (8) is implied here */
  1802. s->last_dc[i] = 128 << s->intra_dc_precision;
  1803. s->current_picture.f.error[i] = 0;
  1804. }
  1805. if(s->codec_id==CODEC_ID_AMV){
  1806. s->last_dc[0] = 128*8/13;
  1807. s->last_dc[1] = 128*8/14;
  1808. s->last_dc[2] = 128*8/14;
  1809. }
  1810. s->mb_skip_run = 0;
  1811. memset(s->last_mv, 0, sizeof(s->last_mv));
  1812. s->last_mv_dir = 0;
  1813. switch(s->codec_id){
  1814. case CODEC_ID_H263:
  1815. case CODEC_ID_H263P:
  1816. case CODEC_ID_FLV1:
  1817. if (CONFIG_H263_ENCODER)
  1818. s->gob_index = ff_h263_get_gob_height(s);
  1819. break;
  1820. case CODEC_ID_MPEG4:
  1821. if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  1822. ff_mpeg4_init_partitions(s);
  1823. break;
  1824. }
  1825. s->resync_mb_x=0;
  1826. s->resync_mb_y=0;
  1827. s->first_slice_line = 1;
  1828. s->ptr_lastgob = s->pb.buf;
  1829. for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  1830. // printf("row %d at %X\n", s->mb_y, (int)s);
  1831. s->mb_x=0;
  1832. s->mb_y= mb_y;
  1833. ff_set_qscale(s, s->qscale);
  1834. ff_init_block_index(s);
  1835. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  1836. int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  1837. int mb_type= s->mb_type[xy];
  1838. // int d;
  1839. int dmin= INT_MAX;
  1840. int dir;
  1841. if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  1842. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1843. return -1;
  1844. }
  1845. if(s->data_partitioning){
  1846. if( s->pb2 .buf_end - s->pb2 .buf - (put_bits_count(&s-> pb2)>>3) < MAX_MB_BYTES
  1847. || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  1848. av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  1849. return -1;
  1850. }
  1851. }
  1852. s->mb_x = mb_x;
  1853. s->mb_y = mb_y; // moved into loop, can get changed by H.261
  1854. ff_update_block_index(s);
  1855. if(CONFIG_H261_ENCODER && s->codec_id == CODEC_ID_H261){
  1856. ff_h261_reorder_mb_index(s);
  1857. xy= s->mb_y*s->mb_stride + s->mb_x;
  1858. mb_type= s->mb_type[xy];
  1859. }
  1860. /* write gob / video packet header */
  1861. if(s->rtp_mode){
  1862. int current_packet_size, is_gob_start;
  1863. current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  1864. is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  1865. if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  1866. switch(s->codec_id){
  1867. case CODEC_ID_H263:
  1868. case CODEC_ID_H263P:
  1869. if(!s->h263_slice_structured)
  1870. if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  1871. break;
  1872. case CODEC_ID_MPEG2VIDEO:
  1873. if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  1874. case CODEC_ID_MPEG1VIDEO:
  1875. if(s->mb_skip_run) is_gob_start=0;
  1876. break;
  1877. }
  1878. if(is_gob_start){
  1879. if(s->start_mb_y != mb_y || mb_x!=0){
  1880. write_slice_end(s);
  1881. if(CONFIG_MPEG4_ENCODER && s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame){
  1882. ff_mpeg4_init_partitions(s);
  1883. }
  1884. }
  1885. assert((put_bits_count(&s->pb)&7) == 0);
  1886. current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  1887. if(s->avctx->error_rate && s->resync_mb_x + s->resync_mb_y > 0){
  1888. int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  1889. int d= 100 / s->avctx->error_rate;
  1890. if(r % d == 0){
  1891. current_packet_size=0;
  1892. s->pb.buf_ptr= s->ptr_lastgob;
  1893. assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  1894. }
  1895. }
  1896. if (s->avctx->rtp_callback){
  1897. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  1898. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  1899. }
  1900. switch(s->codec_id){
  1901. case CODEC_ID_MPEG4:
  1902. if (CONFIG_MPEG4_ENCODER) {
  1903. ff_mpeg4_encode_video_packet_header(s);
  1904. ff_mpeg4_clean_buffers(s);
  1905. }
  1906. break;
  1907. case CODEC_ID_MPEG1VIDEO:
  1908. case CODEC_ID_MPEG2VIDEO:
  1909. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  1910. ff_mpeg1_encode_slice_header(s);
  1911. ff_mpeg1_clean_buffers(s);
  1912. }
  1913. break;
  1914. case CODEC_ID_H263:
  1915. case CODEC_ID_H263P:
  1916. if (CONFIG_H263_ENCODER)
  1917. h263_encode_gob_header(s, mb_y);
  1918. break;
  1919. }
  1920. if(s->flags&CODEC_FLAG_PASS1){
  1921. int bits= put_bits_count(&s->pb);
  1922. s->misc_bits+= bits - s->last_bits;
  1923. s->last_bits= bits;
  1924. }
  1925. s->ptr_lastgob += current_packet_size;
  1926. s->first_slice_line=1;
  1927. s->resync_mb_x=mb_x;
  1928. s->resync_mb_y=mb_y;
  1929. }
  1930. }
  1931. if( (s->resync_mb_x == s->mb_x)
  1932. && s->resync_mb_y+1 == s->mb_y){
  1933. s->first_slice_line=0;
  1934. }
  1935. s->mb_skipped=0;
  1936. s->dquant=0; //only for QP_RD
  1937. if(mb_type & (mb_type-1) || (s->flags & CODEC_FLAG_QP_RD)){ // more than 1 MB type possible or CODEC_FLAG_QP_RD
  1938. int next_block=0;
  1939. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  1940. copy_context_before_encode(&backup_s, s, -1);
  1941. backup_s.pb= s->pb;
  1942. best_s.data_partitioning= s->data_partitioning;
  1943. best_s.partitioned_frame= s->partitioned_frame;
  1944. if(s->data_partitioning){
  1945. backup_s.pb2= s->pb2;
  1946. backup_s.tex_pb= s->tex_pb;
  1947. }
  1948. if(mb_type&CANDIDATE_MB_TYPE_INTER){
  1949. s->mv_dir = MV_DIR_FORWARD;
  1950. s->mv_type = MV_TYPE_16X16;
  1951. s->mb_intra= 0;
  1952. s->mv[0][0][0] = s->p_mv_table[xy][0];
  1953. s->mv[0][0][1] = s->p_mv_table[xy][1];
  1954. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  1955. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1956. }
  1957. if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  1958. s->mv_dir = MV_DIR_FORWARD;
  1959. s->mv_type = MV_TYPE_FIELD;
  1960. s->mb_intra= 0;
  1961. for(i=0; i<2; i++){
  1962. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  1963. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  1964. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  1965. }
  1966. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  1967. &dmin, &next_block, 0, 0);
  1968. }
  1969. if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  1970. s->mv_dir = MV_DIR_FORWARD;
  1971. s->mv_type = MV_TYPE_16X16;
  1972. s->mb_intra= 0;
  1973. s->mv[0][0][0] = 0;
  1974. s->mv[0][0][1] = 0;
  1975. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  1976. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1977. }
  1978. if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  1979. s->mv_dir = MV_DIR_FORWARD;
  1980. s->mv_type = MV_TYPE_8X8;
  1981. s->mb_intra= 0;
  1982. for(i=0; i<4; i++){
  1983. s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
  1984. s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
  1985. }
  1986. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  1987. &dmin, &next_block, 0, 0);
  1988. }
  1989. if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  1990. s->mv_dir = MV_DIR_FORWARD;
  1991. s->mv_type = MV_TYPE_16X16;
  1992. s->mb_intra= 0;
  1993. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  1994. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  1995. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  1996. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  1997. }
  1998. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  1999. s->mv_dir = MV_DIR_BACKWARD;
  2000. s->mv_type = MV_TYPE_16X16;
  2001. s->mb_intra= 0;
  2002. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2003. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2004. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  2005. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  2006. }
  2007. if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  2008. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2009. s->mv_type = MV_TYPE_16X16;
  2010. s->mb_intra= 0;
  2011. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2012. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2013. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2014. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2015. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  2016. &dmin, &next_block, 0, 0);
  2017. }
  2018. if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  2019. s->mv_dir = MV_DIR_FORWARD;
  2020. s->mv_type = MV_TYPE_FIELD;
  2021. s->mb_intra= 0;
  2022. for(i=0; i<2; i++){
  2023. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2024. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2025. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2026. }
  2027. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  2028. &dmin, &next_block, 0, 0);
  2029. }
  2030. if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  2031. s->mv_dir = MV_DIR_BACKWARD;
  2032. s->mv_type = MV_TYPE_FIELD;
  2033. s->mb_intra= 0;
  2034. for(i=0; i<2; i++){
  2035. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2036. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2037. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2038. }
  2039. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  2040. &dmin, &next_block, 0, 0);
  2041. }
  2042. if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  2043. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2044. s->mv_type = MV_TYPE_FIELD;
  2045. s->mb_intra= 0;
  2046. for(dir=0; dir<2; dir++){
  2047. for(i=0; i<2; i++){
  2048. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2049. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2050. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2051. }
  2052. }
  2053. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  2054. &dmin, &next_block, 0, 0);
  2055. }
  2056. if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  2057. s->mv_dir = 0;
  2058. s->mv_type = MV_TYPE_16X16;
  2059. s->mb_intra= 1;
  2060. s->mv[0][0][0] = 0;
  2061. s->mv[0][0][1] = 0;
  2062. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  2063. &dmin, &next_block, 0, 0);
  2064. if(s->h263_pred || s->h263_aic){
  2065. if(best_s.mb_intra)
  2066. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  2067. else
  2068. ff_clean_intra_table_entries(s); //old mode?
  2069. }
  2070. }
  2071. if((s->flags & CODEC_FLAG_QP_RD) && dmin < INT_MAX){
  2072. if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  2073. const int last_qp= backup_s.qscale;
  2074. int qpi, qp, dc[6];
  2075. DCTELEM ac[6][16];
  2076. const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  2077. static const int dquant_tab[4]={-1,1,-2,2};
  2078. assert(backup_s.dquant == 0);
  2079. //FIXME intra
  2080. s->mv_dir= best_s.mv_dir;
  2081. s->mv_type = MV_TYPE_16X16;
  2082. s->mb_intra= best_s.mb_intra;
  2083. s->mv[0][0][0] = best_s.mv[0][0][0];
  2084. s->mv[0][0][1] = best_s.mv[0][0][1];
  2085. s->mv[1][0][0] = best_s.mv[1][0][0];
  2086. s->mv[1][0][1] = best_s.mv[1][0][1];
  2087. qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
  2088. for(; qpi<4; qpi++){
  2089. int dquant= dquant_tab[qpi];
  2090. qp= last_qp + dquant;
  2091. if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  2092. continue;
  2093. backup_s.dquant= dquant;
  2094. if(s->mb_intra && s->dc_val[0]){
  2095. for(i=0; i<6; i++){
  2096. dc[i]= s->dc_val[0][ s->block_index[i] ];
  2097. memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(DCTELEM)*16);
  2098. }
  2099. }
  2100. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2101. &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  2102. if(best_s.qscale != qp){
  2103. if(s->mb_intra && s->dc_val[0]){
  2104. for(i=0; i<6; i++){
  2105. s->dc_val[0][ s->block_index[i] ]= dc[i];
  2106. memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(DCTELEM)*16);
  2107. }
  2108. }
  2109. }
  2110. }
  2111. }
  2112. }
  2113. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  2114. int mx= s->b_direct_mv_table[xy][0];
  2115. int my= s->b_direct_mv_table[xy][1];
  2116. backup_s.dquant = 0;
  2117. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2118. s->mb_intra= 0;
  2119. ff_mpeg4_set_direct_mv(s, mx, my);
  2120. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2121. &dmin, &next_block, mx, my);
  2122. }
  2123. if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  2124. backup_s.dquant = 0;
  2125. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  2126. s->mb_intra= 0;
  2127. ff_mpeg4_set_direct_mv(s, 0, 0);
  2128. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  2129. &dmin, &next_block, 0, 0);
  2130. }
  2131. if(!best_s.mb_intra && s->flags2&CODEC_FLAG2_SKIP_RD){
  2132. int coded=0;
  2133. for(i=0; i<6; i++)
  2134. coded |= s->block_last_index[i];
  2135. if(coded){
  2136. int mx,my;
  2137. memcpy(s->mv, best_s.mv, sizeof(s->mv));
  2138. if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  2139. mx=my=0; //FIXME find the one we actually used
  2140. ff_mpeg4_set_direct_mv(s, mx, my);
  2141. }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  2142. mx= s->mv[1][0][0];
  2143. my= s->mv[1][0][1];
  2144. }else{
  2145. mx= s->mv[0][0][0];
  2146. my= s->mv[0][0][1];
  2147. }
  2148. s->mv_dir= best_s.mv_dir;
  2149. s->mv_type = best_s.mv_type;
  2150. s->mb_intra= 0;
  2151. /* s->mv[0][0][0] = best_s.mv[0][0][0];
  2152. s->mv[0][0][1] = best_s.mv[0][0][1];
  2153. s->mv[1][0][0] = best_s.mv[1][0][0];
  2154. s->mv[1][0][1] = best_s.mv[1][0][1];*/
  2155. backup_s.dquant= 0;
  2156. s->skipdct=1;
  2157. encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  2158. &dmin, &next_block, mx, my);
  2159. s->skipdct=0;
  2160. }
  2161. }
  2162. s->current_picture.f.qscale_table[xy] = best_s.qscale;
  2163. copy_context_after_encode(s, &best_s, -1);
  2164. pb_bits_count= put_bits_count(&s->pb);
  2165. flush_put_bits(&s->pb);
  2166. avpriv_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  2167. s->pb= backup_s.pb;
  2168. if(s->data_partitioning){
  2169. pb2_bits_count= put_bits_count(&s->pb2);
  2170. flush_put_bits(&s->pb2);
  2171. avpriv_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  2172. s->pb2= backup_s.pb2;
  2173. tex_pb_bits_count= put_bits_count(&s->tex_pb);
  2174. flush_put_bits(&s->tex_pb);
  2175. avpriv_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  2176. s->tex_pb= backup_s.tex_pb;
  2177. }
  2178. s->last_bits= put_bits_count(&s->pb);
  2179. if (CONFIG_H263_ENCODER &&
  2180. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2181. ff_h263_update_motion_val(s);
  2182. if(next_block==0){ //FIXME 16 vs linesize16
  2183. s->dsp.put_pixels_tab[0][0](s->dest[0], s->rd_scratchpad , s->linesize ,16);
  2184. s->dsp.put_pixels_tab[1][0](s->dest[1], s->rd_scratchpad + 16*s->linesize , s->uvlinesize, 8);
  2185. s->dsp.put_pixels_tab[1][0](s->dest[2], s->rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  2186. }
  2187. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  2188. MPV_decode_mb(s, s->block);
  2189. } else {
  2190. int motion_x = 0, motion_y = 0;
  2191. s->mv_type=MV_TYPE_16X16;
  2192. // only one MB-Type possible
  2193. switch(mb_type){
  2194. case CANDIDATE_MB_TYPE_INTRA:
  2195. s->mv_dir = 0;
  2196. s->mb_intra= 1;
  2197. motion_x= s->mv[0][0][0] = 0;
  2198. motion_y= s->mv[0][0][1] = 0;
  2199. break;
  2200. case CANDIDATE_MB_TYPE_INTER:
  2201. s->mv_dir = MV_DIR_FORWARD;
  2202. s->mb_intra= 0;
  2203. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  2204. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  2205. break;
  2206. case CANDIDATE_MB_TYPE_INTER_I:
  2207. s->mv_dir = MV_DIR_FORWARD;
  2208. s->mv_type = MV_TYPE_FIELD;
  2209. s->mb_intra= 0;
  2210. for(i=0; i<2; i++){
  2211. j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  2212. s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  2213. s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  2214. }
  2215. break;
  2216. case CANDIDATE_MB_TYPE_INTER4V:
  2217. s->mv_dir = MV_DIR_FORWARD;
  2218. s->mv_type = MV_TYPE_8X8;
  2219. s->mb_intra= 0;
  2220. for(i=0; i<4; i++){
  2221. s->mv[0][i][0] = s->current_picture.f.motion_val[0][s->block_index[i]][0];
  2222. s->mv[0][i][1] = s->current_picture.f.motion_val[0][s->block_index[i]][1];
  2223. }
  2224. break;
  2225. case CANDIDATE_MB_TYPE_DIRECT:
  2226. if (CONFIG_MPEG4_ENCODER) {
  2227. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2228. s->mb_intra= 0;
  2229. motion_x=s->b_direct_mv_table[xy][0];
  2230. motion_y=s->b_direct_mv_table[xy][1];
  2231. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  2232. }
  2233. break;
  2234. case CANDIDATE_MB_TYPE_DIRECT0:
  2235. if (CONFIG_MPEG4_ENCODER) {
  2236. s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  2237. s->mb_intra= 0;
  2238. ff_mpeg4_set_direct_mv(s, 0, 0);
  2239. }
  2240. break;
  2241. case CANDIDATE_MB_TYPE_BIDIR:
  2242. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2243. s->mb_intra= 0;
  2244. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  2245. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  2246. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  2247. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  2248. break;
  2249. case CANDIDATE_MB_TYPE_BACKWARD:
  2250. s->mv_dir = MV_DIR_BACKWARD;
  2251. s->mb_intra= 0;
  2252. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  2253. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  2254. break;
  2255. case CANDIDATE_MB_TYPE_FORWARD:
  2256. s->mv_dir = MV_DIR_FORWARD;
  2257. s->mb_intra= 0;
  2258. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  2259. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  2260. // printf(" %d %d ", motion_x, motion_y);
  2261. break;
  2262. case CANDIDATE_MB_TYPE_FORWARD_I:
  2263. s->mv_dir = MV_DIR_FORWARD;
  2264. s->mv_type = MV_TYPE_FIELD;
  2265. s->mb_intra= 0;
  2266. for(i=0; i<2; i++){
  2267. j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  2268. s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  2269. s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  2270. }
  2271. break;
  2272. case CANDIDATE_MB_TYPE_BACKWARD_I:
  2273. s->mv_dir = MV_DIR_BACKWARD;
  2274. s->mv_type = MV_TYPE_FIELD;
  2275. s->mb_intra= 0;
  2276. for(i=0; i<2; i++){
  2277. j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  2278. s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  2279. s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  2280. }
  2281. break;
  2282. case CANDIDATE_MB_TYPE_BIDIR_I:
  2283. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  2284. s->mv_type = MV_TYPE_FIELD;
  2285. s->mb_intra= 0;
  2286. for(dir=0; dir<2; dir++){
  2287. for(i=0; i<2; i++){
  2288. j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  2289. s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  2290. s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  2291. }
  2292. }
  2293. break;
  2294. default:
  2295. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  2296. }
  2297. encode_mb(s, motion_x, motion_y);
  2298. // RAL: Update last macroblock type
  2299. s->last_mv_dir = s->mv_dir;
  2300. if (CONFIG_H263_ENCODER &&
  2301. s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  2302. ff_h263_update_motion_val(s);
  2303. MPV_decode_mb(s, s->block);
  2304. }
  2305. /* clean the MV table in IPS frames for direct mode in B frames */
  2306. if(s->mb_intra /* && I,P,S_TYPE */){
  2307. s->p_mv_table[xy][0]=0;
  2308. s->p_mv_table[xy][1]=0;
  2309. }
  2310. if(s->flags&CODEC_FLAG_PSNR){
  2311. int w= 16;
  2312. int h= 16;
  2313. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2314. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2315. s->current_picture.f.error[0] += sse(
  2316. s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  2317. s->dest[0], w, h, s->linesize);
  2318. s->current_picture.f.error[1] += sse(
  2319. s, s->new_picture.f.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2320. s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2321. s->current_picture.f.error[2] += sse(
  2322. s, s->new_picture.f.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*chr_h,
  2323. s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  2324. }
  2325. if(s->loop_filter){
  2326. if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  2327. ff_h263_loop_filter(s);
  2328. }
  2329. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, put_bits_count(&s->pb));
  2330. }
  2331. }
  2332. //not beautiful here but we must write it before flushing so it has to be here
  2333. if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
  2334. msmpeg4_encode_ext_header(s);
  2335. write_slice_end(s);
  2336. /* Send the last GOB if RTP */
  2337. if (s->avctx->rtp_callback) {
  2338. int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  2339. pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2340. /* Call the RTP callback to send the last GOB */
  2341. emms_c();
  2342. s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  2343. }
  2344. return 0;
  2345. }
  2346. #define MERGE(field) dst->field += src->field; src->field=0
  2347. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  2348. MERGE(me.scene_change_score);
  2349. MERGE(me.mc_mb_var_sum_temp);
  2350. MERGE(me.mb_var_sum_temp);
  2351. }
  2352. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  2353. int i;
  2354. MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  2355. MERGE(dct_count[1]);
  2356. MERGE(mv_bits);
  2357. MERGE(i_tex_bits);
  2358. MERGE(p_tex_bits);
  2359. MERGE(i_count);
  2360. MERGE(f_count);
  2361. MERGE(b_count);
  2362. MERGE(skip_count);
  2363. MERGE(misc_bits);
  2364. MERGE(error_count);
  2365. MERGE(padding_bug_score);
  2366. MERGE(current_picture.f.error[0]);
  2367. MERGE(current_picture.f.error[1]);
  2368. MERGE(current_picture.f.error[2]);
  2369. if(dst->avctx->noise_reduction){
  2370. for(i=0; i<64; i++){
  2371. MERGE(dct_error_sum[0][i]);
  2372. MERGE(dct_error_sum[1][i]);
  2373. }
  2374. }
  2375. assert(put_bits_count(&src->pb) % 8 ==0);
  2376. assert(put_bits_count(&dst->pb) % 8 ==0);
  2377. avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  2378. flush_put_bits(&dst->pb);
  2379. }
  2380. static int estimate_qp(MpegEncContext *s, int dry_run){
  2381. if (s->next_lambda){
  2382. s->current_picture_ptr->f.quality =
  2383. s->current_picture.f.quality = s->next_lambda;
  2384. if(!dry_run) s->next_lambda= 0;
  2385. } else if (!s->fixed_qscale) {
  2386. s->current_picture_ptr->f.quality =
  2387. s->current_picture.f.quality = ff_rate_estimate_qscale(s, dry_run);
  2388. if (s->current_picture.f.quality < 0)
  2389. return -1;
  2390. }
  2391. if(s->adaptive_quant){
  2392. switch(s->codec_id){
  2393. case CODEC_ID_MPEG4:
  2394. if (CONFIG_MPEG4_ENCODER)
  2395. ff_clean_mpeg4_qscales(s);
  2396. break;
  2397. case CODEC_ID_H263:
  2398. case CODEC_ID_H263P:
  2399. case CODEC_ID_FLV1:
  2400. if (CONFIG_H263_ENCODER)
  2401. ff_clean_h263_qscales(s);
  2402. break;
  2403. default:
  2404. ff_init_qscale_tab(s);
  2405. }
  2406. s->lambda= s->lambda_table[0];
  2407. //FIXME broken
  2408. }else
  2409. s->lambda = s->current_picture.f.quality;
  2410. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  2411. update_qscale(s);
  2412. return 0;
  2413. }
  2414. /* must be called before writing the header */
  2415. static void set_frame_distances(MpegEncContext * s){
  2416. assert(s->current_picture_ptr->f.pts != AV_NOPTS_VALUE);
  2417. s->time = s->current_picture_ptr->f.pts * s->avctx->time_base.num;
  2418. if(s->pict_type==AV_PICTURE_TYPE_B){
  2419. s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  2420. assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  2421. }else{
  2422. s->pp_time= s->time - s->last_non_b_time;
  2423. s->last_non_b_time= s->time;
  2424. assert(s->picture_number==0 || s->pp_time > 0);
  2425. }
  2426. }
  2427. static int encode_picture(MpegEncContext *s, int picture_number)
  2428. {
  2429. int i;
  2430. int bits;
  2431. int context_count = s->avctx->thread_count;
  2432. s->picture_number = picture_number;
  2433. /* Reset the average MB variance */
  2434. s->me.mb_var_sum_temp =
  2435. s->me.mc_mb_var_sum_temp = 0;
  2436. /* we need to initialize some time vars before we can encode b-frames */
  2437. // RAL: Condition added for MPEG1VIDEO
  2438. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
  2439. set_frame_distances(s);
  2440. if(CONFIG_MPEG4_ENCODER && s->codec_id == CODEC_ID_MPEG4)
  2441. ff_set_mpeg4_time(s);
  2442. s->me.scene_change_score=0;
  2443. // s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  2444. if(s->pict_type==AV_PICTURE_TYPE_I){
  2445. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2446. else s->no_rounding=0;
  2447. }else if(s->pict_type!=AV_PICTURE_TYPE_B){
  2448. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2449. s->no_rounding ^= 1;
  2450. }
  2451. if(s->flags & CODEC_FLAG_PASS2){
  2452. if (estimate_qp(s,1) < 0)
  2453. return -1;
  2454. ff_get_2pass_fcode(s);
  2455. }else if(!(s->flags & CODEC_FLAG_QSCALE)){
  2456. if(s->pict_type==AV_PICTURE_TYPE_B)
  2457. s->lambda= s->last_lambda_for[s->pict_type];
  2458. else
  2459. s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  2460. update_qscale(s);
  2461. }
  2462. if(s->codec_id != CODEC_ID_AMV){
  2463. if(s->q_chroma_intra_matrix != s->q_intra_matrix ) av_freep(&s->q_chroma_intra_matrix);
  2464. if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
  2465. s->q_chroma_intra_matrix = s->q_intra_matrix;
  2466. s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
  2467. }
  2468. s->mb_intra=0; //for the rate distortion & bit compare functions
  2469. for(i=1; i<context_count; i++){
  2470. ff_update_duplicate_context(s->thread_context[i], s);
  2471. }
  2472. if(ff_init_me(s)<0)
  2473. return -1;
  2474. /* Estimate motion for every MB */
  2475. if(s->pict_type != AV_PICTURE_TYPE_I){
  2476. s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  2477. s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  2478. if(s->pict_type != AV_PICTURE_TYPE_B && s->avctx->me_threshold==0){
  2479. if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
  2480. s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2481. }
  2482. }
  2483. s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2484. }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
  2485. /* I-Frame */
  2486. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2487. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2488. if(!s->fixed_qscale){
  2489. /* finding spatial complexity for I-frame rate control */
  2490. s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2491. }
  2492. }
  2493. for(i=1; i<context_count; i++){
  2494. merge_context_after_me(s, s->thread_context[i]);
  2495. }
  2496. s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  2497. s->current_picture. mb_var_sum= s->current_picture_ptr-> mb_var_sum= s->me. mb_var_sum_temp;
  2498. emms_c();
  2499. if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
  2500. s->pict_type= AV_PICTURE_TYPE_I;
  2501. for(i=0; i<s->mb_stride*s->mb_height; i++)
  2502. s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  2503. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2504. }
  2505. if(!s->umvplus){
  2506. if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
  2507. s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  2508. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2509. int a,b;
  2510. a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  2511. b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  2512. s->f_code= FFMAX3(s->f_code, a, b);
  2513. }
  2514. ff_fix_long_p_mvs(s);
  2515. ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  2516. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2517. int j;
  2518. for(i=0; i<2; i++){
  2519. for(j=0; j<2; j++)
  2520. ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  2521. s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  2522. }
  2523. }
  2524. }
  2525. if(s->pict_type==AV_PICTURE_TYPE_B){
  2526. int a, b;
  2527. a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  2528. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2529. s->f_code = FFMAX(a, b);
  2530. a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  2531. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  2532. s->b_code = FFMAX(a, b);
  2533. ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  2534. ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  2535. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2536. ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  2537. if(s->flags & CODEC_FLAG_INTERLACED_ME){
  2538. int dir, j;
  2539. for(dir=0; dir<2; dir++){
  2540. for(i=0; i<2; i++){
  2541. for(j=0; j<2; j++){
  2542. int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  2543. : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  2544. ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  2545. s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  2546. }
  2547. }
  2548. }
  2549. }
  2550. }
  2551. }
  2552. if (estimate_qp(s, 0) < 0)
  2553. return -1;
  2554. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))
  2555. s->qscale= 3; //reduce clipping problems
  2556. if (s->out_format == FMT_MJPEG) {
  2557. /* for mjpeg, we do include qscale in the matrix */
  2558. for(i=1;i<64;i++){
  2559. int j= s->dsp.idct_permutation[i];
  2560. s->intra_matrix[j] = av_clip_uint8((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  2561. }
  2562. s->y_dc_scale_table=
  2563. s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
  2564. s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
  2565. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2566. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2567. s->qscale= 8;
  2568. }
  2569. if(s->codec_id == CODEC_ID_AMV){
  2570. 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};
  2571. 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};
  2572. for(i=1;i<64;i++){
  2573. int j= s->dsp.idct_permutation[ff_zigzag_direct[i]];
  2574. s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];
  2575. s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];
  2576. }
  2577. s->y_dc_scale_table= y;
  2578. s->c_dc_scale_table= c;
  2579. s->intra_matrix[0] = 13;
  2580. s->chroma_intra_matrix[0] = 14;
  2581. ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  2582. s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2583. ff_convert_matrix(&s->dsp, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
  2584. s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
  2585. s->qscale= 8;
  2586. }
  2587. //FIXME var duplication
  2588. s->current_picture_ptr->f.key_frame =
  2589. s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
  2590. s->current_picture_ptr->f.pict_type =
  2591. s->current_picture.f.pict_type = s->pict_type;
  2592. if (s->current_picture.f.key_frame)
  2593. s->picture_in_gop_number=0;
  2594. s->last_bits= put_bits_count(&s->pb);
  2595. switch(s->out_format) {
  2596. case FMT_MJPEG:
  2597. if (CONFIG_MJPEG_ENCODER)
  2598. ff_mjpeg_encode_picture_header(s);
  2599. break;
  2600. case FMT_H261:
  2601. if (CONFIG_H261_ENCODER)
  2602. ff_h261_encode_picture_header(s, picture_number);
  2603. break;
  2604. case FMT_H263:
  2605. if (CONFIG_WMV2_ENCODER && s->codec_id == CODEC_ID_WMV2)
  2606. ff_wmv2_encode_picture_header(s, picture_number);
  2607. else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  2608. msmpeg4_encode_picture_header(s, picture_number);
  2609. else if (CONFIG_MPEG4_ENCODER && s->h263_pred)
  2610. mpeg4_encode_picture_header(s, picture_number);
  2611. else if (CONFIG_RV10_ENCODER && s->codec_id == CODEC_ID_RV10)
  2612. rv10_encode_picture_header(s, picture_number);
  2613. else if (CONFIG_RV20_ENCODER && s->codec_id == CODEC_ID_RV20)
  2614. rv20_encode_picture_header(s, picture_number);
  2615. else if (CONFIG_FLV_ENCODER && s->codec_id == CODEC_ID_FLV1)
  2616. ff_flv_encode_picture_header(s, picture_number);
  2617. else if (CONFIG_H263_ENCODER)
  2618. h263_encode_picture_header(s, picture_number);
  2619. break;
  2620. case FMT_MPEG1:
  2621. if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2622. mpeg1_encode_picture_header(s, picture_number);
  2623. break;
  2624. case FMT_H264:
  2625. break;
  2626. default:
  2627. assert(0);
  2628. }
  2629. bits= put_bits_count(&s->pb);
  2630. s->header_bits= bits - s->last_bits;
  2631. for(i=1; i<context_count; i++){
  2632. update_duplicate_context_after_me(s->thread_context[i], s);
  2633. }
  2634. s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  2635. for(i=1; i<context_count; i++){
  2636. merge_context_after_encode(s, s->thread_context[i]);
  2637. }
  2638. emms_c();
  2639. return 0;
  2640. }
  2641. static void denoise_dct_c(MpegEncContext *s, DCTELEM *block){
  2642. const int intra= s->mb_intra;
  2643. int i;
  2644. s->dct_count[intra]++;
  2645. for(i=0; i<64; i++){
  2646. int level= block[i];
  2647. if(level){
  2648. if(level>0){
  2649. s->dct_error_sum[intra][i] += level;
  2650. level -= s->dct_offset[intra][i];
  2651. if(level<0) level=0;
  2652. }else{
  2653. s->dct_error_sum[intra][i] -= level;
  2654. level += s->dct_offset[intra][i];
  2655. if(level>0) level=0;
  2656. }
  2657. block[i]= level;
  2658. }
  2659. }
  2660. }
  2661. static int dct_quantize_trellis_c(MpegEncContext *s,
  2662. DCTELEM *block, int n,
  2663. int qscale, int *overflow){
  2664. const int *qmat;
  2665. const uint8_t *scantable= s->intra_scantable.scantable;
  2666. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2667. int max=0;
  2668. unsigned int threshold1, threshold2;
  2669. int bias=0;
  2670. int run_tab[65];
  2671. int level_tab[65];
  2672. int score_tab[65];
  2673. int survivor[65];
  2674. int survivor_count;
  2675. int last_run=0;
  2676. int last_level=0;
  2677. int last_score= 0;
  2678. int last_i;
  2679. int coeff[2][64];
  2680. int coeff_count[64];
  2681. int qmul, qadd, start_i, last_non_zero, i, dc;
  2682. const int esc_length= s->ac_esc_length;
  2683. uint8_t * length;
  2684. uint8_t * last_length;
  2685. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  2686. s->dsp.fdct (block);
  2687. if(s->dct_error_sum)
  2688. s->denoise_dct(s, block);
  2689. qmul= qscale*16;
  2690. qadd= ((qscale-1)|1)*8;
  2691. if (s->mb_intra) {
  2692. int q;
  2693. if (!s->h263_aic) {
  2694. if (n < 4)
  2695. q = s->y_dc_scale;
  2696. else
  2697. q = s->c_dc_scale;
  2698. q = q << 3;
  2699. } else{
  2700. /* For AIC we skip quant/dequant of INTRADC */
  2701. q = 1 << 3;
  2702. qadd=0;
  2703. }
  2704. /* note: block[0] is assumed to be positive */
  2705. block[0] = (block[0] + (q >> 1)) / q;
  2706. start_i = 1;
  2707. last_non_zero = 0;
  2708. qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  2709. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2710. bias= 1<<(QMAT_SHIFT-1);
  2711. length = s->intra_ac_vlc_length;
  2712. last_length= s->intra_ac_vlc_last_length;
  2713. } else {
  2714. start_i = 0;
  2715. last_non_zero = -1;
  2716. qmat = s->q_inter_matrix[qscale];
  2717. length = s->inter_ac_vlc_length;
  2718. last_length= s->inter_ac_vlc_last_length;
  2719. }
  2720. last_i= start_i;
  2721. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  2722. threshold2= (threshold1<<1);
  2723. for(i=63; i>=start_i; i--) {
  2724. const int j = scantable[i];
  2725. int level = block[j] * qmat[j];
  2726. if(((unsigned)(level+threshold1))>threshold2){
  2727. last_non_zero = i;
  2728. break;
  2729. }
  2730. }
  2731. for(i=start_i; i<=last_non_zero; i++) {
  2732. const int j = scantable[i];
  2733. int level = block[j] * qmat[j];
  2734. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  2735. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  2736. if(((unsigned)(level+threshold1))>threshold2){
  2737. if(level>0){
  2738. level= (bias + level)>>QMAT_SHIFT;
  2739. coeff[0][i]= level;
  2740. coeff[1][i]= level-1;
  2741. // coeff[2][k]= level-2;
  2742. }else{
  2743. level= (bias - level)>>QMAT_SHIFT;
  2744. coeff[0][i]= -level;
  2745. coeff[1][i]= -level+1;
  2746. // coeff[2][k]= -level+2;
  2747. }
  2748. coeff_count[i]= FFMIN(level, 2);
  2749. assert(coeff_count[i]);
  2750. max |=level;
  2751. }else{
  2752. coeff[0][i]= (level>>31)|1;
  2753. coeff_count[i]= 1;
  2754. }
  2755. }
  2756. *overflow= s->max_qcoeff < max; //overflow might have happened
  2757. if(last_non_zero < start_i){
  2758. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2759. return last_non_zero;
  2760. }
  2761. score_tab[start_i]= 0;
  2762. survivor[0]= start_i;
  2763. survivor_count= 1;
  2764. for(i=start_i; i<=last_non_zero; i++){
  2765. int level_index, j, zero_distortion;
  2766. int dct_coeff= FFABS(block[ scantable[i] ]);
  2767. int best_score=256*256*256*120;
  2768. if ( s->dsp.fdct == fdct_ifast
  2769. #ifndef FAAN_POSTSCALE
  2770. || s->dsp.fdct == ff_faandct
  2771. #endif
  2772. )
  2773. dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  2774. zero_distortion= dct_coeff*dct_coeff;
  2775. for(level_index=0; level_index < coeff_count[i]; level_index++){
  2776. int distortion;
  2777. int level= coeff[level_index][i];
  2778. const int alevel= FFABS(level);
  2779. int unquant_coeff;
  2780. assert(level);
  2781. if(s->out_format == FMT_H263){
  2782. unquant_coeff= alevel*qmul + qadd;
  2783. }else{ //MPEG1
  2784. j= s->dsp.idct_permutation[ scantable[i] ]; //FIXME optimize
  2785. if(s->mb_intra){
  2786. unquant_coeff = (int)( alevel * qscale * s->intra_matrix[j]) >> 3;
  2787. unquant_coeff = (unquant_coeff - 1) | 1;
  2788. }else{
  2789. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  2790. unquant_coeff = (unquant_coeff - 1) | 1;
  2791. }
  2792. unquant_coeff<<= 3;
  2793. }
  2794. distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  2795. level+=64;
  2796. if((level&(~127)) == 0){
  2797. for(j=survivor_count-1; j>=0; j--){
  2798. int run= i - survivor[j];
  2799. int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2800. score += score_tab[i-run];
  2801. if(score < best_score){
  2802. best_score= score;
  2803. run_tab[i+1]= run;
  2804. level_tab[i+1]= level-64;
  2805. }
  2806. }
  2807. if(s->out_format == FMT_H263){
  2808. for(j=survivor_count-1; j>=0; j--){
  2809. int run= i - survivor[j];
  2810. int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  2811. score += score_tab[i-run];
  2812. if(score < last_score){
  2813. last_score= score;
  2814. last_run= run;
  2815. last_level= level-64;
  2816. last_i= i+1;
  2817. }
  2818. }
  2819. }
  2820. }else{
  2821. distortion += esc_length*lambda;
  2822. for(j=survivor_count-1; j>=0; j--){
  2823. int run= i - survivor[j];
  2824. int score= distortion + score_tab[i-run];
  2825. if(score < best_score){
  2826. best_score= score;
  2827. run_tab[i+1]= run;
  2828. level_tab[i+1]= level-64;
  2829. }
  2830. }
  2831. if(s->out_format == FMT_H263){
  2832. for(j=survivor_count-1; j>=0; j--){
  2833. int run= i - survivor[j];
  2834. int score= distortion + score_tab[i-run];
  2835. if(score < last_score){
  2836. last_score= score;
  2837. last_run= run;
  2838. last_level= level-64;
  2839. last_i= i+1;
  2840. }
  2841. }
  2842. }
  2843. }
  2844. }
  2845. score_tab[i+1]= best_score;
  2846. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  2847. if(last_non_zero <= 27){
  2848. for(; survivor_count; survivor_count--){
  2849. if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  2850. break;
  2851. }
  2852. }else{
  2853. for(; survivor_count; survivor_count--){
  2854. if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  2855. break;
  2856. }
  2857. }
  2858. survivor[ survivor_count++ ]= i+1;
  2859. }
  2860. if(s->out_format != FMT_H263){
  2861. last_score= 256*256*256*120;
  2862. for(i= survivor[0]; i<=last_non_zero + 1; i++){
  2863. int score= score_tab[i];
  2864. if(i) score += lambda*2; //FIXME exacter?
  2865. if(score < last_score){
  2866. last_score= score;
  2867. last_i= i;
  2868. last_level= level_tab[i];
  2869. last_run= run_tab[i];
  2870. }
  2871. }
  2872. }
  2873. s->coded_score[n] = last_score;
  2874. dc= FFABS(block[0]);
  2875. last_non_zero= last_i - 1;
  2876. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  2877. if(last_non_zero < start_i)
  2878. return last_non_zero;
  2879. if(last_non_zero == 0 && start_i == 0){
  2880. int best_level= 0;
  2881. int best_score= dc * dc;
  2882. for(i=0; i<coeff_count[0]; i++){
  2883. int level= coeff[i][0];
  2884. int alevel= FFABS(level);
  2885. int unquant_coeff, score, distortion;
  2886. if(s->out_format == FMT_H263){
  2887. unquant_coeff= (alevel*qmul + qadd)>>3;
  2888. }else{ //MPEG1
  2889. unquant_coeff = ((( alevel << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  2890. unquant_coeff = (unquant_coeff - 1) | 1;
  2891. }
  2892. unquant_coeff = (unquant_coeff + 4) >> 3;
  2893. unquant_coeff<<= 3 + 3;
  2894. distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  2895. level+=64;
  2896. if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  2897. else score= distortion + esc_length*lambda;
  2898. if(score < best_score){
  2899. best_score= score;
  2900. best_level= level - 64;
  2901. }
  2902. }
  2903. block[0]= best_level;
  2904. s->coded_score[n] = best_score - dc*dc;
  2905. if(best_level == 0) return -1;
  2906. else return last_non_zero;
  2907. }
  2908. i= last_i;
  2909. assert(last_level);
  2910. block[ perm_scantable[last_non_zero] ]= last_level;
  2911. i -= last_run + 1;
  2912. for(; i>start_i; i -= run_tab[i] + 1){
  2913. block[ perm_scantable[i-1] ]= level_tab[i];
  2914. }
  2915. return last_non_zero;
  2916. }
  2917. //#define REFINE_STATS 1
  2918. static int16_t basis[64][64];
  2919. static void build_basis(uint8_t *perm){
  2920. int i, j, x, y;
  2921. emms_c();
  2922. for(i=0; i<8; i++){
  2923. for(j=0; j<8; j++){
  2924. for(y=0; y<8; y++){
  2925. for(x=0; x<8; x++){
  2926. double s= 0.25*(1<<BASIS_SHIFT);
  2927. int index= 8*i + j;
  2928. int perm_index= perm[index];
  2929. if(i==0) s*= sqrt(0.5);
  2930. if(j==0) s*= sqrt(0.5);
  2931. 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)));
  2932. }
  2933. }
  2934. }
  2935. }
  2936. }
  2937. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  2938. DCTELEM *block, int16_t *weight, DCTELEM *orig,
  2939. int n, int qscale){
  2940. int16_t rem[64];
  2941. LOCAL_ALIGNED_16(DCTELEM, d1, [64]);
  2942. const uint8_t *scantable= s->intra_scantable.scantable;
  2943. const uint8_t *perm_scantable= s->intra_scantable.permutated;
  2944. // unsigned int threshold1, threshold2;
  2945. // int bias=0;
  2946. int run_tab[65];
  2947. int prev_run=0;
  2948. int prev_level=0;
  2949. int qmul, qadd, start_i, last_non_zero, i, dc;
  2950. uint8_t * length;
  2951. uint8_t * last_length;
  2952. int lambda;
  2953. int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  2954. #ifdef REFINE_STATS
  2955. static int count=0;
  2956. static int after_last=0;
  2957. static int to_zero=0;
  2958. static int from_zero=0;
  2959. static int raise=0;
  2960. static int lower=0;
  2961. static int messed_sign=0;
  2962. #endif
  2963. if(basis[0][0] == 0)
  2964. build_basis(s->dsp.idct_permutation);
  2965. qmul= qscale*2;
  2966. qadd= (qscale-1)|1;
  2967. if (s->mb_intra) {
  2968. if (!s->h263_aic) {
  2969. if (n < 4)
  2970. q = s->y_dc_scale;
  2971. else
  2972. q = s->c_dc_scale;
  2973. } else{
  2974. /* For AIC we skip quant/dequant of INTRADC */
  2975. q = 1;
  2976. qadd=0;
  2977. }
  2978. q <<= RECON_SHIFT-3;
  2979. /* note: block[0] is assumed to be positive */
  2980. dc= block[0]*q;
  2981. // block[0] = (block[0] + (q >> 1)) / q;
  2982. start_i = 1;
  2983. // if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  2984. // bias= 1<<(QMAT_SHIFT-1);
  2985. length = s->intra_ac_vlc_length;
  2986. last_length= s->intra_ac_vlc_last_length;
  2987. } else {
  2988. dc= 0;
  2989. start_i = 0;
  2990. length = s->inter_ac_vlc_length;
  2991. last_length= s->inter_ac_vlc_last_length;
  2992. }
  2993. last_non_zero = s->block_last_index[n];
  2994. #ifdef REFINE_STATS
  2995. {START_TIMER
  2996. #endif
  2997. dc += (1<<(RECON_SHIFT-1));
  2998. for(i=0; i<64; i++){
  2999. rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME use orig dirrectly instead of copying to rem[]
  3000. }
  3001. #ifdef REFINE_STATS
  3002. STOP_TIMER("memset rem[]")}
  3003. #endif
  3004. sum=0;
  3005. for(i=0; i<64; i++){
  3006. int one= 36;
  3007. int qns=4;
  3008. int w;
  3009. w= FFABS(weight[i]) + qns*one;
  3010. w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  3011. weight[i] = w;
  3012. // w=weight[i] = (63*qns + (w/2)) / w;
  3013. assert(w>0);
  3014. assert(w<(1<<6));
  3015. sum += w*w;
  3016. }
  3017. lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  3018. #ifdef REFINE_STATS
  3019. {START_TIMER
  3020. #endif
  3021. run=0;
  3022. rle_index=0;
  3023. for(i=start_i; i<=last_non_zero; i++){
  3024. int j= perm_scantable[i];
  3025. const int level= block[j];
  3026. int coeff;
  3027. if(level){
  3028. if(level<0) coeff= qmul*level - qadd;
  3029. else coeff= qmul*level + qadd;
  3030. run_tab[rle_index++]=run;
  3031. run=0;
  3032. s->dsp.add_8x8basis(rem, basis[j], coeff);
  3033. }else{
  3034. run++;
  3035. }
  3036. }
  3037. #ifdef REFINE_STATS
  3038. if(last_non_zero>0){
  3039. STOP_TIMER("init rem[]")
  3040. }
  3041. }
  3042. {START_TIMER
  3043. #endif
  3044. for(;;){
  3045. int best_score=s->dsp.try_8x8basis(rem, weight, basis[0], 0);
  3046. int best_coeff=0;
  3047. int best_change=0;
  3048. int run2, best_unquant_change=0, analyze_gradient;
  3049. #ifdef REFINE_STATS
  3050. {START_TIMER
  3051. #endif
  3052. analyze_gradient = last_non_zero > 2 || s->avctx->quantizer_noise_shaping >= 3;
  3053. if(analyze_gradient){
  3054. #ifdef REFINE_STATS
  3055. {START_TIMER
  3056. #endif
  3057. for(i=0; i<64; i++){
  3058. int w= weight[i];
  3059. d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  3060. }
  3061. #ifdef REFINE_STATS
  3062. STOP_TIMER("rem*w*w")}
  3063. {START_TIMER
  3064. #endif
  3065. s->dsp.fdct(d1);
  3066. #ifdef REFINE_STATS
  3067. STOP_TIMER("dct")}
  3068. #endif
  3069. }
  3070. if(start_i){
  3071. const int level= block[0];
  3072. int change, old_coeff;
  3073. assert(s->mb_intra);
  3074. old_coeff= q*level;
  3075. for(change=-1; change<=1; change+=2){
  3076. int new_level= level + change;
  3077. int score, new_coeff;
  3078. new_coeff= q*new_level;
  3079. if(new_coeff >= 2048 || new_coeff < 0)
  3080. continue;
  3081. score= s->dsp.try_8x8basis(rem, weight, basis[0], new_coeff - old_coeff);
  3082. if(score<best_score){
  3083. best_score= score;
  3084. best_coeff= 0;
  3085. best_change= change;
  3086. best_unquant_change= new_coeff - old_coeff;
  3087. }
  3088. }
  3089. }
  3090. run=0;
  3091. rle_index=0;
  3092. run2= run_tab[rle_index++];
  3093. prev_level=0;
  3094. prev_run=0;
  3095. for(i=start_i; i<64; i++){
  3096. int j= perm_scantable[i];
  3097. const int level= block[j];
  3098. int change, old_coeff;
  3099. if(s->avctx->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  3100. break;
  3101. if(level){
  3102. if(level<0) old_coeff= qmul*level - qadd;
  3103. else old_coeff= qmul*level + qadd;
  3104. run2= run_tab[rle_index++]; //FIXME ! maybe after last
  3105. }else{
  3106. old_coeff=0;
  3107. run2--;
  3108. assert(run2>=0 || i >= last_non_zero );
  3109. }
  3110. for(change=-1; change<=1; change+=2){
  3111. int new_level= level + change;
  3112. int score, new_coeff, unquant_change;
  3113. score=0;
  3114. if(s->avctx->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  3115. continue;
  3116. if(new_level){
  3117. if(new_level<0) new_coeff= qmul*new_level - qadd;
  3118. else new_coeff= qmul*new_level + qadd;
  3119. if(new_coeff >= 2048 || new_coeff <= -2048)
  3120. continue;
  3121. //FIXME check for overflow
  3122. if(level){
  3123. if(level < 63 && level > -63){
  3124. if(i < last_non_zero)
  3125. score += length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3126. - length[UNI_AC_ENC_INDEX(run, level+64)];
  3127. else
  3128. score += last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  3129. - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  3130. }
  3131. }else{
  3132. assert(FFABS(new_level)==1);
  3133. if(analyze_gradient){
  3134. int g= d1[ scantable[i] ];
  3135. if(g && (g^new_level) >= 0)
  3136. continue;
  3137. }
  3138. if(i < last_non_zero){
  3139. int next_i= i + run2 + 1;
  3140. int next_level= block[ perm_scantable[next_i] ] + 64;
  3141. if(next_level&(~127))
  3142. next_level= 0;
  3143. if(next_i < last_non_zero)
  3144. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3145. + length[UNI_AC_ENC_INDEX(run2, next_level)]
  3146. - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3147. else
  3148. score += length[UNI_AC_ENC_INDEX(run, 65)]
  3149. + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3150. - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  3151. }else{
  3152. score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  3153. if(prev_level){
  3154. score += length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3155. - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3156. }
  3157. }
  3158. }
  3159. }else{
  3160. new_coeff=0;
  3161. assert(FFABS(level)==1);
  3162. if(i < last_non_zero){
  3163. int next_i= i + run2 + 1;
  3164. int next_level= block[ perm_scantable[next_i] ] + 64;
  3165. if(next_level&(~127))
  3166. next_level= 0;
  3167. if(next_i < last_non_zero)
  3168. score += length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3169. - length[UNI_AC_ENC_INDEX(run2, next_level)]
  3170. - length[UNI_AC_ENC_INDEX(run, 65)];
  3171. else
  3172. score += last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  3173. - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  3174. - length[UNI_AC_ENC_INDEX(run, 65)];
  3175. }else{
  3176. score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  3177. if(prev_level){
  3178. score += last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  3179. - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  3180. }
  3181. }
  3182. }
  3183. score *= lambda;
  3184. unquant_change= new_coeff - old_coeff;
  3185. assert((score < 100*lambda && score > -100*lambda) || lambda==0);
  3186. score+= s->dsp.try_8x8basis(rem, weight, basis[j], unquant_change);
  3187. if(score<best_score){
  3188. best_score= score;
  3189. best_coeff= i;
  3190. best_change= change;
  3191. best_unquant_change= unquant_change;
  3192. }
  3193. }
  3194. if(level){
  3195. prev_level= level + 64;
  3196. if(prev_level&(~127))
  3197. prev_level= 0;
  3198. prev_run= run;
  3199. run=0;
  3200. }else{
  3201. run++;
  3202. }
  3203. }
  3204. #ifdef REFINE_STATS
  3205. STOP_TIMER("iterative step")}
  3206. #endif
  3207. if(best_change){
  3208. int j= perm_scantable[ best_coeff ];
  3209. block[j] += best_change;
  3210. if(best_coeff > last_non_zero){
  3211. last_non_zero= best_coeff;
  3212. assert(block[j]);
  3213. #ifdef REFINE_STATS
  3214. after_last++;
  3215. #endif
  3216. }else{
  3217. #ifdef REFINE_STATS
  3218. if(block[j]){
  3219. if(block[j] - best_change){
  3220. if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  3221. raise++;
  3222. }else{
  3223. lower++;
  3224. }
  3225. }else{
  3226. from_zero++;
  3227. }
  3228. }else{
  3229. to_zero++;
  3230. }
  3231. #endif
  3232. for(; last_non_zero>=start_i; last_non_zero--){
  3233. if(block[perm_scantable[last_non_zero]])
  3234. break;
  3235. }
  3236. }
  3237. #ifdef REFINE_STATS
  3238. count++;
  3239. if(256*256*256*64 % count == 0){
  3240. 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);
  3241. }
  3242. #endif
  3243. run=0;
  3244. rle_index=0;
  3245. for(i=start_i; i<=last_non_zero; i++){
  3246. int j= perm_scantable[i];
  3247. const int level= block[j];
  3248. if(level){
  3249. run_tab[rle_index++]=run;
  3250. run=0;
  3251. }else{
  3252. run++;
  3253. }
  3254. }
  3255. s->dsp.add_8x8basis(rem, basis[j], best_unquant_change);
  3256. }else{
  3257. break;
  3258. }
  3259. }
  3260. #ifdef REFINE_STATS
  3261. if(last_non_zero>0){
  3262. STOP_TIMER("iterative search")
  3263. }
  3264. }
  3265. #endif
  3266. return last_non_zero;
  3267. }
  3268. int dct_quantize_c(MpegEncContext *s,
  3269. DCTELEM *block, int n,
  3270. int qscale, int *overflow)
  3271. {
  3272. int i, j, level, last_non_zero, q, start_i;
  3273. const int *qmat;
  3274. const uint8_t *scantable= s->intra_scantable.scantable;
  3275. int bias;
  3276. int max=0;
  3277. unsigned int threshold1, threshold2;
  3278. s->dsp.fdct (block);
  3279. if(s->dct_error_sum)
  3280. s->denoise_dct(s, block);
  3281. if (s->mb_intra) {
  3282. if (!s->h263_aic) {
  3283. if (n < 4)
  3284. q = s->y_dc_scale;
  3285. else
  3286. q = s->c_dc_scale;
  3287. q = q << 3;
  3288. } else
  3289. /* For AIC we skip quant/dequant of INTRADC */
  3290. q = 1 << 3;
  3291. /* note: block[0] is assumed to be positive */
  3292. block[0] = (block[0] + (q >> 1)) / q;
  3293. start_i = 1;
  3294. last_non_zero = 0;
  3295. qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  3296. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3297. } else {
  3298. start_i = 0;
  3299. last_non_zero = -1;
  3300. qmat = s->q_inter_matrix[qscale];
  3301. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3302. }
  3303. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3304. threshold2= (threshold1<<1);
  3305. for(i=63;i>=start_i;i--) {
  3306. j = scantable[i];
  3307. level = block[j] * qmat[j];
  3308. if(((unsigned)(level+threshold1))>threshold2){
  3309. last_non_zero = i;
  3310. break;
  3311. }else{
  3312. block[j]=0;
  3313. }
  3314. }
  3315. for(i=start_i; i<=last_non_zero; i++) {
  3316. j = scantable[i];
  3317. level = block[j] * qmat[j];
  3318. // if( bias+level >= (1<<QMAT_SHIFT)
  3319. // || bias-level >= (1<<QMAT_SHIFT)){
  3320. if(((unsigned)(level+threshold1))>threshold2){
  3321. if(level>0){
  3322. level= (bias + level)>>QMAT_SHIFT;
  3323. block[j]= level;
  3324. }else{
  3325. level= (bias - level)>>QMAT_SHIFT;
  3326. block[j]= -level;
  3327. }
  3328. max |=level;
  3329. }else{
  3330. block[j]=0;
  3331. }
  3332. }
  3333. *overflow= s->max_qcoeff < max; //overflow might have happened
  3334. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3335. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3336. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3337. return last_non_zero;
  3338. }
  3339. #define OFFSET(x) offsetof(MpegEncContext, x)
  3340. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  3341. static const AVOption h263_options[] = {
  3342. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3343. { "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},
  3344. { NULL },
  3345. };
  3346. static const AVClass h263_class = {
  3347. .class_name = "H.263 encoder",
  3348. .item_name = av_default_item_name,
  3349. .option = h263_options,
  3350. .version = LIBAVUTIL_VERSION_INT,
  3351. };
  3352. AVCodec ff_h263_encoder = {
  3353. .name = "h263",
  3354. .type = AVMEDIA_TYPE_VIDEO,
  3355. .id = CODEC_ID_H263,
  3356. .priv_data_size = sizeof(MpegEncContext),
  3357. .init = MPV_encode_init,
  3358. .encode = MPV_encode_picture,
  3359. .close = MPV_encode_end,
  3360. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3361. .long_name= NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  3362. .priv_class = &h263_class,
  3363. };
  3364. static const AVOption h263p_options[] = {
  3365. { "umv", "Use unlimited motion vectors.", OFFSET(umvplus), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3366. { "aiv", "Use alternative inter VLC.", OFFSET(alt_inter_vlc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3367. { "obmc", "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { 0 }, 0, 1, VE },
  3368. { "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},
  3369. { NULL },
  3370. };
  3371. static const AVClass h263p_class = {
  3372. .class_name = "H.263p encoder",
  3373. .item_name = av_default_item_name,
  3374. .option = h263p_options,
  3375. .version = LIBAVUTIL_VERSION_INT,
  3376. };
  3377. AVCodec ff_h263p_encoder = {
  3378. .name = "h263p",
  3379. .type = AVMEDIA_TYPE_VIDEO,
  3380. .id = CODEC_ID_H263P,
  3381. .priv_data_size = sizeof(MpegEncContext),
  3382. .init = MPV_encode_init,
  3383. .encode = MPV_encode_picture,
  3384. .close = MPV_encode_end,
  3385. .capabilities = CODEC_CAP_SLICE_THREADS,
  3386. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3387. .long_name= NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  3388. .priv_class = &h263p_class,
  3389. };
  3390. AVCodec ff_msmpeg4v2_encoder = {
  3391. .name = "msmpeg4v2",
  3392. .type = AVMEDIA_TYPE_VIDEO,
  3393. .id = CODEC_ID_MSMPEG4V2,
  3394. .priv_data_size = sizeof(MpegEncContext),
  3395. .init = MPV_encode_init,
  3396. .encode = MPV_encode_picture,
  3397. .close = MPV_encode_end,
  3398. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3399. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  3400. };
  3401. AVCodec ff_msmpeg4v3_encoder = {
  3402. .name = "msmpeg4",
  3403. .type = AVMEDIA_TYPE_VIDEO,
  3404. .id = CODEC_ID_MSMPEG4V3,
  3405. .priv_data_size = sizeof(MpegEncContext),
  3406. .init = MPV_encode_init,
  3407. .encode = MPV_encode_picture,
  3408. .close = MPV_encode_end,
  3409. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3410. .long_name= NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  3411. };
  3412. AVCodec ff_wmv1_encoder = {
  3413. .name = "wmv1",
  3414. .type = AVMEDIA_TYPE_VIDEO,
  3415. .id = CODEC_ID_WMV1,
  3416. .priv_data_size = sizeof(MpegEncContext),
  3417. .init = MPV_encode_init,
  3418. .encode = MPV_encode_picture,
  3419. .close = MPV_encode_end,
  3420. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  3421. .long_name= NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  3422. };