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.

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