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.

3834 lines
141KB

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