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.

3851 lines
140KB

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