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.

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