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.

3916 lines
144KB

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