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.

3879 lines
142KB

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