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.

3878 lines
142KB

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