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.

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