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.

4858 lines
169KB

  1. /*
  2. * The simplest mpeg encoder (well, it was the simplest!)
  3. * Copyright (c) 2000,2001 Fabrice Bellard.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *
  19. * 4MV & hq & b-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  20. */
  21. /**
  22. * @file mpegvideo.c
  23. * The simplest mpeg encoder (well, it was the simplest!).
  24. */
  25. #include <limits.h>
  26. #include "avcodec.h"
  27. #include "dsputil.h"
  28. #include "mpegvideo.h"
  29. #include "faandct.h"
  30. #ifdef USE_FASTMEMCPY
  31. #include "fastmemcpy.h"
  32. #endif
  33. //#undef NDEBUG
  34. //#include <assert.h>
  35. #ifdef CONFIG_ENCODERS
  36. static void encode_picture(MpegEncContext *s, int picture_number);
  37. #endif //CONFIG_ENCODERS
  38. static void dct_unquantize_mpeg1_c(MpegEncContext *s,
  39. DCTELEM *block, int n, int qscale);
  40. static void dct_unquantize_mpeg2_c(MpegEncContext *s,
  41. DCTELEM *block, int n, int qscale);
  42. static void dct_unquantize_h263_c(MpegEncContext *s,
  43. DCTELEM *block, int n, int qscale);
  44. static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w);
  45. #ifdef CONFIG_ENCODERS
  46. static int dct_quantize_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
  47. static int dct_quantize_trellis_c(MpegEncContext *s, DCTELEM *block, int n, int qscale, int *overflow);
  48. static int sse_mb(MpegEncContext *s);
  49. #endif //CONFIG_ENCODERS
  50. #ifdef HAVE_XVMC
  51. extern int XVMC_field_start(MpegEncContext*s, AVCodecContext *avctx);
  52. extern void XVMC_field_end(MpegEncContext *s);
  53. extern void XVMC_decode_mb(MpegEncContext *s);
  54. #endif
  55. void (*draw_edges)(uint8_t *buf, int wrap, int width, int height, int w)= draw_edges_c;
  56. /* enable all paranoid tests for rounding, overflows, etc... */
  57. //#define PARANOID
  58. //#define DEBUG
  59. /* for jpeg fast DCT */
  60. #define CONST_BITS 14
  61. static const uint16_t aanscales[64] = {
  62. /* precomputed values scaled up by 14 bits */
  63. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  64. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  65. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  66. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  67. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  68. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  69. 8867 , 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  70. 4520 , 6270, 5906, 5315, 4520, 3552, 2446, 1247
  71. };
  72. static const uint8_t h263_chroma_roundtab[16] = {
  73. // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  74. 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
  75. };
  76. #ifdef CONFIG_ENCODERS
  77. static uint8_t (*default_mv_penalty)[MAX_MV*2+1]=NULL;
  78. static uint8_t default_fcode_tab[MAX_MV*2+1];
  79. enum PixelFormat ff_yuv420p_list[2]= {PIX_FMT_YUV420P, -1};
  80. static void convert_matrix(DSPContext *dsp, int (*qmat)[64], uint16_t (*qmat16)[2][64],
  81. const uint16_t *quant_matrix, int bias, int qmin, int qmax)
  82. {
  83. int qscale;
  84. for(qscale=qmin; qscale<=qmax; qscale++){
  85. int i;
  86. if (dsp->fdct == ff_jpeg_fdct_islow
  87. #ifdef FAAN_POSTSCALE
  88. || dsp->fdct == ff_faandct
  89. #endif
  90. ) {
  91. for(i=0;i<64;i++) {
  92. const int j= dsp->idct_permutation[i];
  93. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  94. /* 19952 <= aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  95. /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
  96. /* 3444240 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  97. qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) /
  98. (qscale * quant_matrix[j]));
  99. }
  100. } else if (dsp->fdct == fdct_ifast
  101. #ifndef FAAN_POSTSCALE
  102. || dsp->fdct == ff_faandct
  103. #endif
  104. ) {
  105. for(i=0;i<64;i++) {
  106. const int j= dsp->idct_permutation[i];
  107. /* 16 <= qscale * quant_matrix[i] <= 7905 */
  108. /* 19952 <= aanscales[i] * qscale * quant_matrix[i] <= 249205026 */
  109. /* (1<<36)/19952 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= (1<<36)/249205026 */
  110. /* 3444240 >= (1<<36)/(aanscales[i] * qscale * quant_matrix[i]) >= 275 */
  111. qmat[qscale][i] = (int)((uint64_t_C(1) << (QMAT_SHIFT + 14)) /
  112. (aanscales[i] * qscale * quant_matrix[j]));
  113. }
  114. } else {
  115. for(i=0;i<64;i++) {
  116. const int j= dsp->idct_permutation[i];
  117. /* We can safely suppose that 16 <= quant_matrix[i] <= 255
  118. So 16 <= qscale * quant_matrix[i] <= 7905
  119. so (1<<19) / 16 >= (1<<19) / (qscale * quant_matrix[i]) >= (1<<19) / 7905
  120. so 32768 >= (1<<19) / (qscale * quant_matrix[i]) >= 67
  121. */
  122. qmat[qscale][i] = (int)((uint64_t_C(1) << QMAT_SHIFT) / (qscale * quant_matrix[j]));
  123. // qmat [qscale][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[i]);
  124. qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / (qscale * quant_matrix[j]);
  125. if(qmat16[qscale][0][i]==0 || qmat16[qscale][0][i]==128*256) qmat16[qscale][0][i]=128*256-1;
  126. qmat16[qscale][1][i]= ROUNDED_DIV(bias<<(16-QUANT_BIAS_SHIFT), qmat16[qscale][0][i]);
  127. }
  128. }
  129. }
  130. }
  131. static inline void update_qscale(MpegEncContext *s){
  132. s->qscale= (s->lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);
  133. s->qscale= clip(s->qscale, s->avctx->qmin, s->avctx->qmax);
  134. s->lambda2= (s->lambda*s->lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;
  135. }
  136. #endif //CONFIG_ENCODERS
  137. void ff_init_scantable(uint8_t *permutation, ScanTable *st, const uint8_t *src_scantable){
  138. int i;
  139. int end;
  140. st->scantable= src_scantable;
  141. for(i=0; i<64; i++){
  142. int j;
  143. j = src_scantable[i];
  144. st->permutated[i] = permutation[j];
  145. #ifdef ARCH_POWERPC
  146. st->inverse[j] = i;
  147. #endif
  148. }
  149. end=-1;
  150. for(i=0; i<64; i++){
  151. int j;
  152. j = st->permutated[i];
  153. if(j>end) end=j;
  154. st->raster_end[i]= end;
  155. }
  156. }
  157. #ifdef CONFIG_ENCODERS
  158. void ff_write_quant_matrix(PutBitContext *pb, int16_t *matrix){
  159. int i;
  160. if(matrix){
  161. put_bits(pb, 1, 1);
  162. for(i=0;i<64;i++) {
  163. put_bits(pb, 8, matrix[ ff_zigzag_direct[i] ]);
  164. }
  165. }else
  166. put_bits(pb, 1, 0);
  167. }
  168. #endif //CONFIG_ENCODERS
  169. /* init common dct for both encoder and decoder */
  170. int DCT_common_init(MpegEncContext *s)
  171. {
  172. s->dct_unquantize_h263 = dct_unquantize_h263_c;
  173. s->dct_unquantize_mpeg1 = dct_unquantize_mpeg1_c;
  174. s->dct_unquantize_mpeg2 = dct_unquantize_mpeg2_c;
  175. #ifdef CONFIG_ENCODERS
  176. s->dct_quantize= dct_quantize_c;
  177. #endif
  178. #ifdef HAVE_MMX
  179. MPV_common_init_mmx(s);
  180. #endif
  181. #ifdef ARCH_ALPHA
  182. MPV_common_init_axp(s);
  183. #endif
  184. #ifdef HAVE_MLIB
  185. MPV_common_init_mlib(s);
  186. #endif
  187. #ifdef HAVE_MMI
  188. MPV_common_init_mmi(s);
  189. #endif
  190. #ifdef ARCH_ARMV4L
  191. MPV_common_init_armv4l(s);
  192. #endif
  193. #ifdef ARCH_POWERPC
  194. MPV_common_init_ppc(s);
  195. #endif
  196. #ifdef CONFIG_ENCODERS
  197. s->fast_dct_quantize= s->dct_quantize;
  198. if(s->flags&CODEC_FLAG_TRELLIS_QUANT){
  199. s->dct_quantize= dct_quantize_trellis_c; //move before MPV_common_init_*
  200. }
  201. #endif //CONFIG_ENCODERS
  202. /* load & permutate scantables
  203. note: only wmv uses differnt ones
  204. */
  205. ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable , ff_zigzag_direct);
  206. ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable , ff_zigzag_direct);
  207. ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
  208. ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
  209. s->picture_structure= PICT_FRAME;
  210. return 0;
  211. }
  212. static void copy_picture(Picture *dst, Picture *src){
  213. *dst = *src;
  214. dst->type= FF_BUFFER_TYPE_COPY;
  215. }
  216. /**
  217. * allocates a Picture
  218. * The pixels are allocated/set by calling get_buffer() if shared=0
  219. */
  220. static int alloc_picture(MpegEncContext *s, Picture *pic, int shared){
  221. const int big_mb_num= s->mb_stride*(s->mb_height+1) + 1; //the +1 is needed so memset(,,stride*height) doesnt sig11
  222. const int mb_array_size= s->mb_stride*s->mb_height;
  223. int i;
  224. if(shared){
  225. assert(pic->data[0]);
  226. assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);
  227. pic->type= FF_BUFFER_TYPE_SHARED;
  228. }else{
  229. int r;
  230. assert(!pic->data[0]);
  231. r= s->avctx->get_buffer(s->avctx, (AVFrame*)pic);
  232. if(r<0 || !pic->age || !pic->type || !pic->data[0]){
  233. av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (%d %d %d %p)\n", r, pic->age, pic->type, pic->data[0]);
  234. return -1;
  235. }
  236. if(s->linesize && (s->linesize != pic->linesize[0] || s->uvlinesize != pic->linesize[1])){
  237. av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (stride changed)\n");
  238. return -1;
  239. }
  240. if(pic->linesize[1] != pic->linesize[2]){
  241. av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed (uv stride missmatch)\n");
  242. return -1;
  243. }
  244. s->linesize = pic->linesize[0];
  245. s->uvlinesize= pic->linesize[1];
  246. }
  247. if(pic->qscale_table==NULL){
  248. if (s->encoding) {
  249. CHECKED_ALLOCZ(pic->mb_var , mb_array_size * sizeof(int16_t))
  250. CHECKED_ALLOCZ(pic->mc_mb_var, mb_array_size * sizeof(int16_t))
  251. CHECKED_ALLOCZ(pic->mb_mean , mb_array_size * sizeof(int8_t))
  252. CHECKED_ALLOCZ(pic->mb_cmp_score, mb_array_size * sizeof(int32_t))
  253. }
  254. CHECKED_ALLOCZ(pic->mbskip_table , mb_array_size * sizeof(uint8_t)+2) //the +2 is for the slice end check
  255. CHECKED_ALLOCZ(pic->qscale_table , mb_array_size * sizeof(uint8_t))
  256. CHECKED_ALLOCZ(pic->mb_type_base , big_mb_num * sizeof(int))
  257. pic->mb_type= pic->mb_type_base + s->mb_stride+1;
  258. if(s->out_format == FMT_H264){
  259. for(i=0; i<2; i++){
  260. CHECKED_ALLOCZ(pic->motion_val[i], 2 * 16 * s->mb_num * sizeof(uint16_t))
  261. CHECKED_ALLOCZ(pic->ref_index[i] , 4 * s->mb_num * sizeof(uint8_t))
  262. }
  263. }
  264. pic->qstride= s->mb_stride;
  265. CHECKED_ALLOCZ(pic->pan_scan , 1 * sizeof(AVPanScan))
  266. }
  267. //it might be nicer if the application would keep track of these but it would require a API change
  268. memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);
  269. s->prev_pict_types[0]= s->pict_type;
  270. if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == B_TYPE)
  271. pic->age= INT_MAX; // skiped MBs in b frames are quite rare in mpeg1/2 and its a bit tricky to skip them anyway
  272. return 0;
  273. fail: //for the CHECKED_ALLOCZ macro
  274. return -1;
  275. }
  276. /**
  277. * deallocates a picture
  278. */
  279. static void free_picture(MpegEncContext *s, Picture *pic){
  280. int i;
  281. if(pic->data[0] && pic->type!=FF_BUFFER_TYPE_SHARED){
  282. s->avctx->release_buffer(s->avctx, (AVFrame*)pic);
  283. }
  284. av_freep(&pic->mb_var);
  285. av_freep(&pic->mc_mb_var);
  286. av_freep(&pic->mb_mean);
  287. av_freep(&pic->mb_cmp_score);
  288. av_freep(&pic->mbskip_table);
  289. av_freep(&pic->qscale_table);
  290. av_freep(&pic->mb_type_base);
  291. av_freep(&pic->pan_scan);
  292. pic->mb_type= NULL;
  293. for(i=0; i<2; i++){
  294. av_freep(&pic->motion_val[i]);
  295. av_freep(&pic->ref_index[i]);
  296. }
  297. if(pic->type == FF_BUFFER_TYPE_SHARED){
  298. for(i=0; i<4; i++){
  299. pic->base[i]=
  300. pic->data[i]= NULL;
  301. }
  302. pic->type= 0;
  303. }
  304. }
  305. /* init common structure for both encoder and decoder */
  306. int MPV_common_init(MpegEncContext *s)
  307. {
  308. int y_size, c_size, yc_size, i, mb_array_size, x, y;
  309. dsputil_init(&s->dsp, s->avctx);
  310. DCT_common_init(s);
  311. s->flags= s->avctx->flags;
  312. s->mb_width = (s->width + 15) / 16;
  313. s->mb_height = (s->height + 15) / 16;
  314. s->mb_stride = s->mb_width + 1;
  315. mb_array_size= s->mb_height * s->mb_stride;
  316. /* set default edge pos, will be overriden in decode_header if needed */
  317. s->h_edge_pos= s->mb_width*16;
  318. s->v_edge_pos= s->mb_height*16;
  319. s->mb_num = s->mb_width * s->mb_height;
  320. s->block_wrap[0]=
  321. s->block_wrap[1]=
  322. s->block_wrap[2]=
  323. s->block_wrap[3]= s->mb_width*2 + 2;
  324. s->block_wrap[4]=
  325. s->block_wrap[5]= s->mb_width + 2;
  326. y_size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
  327. c_size = (s->mb_width + 2) * (s->mb_height + 2);
  328. yc_size = y_size + 2 * c_size;
  329. /* convert fourcc to upper case */
  330. s->avctx->codec_tag= toupper( s->avctx->codec_tag &0xFF)
  331. + (toupper((s->avctx->codec_tag>>8 )&0xFF)<<8 )
  332. + (toupper((s->avctx->codec_tag>>16)&0xFF)<<16)
  333. + (toupper((s->avctx->codec_tag>>24)&0xFF)<<24);
  334. s->avctx->stream_codec_tag= toupper( s->avctx->stream_codec_tag &0xFF)
  335. + (toupper((s->avctx->stream_codec_tag>>8 )&0xFF)<<8 )
  336. + (toupper((s->avctx->stream_codec_tag>>16)&0xFF)<<16)
  337. + (toupper((s->avctx->stream_codec_tag>>24)&0xFF)<<24);
  338. CHECKED_ALLOCZ(s->allocated_edge_emu_buffer, (s->width+64)*2*17*2); //(width + edge + align)*interlaced*MBsize*tolerance
  339. s->edge_emu_buffer= s->allocated_edge_emu_buffer + (s->width+64)*2*17;
  340. s->avctx->coded_frame= (AVFrame*)&s->current_picture;
  341. CHECKED_ALLOCZ(s->mb_index2xy, (s->mb_num+1)*sizeof(int)) //error ressilience code looks cleaner with this
  342. for(y=0; y<s->mb_height; y++){
  343. for(x=0; x<s->mb_width; x++){
  344. s->mb_index2xy[ x + y*s->mb_width ] = x + y*s->mb_stride;
  345. }
  346. }
  347. s->mb_index2xy[ s->mb_height*s->mb_width ] = (s->mb_height-1)*s->mb_stride + s->mb_width; //FIXME really needed?
  348. if (s->encoding) {
  349. int mv_table_size= s->mb_stride * (s->mb_height+2) + 1;
  350. /* Allocate MV tables */
  351. CHECKED_ALLOCZ(s->p_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  352. CHECKED_ALLOCZ(s->b_forw_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  353. CHECKED_ALLOCZ(s->b_back_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  354. CHECKED_ALLOCZ(s->b_bidir_forw_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  355. CHECKED_ALLOCZ(s->b_bidir_back_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  356. CHECKED_ALLOCZ(s->b_direct_mv_table_base , mv_table_size * 2 * sizeof(int16_t))
  357. s->p_mv_table = s->p_mv_table_base + s->mb_stride + 1;
  358. s->b_forw_mv_table = s->b_forw_mv_table_base + s->mb_stride + 1;
  359. s->b_back_mv_table = s->b_back_mv_table_base + s->mb_stride + 1;
  360. s->b_bidir_forw_mv_table= s->b_bidir_forw_mv_table_base + s->mb_stride + 1;
  361. s->b_bidir_back_mv_table= s->b_bidir_back_mv_table_base + s->mb_stride + 1;
  362. s->b_direct_mv_table = s->b_direct_mv_table_base + s->mb_stride + 1;
  363. //FIXME should be linesize instead of s->width*2 but that isnt known before get_buffer()
  364. CHECKED_ALLOCZ(s->me.scratchpad, s->width*2*16*3*sizeof(uint8_t))
  365. CHECKED_ALLOCZ(s->me.map , ME_MAP_SIZE*sizeof(uint32_t))
  366. CHECKED_ALLOCZ(s->me.score_map, ME_MAP_SIZE*sizeof(uint32_t))
  367. if(s->codec_id==CODEC_ID_MPEG4){
  368. CHECKED_ALLOCZ(s->tex_pb_buffer, PB_BUFFER_SIZE);
  369. CHECKED_ALLOCZ( s->pb2_buffer, PB_BUFFER_SIZE);
  370. }
  371. if(s->msmpeg4_version){
  372. CHECKED_ALLOCZ(s->ac_stats, 2*2*(MAX_LEVEL+1)*(MAX_RUN+1)*2*sizeof(int));
  373. }
  374. CHECKED_ALLOCZ(s->avctx->stats_out, 256);
  375. /* Allocate MB type table */
  376. CHECKED_ALLOCZ(s->mb_type , mb_array_size * sizeof(uint8_t)) //needed for encoding
  377. CHECKED_ALLOCZ(s->lambda_table, mb_array_size * sizeof(int))
  378. CHECKED_ALLOCZ(s->q_intra_matrix, 64*32 * sizeof(int))
  379. CHECKED_ALLOCZ(s->q_inter_matrix, 64*32 * sizeof(int))
  380. CHECKED_ALLOCZ(s->q_intra_matrix16, 64*32*2 * sizeof(uint16_t))
  381. CHECKED_ALLOCZ(s->q_inter_matrix16, 64*32*2 * sizeof(uint16_t))
  382. CHECKED_ALLOCZ(s->input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
  383. CHECKED_ALLOCZ(s->reordered_input_picture, MAX_PICTURE_COUNT * sizeof(Picture*))
  384. if(s->avctx->noise_reduction){
  385. CHECKED_ALLOCZ(s->dct_error_sum, 2 * 64 * sizeof(int))
  386. CHECKED_ALLOCZ(s->dct_offset, 2 * 64 * sizeof(uint16_t))
  387. }
  388. }
  389. CHECKED_ALLOCZ(s->blocks, 64*6*2 * sizeof(DCTELEM))
  390. CHECKED_ALLOCZ(s->picture, MAX_PICTURE_COUNT * sizeof(Picture))
  391. CHECKED_ALLOCZ(s->error_status_table, mb_array_size*sizeof(uint8_t))
  392. if (s->out_format == FMT_H263 || s->encoding) {
  393. int size;
  394. /* MV prediction */
  395. size = (2 * s->mb_width + 2) * (2 * s->mb_height + 2);
  396. CHECKED_ALLOCZ(s->motion_val, size * 2 * sizeof(int16_t));
  397. }
  398. if(s->codec_id==CODEC_ID_MPEG4){
  399. /* interlaced direct mode decoding tables */
  400. CHECKED_ALLOCZ(s->field_mv_table, mb_array_size*2*2 * sizeof(int16_t))
  401. CHECKED_ALLOCZ(s->field_select_table, mb_array_size*2* sizeof(int8_t))
  402. }
  403. if (s->out_format == FMT_H263) {
  404. /* ac values */
  405. CHECKED_ALLOCZ(s->ac_val[0], yc_size * sizeof(int16_t) * 16);
  406. s->ac_val[1] = s->ac_val[0] + y_size;
  407. s->ac_val[2] = s->ac_val[1] + c_size;
  408. /* cbp values */
  409. CHECKED_ALLOCZ(s->coded_block, y_size);
  410. /* divx501 bitstream reorder buffer */
  411. CHECKED_ALLOCZ(s->bitstream_buffer, BITSTREAM_BUFFER_SIZE);
  412. /* cbp, ac_pred, pred_dir */
  413. CHECKED_ALLOCZ(s->cbp_table , mb_array_size * sizeof(uint8_t))
  414. CHECKED_ALLOCZ(s->pred_dir_table, mb_array_size * sizeof(uint8_t))
  415. }
  416. if (s->h263_pred || s->h263_plus || !s->encoding) {
  417. /* dc values */
  418. //MN: we need these for error resilience of intra-frames
  419. CHECKED_ALLOCZ(s->dc_val[0], yc_size * sizeof(int16_t));
  420. s->dc_val[1] = s->dc_val[0] + y_size;
  421. s->dc_val[2] = s->dc_val[1] + c_size;
  422. for(i=0;i<yc_size;i++)
  423. s->dc_val[0][i] = 1024;
  424. }
  425. /* which mb is a intra block */
  426. CHECKED_ALLOCZ(s->mbintra_table, mb_array_size);
  427. memset(s->mbintra_table, 1, mb_array_size);
  428. /* default structure is frame */
  429. s->picture_structure = PICT_FRAME;
  430. /* init macroblock skip table */
  431. CHECKED_ALLOCZ(s->mbskip_table, mb_array_size+2);
  432. //Note the +1 is for a quicker mpeg4 slice_end detection
  433. CHECKED_ALLOCZ(s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE);
  434. s->block= s->blocks[0];
  435. for(i=0;i<12;i++){
  436. s->pblocks[i] = (short *)(&s->block[i]);
  437. }
  438. s->parse_context.state= -1;
  439. s->context_initialized = 1;
  440. return 0;
  441. fail:
  442. MPV_common_end(s);
  443. return -1;
  444. }
  445. //extern int sads;
  446. /* init common structure for both encoder and decoder */
  447. void MPV_common_end(MpegEncContext *s)
  448. {
  449. int i;
  450. av_freep(&s->parse_context.buffer);
  451. s->parse_context.buffer_size=0;
  452. av_freep(&s->mb_type);
  453. av_freep(&s->p_mv_table_base);
  454. av_freep(&s->b_forw_mv_table_base);
  455. av_freep(&s->b_back_mv_table_base);
  456. av_freep(&s->b_bidir_forw_mv_table_base);
  457. av_freep(&s->b_bidir_back_mv_table_base);
  458. av_freep(&s->b_direct_mv_table_base);
  459. s->p_mv_table= NULL;
  460. s->b_forw_mv_table= NULL;
  461. s->b_back_mv_table= NULL;
  462. s->b_bidir_forw_mv_table= NULL;
  463. s->b_bidir_back_mv_table= NULL;
  464. s->b_direct_mv_table= NULL;
  465. av_freep(&s->motion_val);
  466. av_freep(&s->dc_val[0]);
  467. av_freep(&s->ac_val[0]);
  468. av_freep(&s->coded_block);
  469. av_freep(&s->mbintra_table);
  470. av_freep(&s->cbp_table);
  471. av_freep(&s->pred_dir_table);
  472. av_freep(&s->me.scratchpad);
  473. av_freep(&s->me.map);
  474. av_freep(&s->me.score_map);
  475. av_freep(&s->mbskip_table);
  476. av_freep(&s->prev_pict_types);
  477. av_freep(&s->bitstream_buffer);
  478. av_freep(&s->tex_pb_buffer);
  479. av_freep(&s->pb2_buffer);
  480. av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL;
  481. av_freep(&s->field_mv_table);
  482. av_freep(&s->field_select_table);
  483. av_freep(&s->avctx->stats_out);
  484. av_freep(&s->ac_stats);
  485. av_freep(&s->error_status_table);
  486. av_freep(&s->mb_index2xy);
  487. av_freep(&s->lambda_table);
  488. av_freep(&s->q_intra_matrix);
  489. av_freep(&s->q_inter_matrix);
  490. av_freep(&s->q_intra_matrix16);
  491. av_freep(&s->q_inter_matrix16);
  492. av_freep(&s->blocks);
  493. av_freep(&s->input_picture);
  494. av_freep(&s->reordered_input_picture);
  495. av_freep(&s->dct_error_sum);
  496. av_freep(&s->dct_offset);
  497. if(s->picture){
  498. for(i=0; i<MAX_PICTURE_COUNT; i++){
  499. free_picture(s, &s->picture[i]);
  500. }
  501. }
  502. av_freep(&s->picture);
  503. avcodec_default_free_buffers(s->avctx);
  504. s->context_initialized = 0;
  505. s->last_picture_ptr=
  506. s->next_picture_ptr=
  507. s->current_picture_ptr= NULL;
  508. }
  509. #ifdef CONFIG_ENCODERS
  510. /* init video encoder */
  511. int MPV_encode_init(AVCodecContext *avctx)
  512. {
  513. MpegEncContext *s = avctx->priv_data;
  514. int i, dummy;
  515. int chroma_h_shift, chroma_v_shift;
  516. avctx->pix_fmt = PIX_FMT_YUV420P; // FIXME
  517. s->bit_rate = avctx->bit_rate;
  518. s->bit_rate_tolerance = avctx->bit_rate_tolerance;
  519. s->width = avctx->width;
  520. s->height = avctx->height;
  521. if(avctx->gop_size > 600){
  522. av_log(avctx, AV_LOG_ERROR, "Warning keyframe interval too large! reducing it ...\n");
  523. avctx->gop_size=600;
  524. }
  525. s->gop_size = avctx->gop_size;
  526. s->rtp_mode = avctx->rtp_mode;
  527. s->rtp_payload_size = avctx->rtp_payload_size;
  528. if (avctx->rtp_callback)
  529. s->rtp_callback = avctx->rtp_callback;
  530. s->max_qdiff= avctx->max_qdiff;
  531. s->qcompress= avctx->qcompress;
  532. s->qblur= avctx->qblur;
  533. s->avctx = avctx;
  534. s->flags= avctx->flags;
  535. s->max_b_frames= avctx->max_b_frames;
  536. s->b_frame_strategy= avctx->b_frame_strategy;
  537. s->codec_id= avctx->codec->id;
  538. s->luma_elim_threshold = avctx->luma_elim_threshold;
  539. s->chroma_elim_threshold= avctx->chroma_elim_threshold;
  540. s->strict_std_compliance= avctx->strict_std_compliance;
  541. s->data_partitioning= avctx->flags & CODEC_FLAG_PART;
  542. s->quarter_sample= (avctx->flags & CODEC_FLAG_QPEL)!=0;
  543. s->mpeg_quant= avctx->mpeg_quant;
  544. if (s->gop_size <= 1) {
  545. s->intra_only = 1;
  546. s->gop_size = 12;
  547. } else {
  548. s->intra_only = 0;
  549. }
  550. s->me_method = avctx->me_method;
  551. /* Fixed QSCALE */
  552. s->fixed_qscale = (avctx->flags & CODEC_FLAG_QSCALE);
  553. s->adaptive_quant= ( s->avctx->lumi_masking
  554. || s->avctx->dark_masking
  555. || s->avctx->temporal_cplx_masking
  556. || s->avctx->spatial_cplx_masking
  557. || s->avctx->p_masking)
  558. && !s->fixed_qscale;
  559. s->progressive_sequence= !(avctx->flags & CODEC_FLAG_INTERLACED_DCT);
  560. if((s->flags & CODEC_FLAG_4MV) && s->codec_id != CODEC_ID_MPEG4){
  561. av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
  562. return -1;
  563. }
  564. if(s->quarter_sample && s->codec_id != CODEC_ID_MPEG4){
  565. av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
  566. return -1;
  567. }
  568. if(s->data_partitioning && s->codec_id != CODEC_ID_MPEG4){
  569. av_log(avctx, AV_LOG_ERROR, "data partitioning not supported by codec\n");
  570. return -1;
  571. }
  572. if(s->max_b_frames && s->codec_id != CODEC_ID_MPEG4 && s->codec_id != CODEC_ID_MPEG1VIDEO && s->codec_id != CODEC_ID_MPEG2VIDEO){
  573. av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
  574. return -1;
  575. }
  576. if(s->mpeg_quant && s->codec_id != CODEC_ID_MPEG4){ //FIXME mpeg2 uses that too
  577. av_log(avctx, AV_LOG_ERROR, "mpeg2 style quantization not supporetd by codec\n");
  578. return -1;
  579. }
  580. if((s->flags & CODEC_FLAG_CBP_RD) && !(s->flags & CODEC_FLAG_TRELLIS_QUANT)){
  581. av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
  582. return -1;
  583. }
  584. if(s->codec_id==CODEC_ID_MJPEG){
  585. s->intra_quant_bias= 1<<(QUANT_BIAS_SHIFT-1); //(a + x/2)/x
  586. s->inter_quant_bias= 0;
  587. }else if(s->mpeg_quant || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO){
  588. s->intra_quant_bias= 3<<(QUANT_BIAS_SHIFT-3); //(a + x*3/8)/x
  589. s->inter_quant_bias= 0;
  590. }else{
  591. s->intra_quant_bias=0;
  592. s->inter_quant_bias=-(1<<(QUANT_BIAS_SHIFT-2)); //(a - x/4)/x
  593. }
  594. if(avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
  595. s->intra_quant_bias= avctx->intra_quant_bias;
  596. if(avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
  597. s->inter_quant_bias= avctx->inter_quant_bias;
  598. avcodec_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift, &chroma_v_shift);
  599. av_reduce(&s->time_increment_resolution, &dummy, s->avctx->frame_rate, s->avctx->frame_rate_base, (1<<16)-1);
  600. s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;
  601. switch(avctx->codec->id) {
  602. case CODEC_ID_MPEG1VIDEO:
  603. s->out_format = FMT_MPEG1;
  604. s->low_delay= 0; //s->max_b_frames ? 0 : 1;
  605. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  606. break;
  607. case CODEC_ID_MPEG2VIDEO:
  608. s->out_format = FMT_MPEG1;
  609. s->low_delay= 0; //s->max_b_frames ? 0 : 1;
  610. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  611. s->rtp_mode= 1; // mpeg2 must have slices
  612. if(s->rtp_payload_size == 0) s->rtp_payload_size= 256*256*256;
  613. break;
  614. case CODEC_ID_LJPEG:
  615. case CODEC_ID_MJPEG:
  616. s->out_format = FMT_MJPEG;
  617. s->intra_only = 1; /* force intra only for jpeg */
  618. s->mjpeg_write_tables = 1; /* write all tables */
  619. s->mjpeg_data_only_frames = 0; /* write all the needed headers */
  620. s->mjpeg_vsample[0] = 1<<chroma_v_shift;
  621. s->mjpeg_vsample[1] = 1;
  622. s->mjpeg_vsample[2] = 1;
  623. s->mjpeg_hsample[0] = 1<<chroma_h_shift;
  624. s->mjpeg_hsample[1] = 1;
  625. s->mjpeg_hsample[2] = 1;
  626. if (mjpeg_init(s) < 0)
  627. return -1;
  628. avctx->delay=0;
  629. s->low_delay=1;
  630. break;
  631. #ifdef CONFIG_RISKY
  632. case CODEC_ID_H263:
  633. if (h263_get_picture_format(s->width, s->height) == 7) {
  634. av_log(avctx, AV_LOG_INFO, "Input picture size isn't suitable for h263 codec! try h263+\n");
  635. return -1;
  636. }
  637. s->out_format = FMT_H263;
  638. avctx->delay=0;
  639. s->low_delay=1;
  640. break;
  641. case CODEC_ID_H263P:
  642. s->out_format = FMT_H263;
  643. s->h263_plus = 1;
  644. /* Fx */
  645. s->unrestricted_mv=(avctx->flags & CODEC_FLAG_H263P_UMV) ? 1:0;
  646. s->h263_aic= (avctx->flags & CODEC_FLAG_H263P_AIC) ? 1:0;
  647. /* /Fx */
  648. /* These are just to be sure */
  649. s->umvplus = 1;
  650. avctx->delay=0;
  651. s->low_delay=1;
  652. break;
  653. case CODEC_ID_FLV1:
  654. s->out_format = FMT_H263;
  655. s->h263_flv = 2; /* format = 1; 11-bit codes */
  656. s->unrestricted_mv = 1;
  657. s->rtp_mode=0; /* don't allow GOB */
  658. avctx->delay=0;
  659. s->low_delay=1;
  660. break;
  661. case CODEC_ID_RV10:
  662. s->out_format = FMT_H263;
  663. s->h263_rv10 = 1;
  664. avctx->delay=0;
  665. s->low_delay=1;
  666. break;
  667. case CODEC_ID_MPEG4:
  668. s->out_format = FMT_H263;
  669. s->h263_pred = 1;
  670. s->unrestricted_mv = 1;
  671. s->low_delay= s->max_b_frames ? 0 : 1;
  672. avctx->delay= s->low_delay ? 0 : (s->max_b_frames + 1);
  673. break;
  674. case CODEC_ID_MSMPEG4V1:
  675. s->out_format = FMT_H263;
  676. s->h263_msmpeg4 = 1;
  677. s->h263_pred = 1;
  678. s->unrestricted_mv = 1;
  679. s->msmpeg4_version= 1;
  680. avctx->delay=0;
  681. s->low_delay=1;
  682. break;
  683. case CODEC_ID_MSMPEG4V2:
  684. s->out_format = FMT_H263;
  685. s->h263_msmpeg4 = 1;
  686. s->h263_pred = 1;
  687. s->unrestricted_mv = 1;
  688. s->msmpeg4_version= 2;
  689. avctx->delay=0;
  690. s->low_delay=1;
  691. break;
  692. case CODEC_ID_MSMPEG4V3:
  693. s->out_format = FMT_H263;
  694. s->h263_msmpeg4 = 1;
  695. s->h263_pred = 1;
  696. s->unrestricted_mv = 1;
  697. s->msmpeg4_version= 3;
  698. s->flipflop_rounding=1;
  699. avctx->delay=0;
  700. s->low_delay=1;
  701. break;
  702. case CODEC_ID_WMV1:
  703. s->out_format = FMT_H263;
  704. s->h263_msmpeg4 = 1;
  705. s->h263_pred = 1;
  706. s->unrestricted_mv = 1;
  707. s->msmpeg4_version= 4;
  708. s->flipflop_rounding=1;
  709. avctx->delay=0;
  710. s->low_delay=1;
  711. break;
  712. case CODEC_ID_WMV2:
  713. s->out_format = FMT_H263;
  714. s->h263_msmpeg4 = 1;
  715. s->h263_pred = 1;
  716. s->unrestricted_mv = 1;
  717. s->msmpeg4_version= 5;
  718. s->flipflop_rounding=1;
  719. avctx->delay=0;
  720. s->low_delay=1;
  721. break;
  722. #endif
  723. default:
  724. return -1;
  725. }
  726. { /* set up some save defaults, some codecs might override them later */
  727. static int done=0;
  728. if(!done){
  729. int i;
  730. done=1;
  731. default_mv_penalty= av_mallocz( sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1) );
  732. memset(default_mv_penalty, 0, sizeof(uint8_t)*(MAX_FCODE+1)*(2*MAX_MV+1));
  733. memset(default_fcode_tab , 0, sizeof(uint8_t)*(2*MAX_MV+1));
  734. for(i=-16; i<16; i++){
  735. default_fcode_tab[i + MAX_MV]= 1;
  736. }
  737. }
  738. }
  739. s->me.mv_penalty= default_mv_penalty;
  740. s->fcode_tab= default_fcode_tab;
  741. s->y_dc_scale_table=
  742. s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
  743. /* dont use mv_penalty table for crap MV as it would be confused */
  744. //FIXME remove after fixing / removing old ME
  745. if (s->me_method < ME_EPZS) s->me.mv_penalty = default_mv_penalty;
  746. s->encoding = 1;
  747. /* init */
  748. if (MPV_common_init(s) < 0)
  749. return -1;
  750. ff_init_me(s);
  751. #ifdef CONFIG_ENCODERS
  752. #ifdef CONFIG_RISKY
  753. if (s->out_format == FMT_H263)
  754. h263_encode_init(s);
  755. if(s->msmpeg4_version)
  756. ff_msmpeg4_encode_init(s);
  757. #endif
  758. if (s->out_format == FMT_MPEG1)
  759. ff_mpeg1_encode_init(s);
  760. #endif
  761. /* init default q matrix */
  762. for(i=0;i<64;i++) {
  763. int j= s->dsp.idct_permutation[i];
  764. #ifdef CONFIG_RISKY
  765. if(s->codec_id==CODEC_ID_MPEG4 && s->mpeg_quant){
  766. s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
  767. s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
  768. }else if(s->out_format == FMT_H263){
  769. s->intra_matrix[j] =
  770. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  771. }else
  772. #endif
  773. { /* mpeg1/2 */
  774. s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
  775. s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  776. }
  777. if(s->avctx->intra_matrix)
  778. s->intra_matrix[j] = s->avctx->intra_matrix[i];
  779. if(s->avctx->inter_matrix)
  780. s->inter_matrix[j] = s->avctx->inter_matrix[i];
  781. }
  782. /* precompute matrix */
  783. /* for mjpeg, we do include qscale in the matrix */
  784. if (s->out_format != FMT_MJPEG) {
  785. convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  786. s->intra_matrix, s->intra_quant_bias, 1, 31);
  787. convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,
  788. s->inter_matrix, s->inter_quant_bias, 1, 31);
  789. }
  790. if(ff_rate_control_init(s) < 0)
  791. return -1;
  792. s->picture_number = 0;
  793. s->picture_in_gop_number = 0;
  794. s->fake_picture_number = 0;
  795. /* motion detector init */
  796. s->f_code = 1;
  797. s->b_code = 1;
  798. return 0;
  799. }
  800. int MPV_encode_end(AVCodecContext *avctx)
  801. {
  802. MpegEncContext *s = avctx->priv_data;
  803. #ifdef STATS
  804. print_stats();
  805. #endif
  806. ff_rate_control_uninit(s);
  807. MPV_common_end(s);
  808. if (s->out_format == FMT_MJPEG)
  809. mjpeg_close(s);
  810. av_freep(&avctx->extradata);
  811. return 0;
  812. }
  813. #endif //CONFIG_ENCODERS
  814. void init_rl(RLTable *rl)
  815. {
  816. int8_t max_level[MAX_RUN+1], max_run[MAX_LEVEL+1];
  817. uint8_t index_run[MAX_RUN+1];
  818. int last, run, level, start, end, i;
  819. /* compute max_level[], max_run[] and index_run[] */
  820. for(last=0;last<2;last++) {
  821. if (last == 0) {
  822. start = 0;
  823. end = rl->last;
  824. } else {
  825. start = rl->last;
  826. end = rl->n;
  827. }
  828. memset(max_level, 0, MAX_RUN + 1);
  829. memset(max_run, 0, MAX_LEVEL + 1);
  830. memset(index_run, rl->n, MAX_RUN + 1);
  831. for(i=start;i<end;i++) {
  832. run = rl->table_run[i];
  833. level = rl->table_level[i];
  834. if (index_run[run] == rl->n)
  835. index_run[run] = i;
  836. if (level > max_level[run])
  837. max_level[run] = level;
  838. if (run > max_run[level])
  839. max_run[level] = run;
  840. }
  841. rl->max_level[last] = av_malloc(MAX_RUN + 1);
  842. memcpy(rl->max_level[last], max_level, MAX_RUN + 1);
  843. rl->max_run[last] = av_malloc(MAX_LEVEL + 1);
  844. memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);
  845. rl->index_run[last] = av_malloc(MAX_RUN + 1);
  846. memcpy(rl->index_run[last], index_run, MAX_RUN + 1);
  847. }
  848. }
  849. /* draw the edges of width 'w' of an image of size width, height */
  850. //FIXME check that this is ok for mpeg4 interlaced
  851. static void draw_edges_c(uint8_t *buf, int wrap, int width, int height, int w)
  852. {
  853. uint8_t *ptr, *last_line;
  854. int i;
  855. last_line = buf + (height - 1) * wrap;
  856. for(i=0;i<w;i++) {
  857. /* top and bottom */
  858. memcpy(buf - (i + 1) * wrap, buf, width);
  859. memcpy(last_line + (i + 1) * wrap, last_line, width);
  860. }
  861. /* left and right */
  862. ptr = buf;
  863. for(i=0;i<height;i++) {
  864. memset(ptr - w, ptr[0], w);
  865. memset(ptr + width, ptr[width-1], w);
  866. ptr += wrap;
  867. }
  868. /* corners */
  869. for(i=0;i<w;i++) {
  870. memset(buf - (i + 1) * wrap - w, buf[0], w); /* top left */
  871. memset(buf - (i + 1) * wrap + width, buf[width-1], w); /* top right */
  872. memset(last_line + (i + 1) * wrap - w, last_line[0], w); /* top left */
  873. memset(last_line + (i + 1) * wrap + width, last_line[width-1], w); /* top right */
  874. }
  875. }
  876. int ff_find_unused_picture(MpegEncContext *s, int shared){
  877. int i;
  878. if(shared){
  879. for(i=0; i<MAX_PICTURE_COUNT; i++){
  880. if(s->picture[i].data[0]==NULL && s->picture[i].type==0) return i;
  881. }
  882. }else{
  883. for(i=0; i<MAX_PICTURE_COUNT; i++){
  884. if(s->picture[i].data[0]==NULL && s->picture[i].type!=0) return i; //FIXME
  885. }
  886. for(i=0; i<MAX_PICTURE_COUNT; i++){
  887. if(s->picture[i].data[0]==NULL) return i;
  888. }
  889. }
  890. assert(0);
  891. return -1;
  892. }
  893. static void update_noise_reduction(MpegEncContext *s){
  894. int intra, i;
  895. for(intra=0; intra<2; intra++){
  896. if(s->dct_count[intra] > (1<<16)){
  897. for(i=0; i<64; i++){
  898. s->dct_error_sum[intra][i] >>=1;
  899. }
  900. s->dct_count[intra] >>= 1;
  901. }
  902. for(i=0; i<64; i++){
  903. s->dct_offset[intra][i]= (s->avctx->noise_reduction * s->dct_count[intra] + s->dct_error_sum[intra][i]/2) / (s->dct_error_sum[intra][i]+1);
  904. }
  905. }
  906. }
  907. /**
  908. * generic function for encode/decode called after coding/decoding the header and before a frame is coded/decoded
  909. */
  910. int MPV_frame_start(MpegEncContext *s, AVCodecContext *avctx)
  911. {
  912. int i;
  913. AVFrame *pic;
  914. s->mb_skiped = 0;
  915. assert(s->last_picture_ptr==NULL || s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3);
  916. /* mark&release old frames */
  917. if (s->pict_type != B_TYPE && s->last_picture_ptr && s->last_picture_ptr->data[0]) {
  918. avctx->release_buffer(avctx, (AVFrame*)s->last_picture_ptr);
  919. /* release forgotten pictures */
  920. /* if(mpeg124/h263) */
  921. if(!s->encoding){
  922. for(i=0; i<MAX_PICTURE_COUNT; i++){
  923. if(s->picture[i].data[0] && &s->picture[i] != s->next_picture_ptr && s->picture[i].reference){
  924. av_log(avctx, AV_LOG_ERROR, "releasing zombie picture\n");
  925. avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
  926. }
  927. }
  928. }
  929. }
  930. alloc:
  931. if(!s->encoding){
  932. /* release non refernce frames */
  933. for(i=0; i<MAX_PICTURE_COUNT; i++){
  934. if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
  935. s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
  936. }
  937. }
  938. if(s->current_picture_ptr && s->current_picture_ptr->data[0]==NULL)
  939. pic= (AVFrame*)s->current_picture_ptr; //we allready have a unused image (maybe it was set before reading the header)
  940. else{
  941. i= ff_find_unused_picture(s, 0);
  942. pic= (AVFrame*)&s->picture[i];
  943. }
  944. pic->reference= s->pict_type != B_TYPE ? 3 : 0;
  945. if(s->current_picture_ptr) //FIXME broken, we need a coded_picture_number in MpegEncContext
  946. pic->coded_picture_number= s->current_picture_ptr->coded_picture_number+1;
  947. if( alloc_picture(s, (Picture*)pic, 0) < 0)
  948. return -1;
  949. s->current_picture_ptr= (Picture*)pic;
  950. }
  951. s->current_picture_ptr->pict_type= s->pict_type;
  952. // if(s->flags && CODEC_FLAG_QSCALE)
  953. // s->current_picture_ptr->quality= s->new_picture_ptr->quality;
  954. s->current_picture_ptr->key_frame= s->pict_type == I_TYPE;
  955. copy_picture(&s->current_picture, s->current_picture_ptr);
  956. if(s->out_format != FMT_H264 || s->codec_id == CODEC_ID_SVQ3){
  957. if (s->pict_type != B_TYPE) {
  958. s->last_picture_ptr= s->next_picture_ptr;
  959. s->next_picture_ptr= s->current_picture_ptr;
  960. }
  961. if(s->last_picture_ptr) copy_picture(&s->last_picture, s->last_picture_ptr);
  962. if(s->next_picture_ptr) copy_picture(&s->next_picture, s->next_picture_ptr);
  963. if(s->pict_type != I_TYPE && (s->last_picture_ptr==NULL || s->last_picture_ptr->data[0]==NULL)){
  964. av_log(avctx, AV_LOG_ERROR, "warning: first frame is no keyframe\n");
  965. assert(s->pict_type != B_TYPE); //these should have been dropped if we dont have a reference
  966. goto alloc;
  967. }
  968. assert(s->pict_type == I_TYPE || (s->last_picture_ptr && s->last_picture_ptr->data[0]));
  969. if(s->picture_structure!=PICT_FRAME){
  970. int i;
  971. for(i=0; i<4; i++){
  972. if(s->picture_structure == PICT_BOTTOM_FIELD){
  973. s->current_picture.data[i] += s->current_picture.linesize[i];
  974. }
  975. s->current_picture.linesize[i] *= 2;
  976. s->last_picture.linesize[i] *=2;
  977. s->next_picture.linesize[i] *=2;
  978. }
  979. }
  980. }
  981. s->hurry_up= s->avctx->hurry_up;
  982. s->error_resilience= avctx->error_resilience;
  983. /* set dequantizer, we cant do it during init as it might change for mpeg4
  984. and we cant do it in the header decode as init isnt called for mpeg4 there yet */
  985. if(s->mpeg_quant || s->codec_id == CODEC_ID_MPEG2VIDEO)
  986. s->dct_unquantize = s->dct_unquantize_mpeg2;
  987. else if(s->out_format == FMT_H263)
  988. s->dct_unquantize = s->dct_unquantize_h263;
  989. else
  990. s->dct_unquantize = s->dct_unquantize_mpeg1;
  991. if(s->dct_error_sum){
  992. assert(s->avctx->noise_reduction && s->encoding);
  993. update_noise_reduction(s);
  994. }
  995. #ifdef HAVE_XVMC
  996. if(s->avctx->xvmc_acceleration)
  997. return XVMC_field_start(s, avctx);
  998. #endif
  999. return 0;
  1000. }
  1001. /* generic function for encode/decode called after a frame has been coded/decoded */
  1002. void MPV_frame_end(MpegEncContext *s)
  1003. {
  1004. int i;
  1005. /* draw edge for correct motion prediction if outside */
  1006. #ifdef HAVE_XVMC
  1007. //just to make sure that all data is rendered.
  1008. if(s->avctx->xvmc_acceleration){
  1009. XVMC_field_end(s);
  1010. }else
  1011. #endif
  1012. if(s->unrestricted_mv && s->pict_type != B_TYPE && !s->intra_only && !(s->flags&CODEC_FLAG_EMU_EDGE)) {
  1013. draw_edges(s->current_picture.data[0], s->linesize , s->h_edge_pos , s->v_edge_pos , EDGE_WIDTH );
  1014. draw_edges(s->current_picture.data[1], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  1015. draw_edges(s->current_picture.data[2], s->uvlinesize, s->h_edge_pos>>1, s->v_edge_pos>>1, EDGE_WIDTH/2);
  1016. }
  1017. emms_c();
  1018. s->last_pict_type = s->pict_type;
  1019. if(s->pict_type!=B_TYPE){
  1020. s->last_non_b_pict_type= s->pict_type;
  1021. }
  1022. #if 0
  1023. /* copy back current_picture variables */
  1024. for(i=0; i<MAX_PICTURE_COUNT; i++){
  1025. if(s->picture[i].data[0] == s->current_picture.data[0]){
  1026. s->picture[i]= s->current_picture;
  1027. break;
  1028. }
  1029. }
  1030. assert(i<MAX_PICTURE_COUNT);
  1031. #endif
  1032. if(s->encoding){
  1033. /* release non refernce frames */
  1034. for(i=0; i<MAX_PICTURE_COUNT; i++){
  1035. if(s->picture[i].data[0] && !s->picture[i].reference /*&& s->picture[i].type!=FF_BUFFER_TYPE_SHARED*/){
  1036. s->avctx->release_buffer(s->avctx, (AVFrame*)&s->picture[i]);
  1037. }
  1038. }
  1039. }
  1040. // clear copies, to avoid confusion
  1041. #if 0
  1042. memset(&s->last_picture, 0, sizeof(Picture));
  1043. memset(&s->next_picture, 0, sizeof(Picture));
  1044. memset(&s->current_picture, 0, sizeof(Picture));
  1045. #endif
  1046. }
  1047. /**
  1048. * draws an line from (ex, ey) -> (sx, sy).
  1049. * @param w width of the image
  1050. * @param h height of the image
  1051. * @param stride stride/linesize of the image
  1052. * @param color color of the arrow
  1053. */
  1054. static void draw_line(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  1055. int t, x, y, f;
  1056. sx= clip(sx, 0, w-1);
  1057. sy= clip(sy, 0, h-1);
  1058. ex= clip(ex, 0, w-1);
  1059. ey= clip(ey, 0, h-1);
  1060. buf[sy*stride + sx]+= color;
  1061. if(ABS(ex - sx) > ABS(ey - sy)){
  1062. if(sx > ex){
  1063. t=sx; sx=ex; ex=t;
  1064. t=sy; sy=ey; ey=t;
  1065. }
  1066. buf+= sx + sy*stride;
  1067. ex-= sx;
  1068. f= ((ey-sy)<<16)/ex;
  1069. for(x= 0; x <= ex; x++){
  1070. y= ((x*f) + (1<<15))>>16;
  1071. buf[y*stride + x]+= color;
  1072. }
  1073. }else{
  1074. if(sy > ey){
  1075. t=sx; sx=ex; ex=t;
  1076. t=sy; sy=ey; ey=t;
  1077. }
  1078. buf+= sx + sy*stride;
  1079. ey-= sy;
  1080. if(ey) f= ((ex-sx)<<16)/ey;
  1081. else f= 0;
  1082. for(y= 0; y <= ey; y++){
  1083. x= ((y*f) + (1<<15))>>16;
  1084. buf[y*stride + x]+= color;
  1085. }
  1086. }
  1087. }
  1088. /**
  1089. * draws an arrow from (ex, ey) -> (sx, sy).
  1090. * @param w width of the image
  1091. * @param h height of the image
  1092. * @param stride stride/linesize of the image
  1093. * @param color color of the arrow
  1094. */
  1095. static void draw_arrow(uint8_t *buf, int sx, int sy, int ex, int ey, int w, int h, int stride, int color){
  1096. int dx,dy;
  1097. sx= clip(sx, -100, w+100);
  1098. sy= clip(sy, -100, h+100);
  1099. ex= clip(ex, -100, w+100);
  1100. ey= clip(ey, -100, h+100);
  1101. dx= ex - sx;
  1102. dy= ey - sy;
  1103. if(dx*dx + dy*dy > 3*3){
  1104. int rx= dx + dy;
  1105. int ry= -dx + dy;
  1106. int length= ff_sqrt((rx*rx + ry*ry)<<8);
  1107. //FIXME subpixel accuracy
  1108. rx= ROUNDED_DIV(rx*3<<4, length);
  1109. ry= ROUNDED_DIV(ry*3<<4, length);
  1110. draw_line(buf, sx, sy, sx + rx, sy + ry, w, h, stride, color);
  1111. draw_line(buf, sx, sy, sx - ry, sy + rx, w, h, stride, color);
  1112. }
  1113. draw_line(buf, sx, sy, ex, ey, w, h, stride, color);
  1114. }
  1115. /**
  1116. * prints debuging info for the given picture.
  1117. */
  1118. void ff_print_debug_info(MpegEncContext *s, Picture *pict){
  1119. if(!pict || !pict->mb_type) return;
  1120. if(s->avctx->debug&(FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)){
  1121. int x,y;
  1122. for(y=0; y<s->mb_height; y++){
  1123. for(x=0; x<s->mb_width; x++){
  1124. if(s->avctx->debug&FF_DEBUG_SKIP){
  1125. int count= s->mbskip_table[x + y*s->mb_stride];
  1126. if(count>9) count=9;
  1127. av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);
  1128. }
  1129. if(s->avctx->debug&FF_DEBUG_QP){
  1130. av_log(s->avctx, AV_LOG_DEBUG, "%2d", pict->qscale_table[x + y*s->mb_stride]);
  1131. }
  1132. if(s->avctx->debug&FF_DEBUG_MB_TYPE){
  1133. int mb_type= pict->mb_type[x + y*s->mb_stride];
  1134. //Type & MV direction
  1135. if(IS_PCM(mb_type))
  1136. av_log(s->avctx, AV_LOG_DEBUG, "P");
  1137. else if(IS_INTRA(mb_type) && IS_ACPRED(mb_type))
  1138. av_log(s->avctx, AV_LOG_DEBUG, "A");
  1139. else if(IS_INTRA4x4(mb_type))
  1140. av_log(s->avctx, AV_LOG_DEBUG, "i");
  1141. else if(IS_INTRA16x16(mb_type))
  1142. av_log(s->avctx, AV_LOG_DEBUG, "I");
  1143. else if(IS_DIRECT(mb_type) && IS_SKIP(mb_type))
  1144. av_log(s->avctx, AV_LOG_DEBUG, "d");
  1145. else if(IS_DIRECT(mb_type))
  1146. av_log(s->avctx, AV_LOG_DEBUG, "D");
  1147. else if(IS_GMC(mb_type) && IS_SKIP(mb_type))
  1148. av_log(s->avctx, AV_LOG_DEBUG, "g");
  1149. else if(IS_GMC(mb_type))
  1150. av_log(s->avctx, AV_LOG_DEBUG, "G");
  1151. else if(IS_SKIP(mb_type))
  1152. av_log(s->avctx, AV_LOG_DEBUG, "S");
  1153. else if(!USES_LIST(mb_type, 1))
  1154. av_log(s->avctx, AV_LOG_DEBUG, ">");
  1155. else if(!USES_LIST(mb_type, 0))
  1156. av_log(s->avctx, AV_LOG_DEBUG, "<");
  1157. else{
  1158. assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));
  1159. av_log(s->avctx, AV_LOG_DEBUG, "X");
  1160. }
  1161. //segmentation
  1162. if(IS_8X8(mb_type))
  1163. av_log(s->avctx, AV_LOG_DEBUG, "+");
  1164. else if(IS_16X8(mb_type))
  1165. av_log(s->avctx, AV_LOG_DEBUG, "-");
  1166. else if(IS_8X16(mb_type))
  1167. av_log(s->avctx, AV_LOG_DEBUG, "¦");
  1168. else if(IS_INTRA(mb_type) || IS_16X16(mb_type))
  1169. av_log(s->avctx, AV_LOG_DEBUG, " ");
  1170. else
  1171. av_log(s->avctx, AV_LOG_DEBUG, "?");
  1172. if(IS_INTERLACED(mb_type) && s->codec_id == CODEC_ID_H264)
  1173. av_log(s->avctx, AV_LOG_DEBUG, "=");
  1174. else
  1175. av_log(s->avctx, AV_LOG_DEBUG, " ");
  1176. }
  1177. // av_log(s->avctx, AV_LOG_DEBUG, " ");
  1178. }
  1179. av_log(s->avctx, AV_LOG_DEBUG, "\n");
  1180. }
  1181. }
  1182. if((s->avctx->debug&FF_DEBUG_VIS_MV) && s->motion_val){
  1183. const int shift= 1 + s->quarter_sample;
  1184. int mb_y;
  1185. uint8_t *ptr= pict->data[0];
  1186. s->low_delay=0; //needed to see the vectors without trashing the buffers
  1187. for(mb_y=0; mb_y<s->mb_height; mb_y++){
  1188. int mb_x;
  1189. for(mb_x=0; mb_x<s->mb_width; mb_x++){
  1190. const int mb_index= mb_x + mb_y*s->mb_stride;
  1191. if(IS_8X8(s->current_picture.mb_type[mb_index])){
  1192. int i;
  1193. for(i=0; i<4; i++){
  1194. int sx= mb_x*16 + 4 + 8*(i&1);
  1195. int sy= mb_y*16 + 4 + 8*(i>>1);
  1196. int xy= 1 + mb_x*2 + (i&1) + (mb_y*2 + 1 + (i>>1))*(s->mb_width*2 + 2);
  1197. int mx= (s->motion_val[xy][0]>>shift) + sx;
  1198. int my= (s->motion_val[xy][1]>>shift) + sy;
  1199. draw_arrow(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);
  1200. }
  1201. }else{
  1202. int sx= mb_x*16 + 8;
  1203. int sy= mb_y*16 + 8;
  1204. int xy= 1 + mb_x*2 + (mb_y*2 + 1)*(s->mb_width*2 + 2);
  1205. int mx= (s->motion_val[xy][0]>>shift) + sx;
  1206. int my= (s->motion_val[xy][1]>>shift) + sy;
  1207. draw_arrow(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);
  1208. }
  1209. s->mbskip_table[mb_index]=0;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. #ifdef CONFIG_ENCODERS
  1215. static int get_sae(uint8_t *src, int ref, int stride){
  1216. int x,y;
  1217. int acc=0;
  1218. for(y=0; y<16; y++){
  1219. for(x=0; x<16; x++){
  1220. acc+= ABS(src[x+y*stride] - ref);
  1221. }
  1222. }
  1223. return acc;
  1224. }
  1225. static int get_intra_count(MpegEncContext *s, uint8_t *src, uint8_t *ref, int stride){
  1226. int x, y, w, h;
  1227. int acc=0;
  1228. w= s->width &~15;
  1229. h= s->height&~15;
  1230. for(y=0; y<h; y+=16){
  1231. for(x=0; x<w; x+=16){
  1232. int offset= x + y*stride;
  1233. int sad = s->dsp.pix_abs16x16(src + offset, ref + offset, stride);
  1234. int mean= (s->dsp.pix_sum(src + offset, stride) + 128)>>8;
  1235. int sae = get_sae(src + offset, mean, stride);
  1236. acc+= sae + 500 < sad;
  1237. }
  1238. }
  1239. return acc;
  1240. }
  1241. static int load_input_picture(MpegEncContext *s, AVFrame *pic_arg){
  1242. AVFrame *pic=NULL;
  1243. int i;
  1244. const int encoding_delay= s->max_b_frames;
  1245. int direct=1;
  1246. if(pic_arg){
  1247. if(encoding_delay && !(s->flags&CODEC_FLAG_INPUT_PRESERVED)) direct=0;
  1248. if(pic_arg->linesize[0] != s->linesize) direct=0;
  1249. if(pic_arg->linesize[1] != s->uvlinesize) direct=0;
  1250. if(pic_arg->linesize[2] != s->uvlinesize) direct=0;
  1251. // av_log(AV_LOG_DEBUG, "%d %d %d %d\n",pic_arg->linesize[0], pic_arg->linesize[1], s->linesize, s->uvlinesize);
  1252. if(direct){
  1253. i= ff_find_unused_picture(s, 1);
  1254. pic= (AVFrame*)&s->picture[i];
  1255. pic->reference= 3;
  1256. for(i=0; i<4; i++){
  1257. pic->data[i]= pic_arg->data[i];
  1258. pic->linesize[i]= pic_arg->linesize[i];
  1259. }
  1260. alloc_picture(s, (Picture*)pic, 1);
  1261. }else{
  1262. int offset= 16;
  1263. i= ff_find_unused_picture(s, 0);
  1264. pic= (AVFrame*)&s->picture[i];
  1265. pic->reference= 3;
  1266. alloc_picture(s, (Picture*)pic, 0);
  1267. if( pic->data[0] + offset == pic_arg->data[0]
  1268. && pic->data[1] + offset == pic_arg->data[1]
  1269. && pic->data[2] + offset == pic_arg->data[2]){
  1270. // empty
  1271. }else{
  1272. int h_chroma_shift, v_chroma_shift;
  1273. avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  1274. for(i=0; i<3; i++){
  1275. int src_stride= pic_arg->linesize[i];
  1276. int dst_stride= i ? s->uvlinesize : s->linesize;
  1277. int h_shift= i ? h_chroma_shift : 0;
  1278. int v_shift= i ? v_chroma_shift : 0;
  1279. int w= s->width >>h_shift;
  1280. int h= s->height>>v_shift;
  1281. uint8_t *src= pic_arg->data[i];
  1282. uint8_t *dst= pic->data[i] + offset;
  1283. if(src_stride==dst_stride)
  1284. memcpy(dst, src, src_stride*h);
  1285. else{
  1286. while(h--){
  1287. memcpy(dst, src, w);
  1288. dst += dst_stride;
  1289. src += src_stride;
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. pic->quality= pic_arg->quality;
  1296. pic->pict_type= pic_arg->pict_type;
  1297. pic->pts = pic_arg->pts;
  1298. if(s->input_picture[encoding_delay])
  1299. pic->display_picture_number= s->input_picture[encoding_delay]->display_picture_number + 1;
  1300. }
  1301. /* shift buffer entries */
  1302. for(i=1; i<MAX_PICTURE_COUNT /*s->encoding_delay+1*/; i++)
  1303. s->input_picture[i-1]= s->input_picture[i];
  1304. s->input_picture[encoding_delay]= (Picture*)pic;
  1305. return 0;
  1306. }
  1307. static void select_input_picture(MpegEncContext *s){
  1308. int i;
  1309. int coded_pic_num=0;
  1310. if(s->reordered_input_picture[0])
  1311. coded_pic_num= s->reordered_input_picture[0]->coded_picture_number + 1;
  1312. for(i=1; i<MAX_PICTURE_COUNT; i++)
  1313. s->reordered_input_picture[i-1]= s->reordered_input_picture[i];
  1314. s->reordered_input_picture[MAX_PICTURE_COUNT-1]= NULL;
  1315. /* set next picture types & ordering */
  1316. if(s->reordered_input_picture[0]==NULL && s->input_picture[0]){
  1317. if(/*s->picture_in_gop_number >= s->gop_size ||*/ s->next_picture_ptr==NULL || s->intra_only){
  1318. s->reordered_input_picture[0]= s->input_picture[0];
  1319. s->reordered_input_picture[0]->pict_type= I_TYPE;
  1320. s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
  1321. }else{
  1322. int b_frames;
  1323. if(s->flags&CODEC_FLAG_PASS2){
  1324. for(i=0; i<s->max_b_frames+1; i++){
  1325. int pict_num= s->input_picture[0]->display_picture_number + i;
  1326. int pict_type= s->rc_context.entry[pict_num].new_pict_type;
  1327. s->input_picture[i]->pict_type= pict_type;
  1328. if(i + 1 >= s->rc_context.num_entries) break;
  1329. }
  1330. }
  1331. if(s->input_picture[0]->pict_type){
  1332. /* user selected pict_type */
  1333. for(b_frames=0; b_frames<s->max_b_frames+1; b_frames++){
  1334. if(s->input_picture[b_frames]->pict_type!=B_TYPE) break;
  1335. }
  1336. if(b_frames > s->max_b_frames){
  1337. av_log(s->avctx, AV_LOG_ERROR, "warning, too many bframes in a row\n");
  1338. b_frames = s->max_b_frames;
  1339. }
  1340. }else if(s->b_frame_strategy==0){
  1341. b_frames= s->max_b_frames;
  1342. while(b_frames && !s->input_picture[b_frames]) b_frames--;
  1343. }else if(s->b_frame_strategy==1){
  1344. for(i=1; i<s->max_b_frames+1; i++){
  1345. if(s->input_picture[i] && s->input_picture[i]->b_frame_score==0){
  1346. s->input_picture[i]->b_frame_score=
  1347. get_intra_count(s, s->input_picture[i ]->data[0],
  1348. s->input_picture[i-1]->data[0], s->linesize) + 1;
  1349. }
  1350. }
  1351. for(i=0; i<s->max_b_frames; i++){
  1352. if(s->input_picture[i]==NULL || s->input_picture[i]->b_frame_score - 1 > s->mb_num/40) break;
  1353. }
  1354. b_frames= FFMAX(0, i-1);
  1355. /* reset scores */
  1356. for(i=0; i<b_frames+1; i++){
  1357. s->input_picture[i]->b_frame_score=0;
  1358. }
  1359. }else{
  1360. av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  1361. b_frames=0;
  1362. }
  1363. emms_c();
  1364. //static int b_count=0;
  1365. //b_count+= b_frames;
  1366. //av_log(s->avctx, AV_LOG_DEBUG, "b_frames: %d\n", b_count);
  1367. s->reordered_input_picture[0]= s->input_picture[b_frames];
  1368. if( s->picture_in_gop_number + b_frames >= s->gop_size
  1369. || s->reordered_input_picture[0]->pict_type== I_TYPE)
  1370. s->reordered_input_picture[0]->pict_type= I_TYPE;
  1371. else
  1372. s->reordered_input_picture[0]->pict_type= P_TYPE;
  1373. s->reordered_input_picture[0]->coded_picture_number= coded_pic_num;
  1374. for(i=0; i<b_frames; i++){
  1375. coded_pic_num++;
  1376. s->reordered_input_picture[i+1]= s->input_picture[i];
  1377. s->reordered_input_picture[i+1]->pict_type= B_TYPE;
  1378. s->reordered_input_picture[i+1]->coded_picture_number= coded_pic_num;
  1379. }
  1380. }
  1381. }
  1382. if(s->reordered_input_picture[0]){
  1383. s->reordered_input_picture[0]->reference= s->reordered_input_picture[0]->pict_type!=B_TYPE ? 3 : 0;
  1384. copy_picture(&s->new_picture, s->reordered_input_picture[0]);
  1385. if(s->reordered_input_picture[0]->type == FF_BUFFER_TYPE_SHARED){
  1386. // input is a shared pix, so we cant modifiy it -> alloc a new one & ensure that the shared one is reuseable
  1387. int i= ff_find_unused_picture(s, 0);
  1388. Picture *pic= &s->picture[i];
  1389. /* mark us unused / free shared pic */
  1390. for(i=0; i<4; i++)
  1391. s->reordered_input_picture[0]->data[i]= NULL;
  1392. s->reordered_input_picture[0]->type= 0;
  1393. //FIXME bad, copy * except
  1394. pic->pict_type = s->reordered_input_picture[0]->pict_type;
  1395. pic->quality = s->reordered_input_picture[0]->quality;
  1396. pic->coded_picture_number = s->reordered_input_picture[0]->coded_picture_number;
  1397. pic->reference = s->reordered_input_picture[0]->reference;
  1398. pic->pts = s->reordered_input_picture[0]->pts;
  1399. alloc_picture(s, pic, 0);
  1400. s->current_picture_ptr= pic;
  1401. }else{
  1402. // input is not a shared pix -> reuse buffer for current_pix
  1403. assert( s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_USER
  1404. || s->reordered_input_picture[0]->type==FF_BUFFER_TYPE_INTERNAL);
  1405. s->current_picture_ptr= s->reordered_input_picture[0];
  1406. for(i=0; i<4; i++){
  1407. s->new_picture.data[i]+=16;
  1408. }
  1409. }
  1410. copy_picture(&s->current_picture, s->current_picture_ptr);
  1411. s->picture_number= s->new_picture.display_picture_number;
  1412. //printf("dpn:%d\n", s->picture_number);
  1413. }else{
  1414. memset(&s->new_picture, 0, sizeof(Picture));
  1415. }
  1416. }
  1417. int MPV_encode_picture(AVCodecContext *avctx,
  1418. unsigned char *buf, int buf_size, void *data)
  1419. {
  1420. MpegEncContext *s = avctx->priv_data;
  1421. AVFrame *pic_arg = data;
  1422. int i;
  1423. if(avctx->pix_fmt != PIX_FMT_YUV420P){
  1424. av_log(avctx, AV_LOG_ERROR, "this codec supports only YUV420P\n");
  1425. return -1;
  1426. }
  1427. init_put_bits(&s->pb, buf, buf_size);
  1428. s->picture_in_gop_number++;
  1429. load_input_picture(s, pic_arg);
  1430. select_input_picture(s);
  1431. /* output? */
  1432. if(s->new_picture.data[0]){
  1433. s->pict_type= s->new_picture.pict_type;
  1434. //emms_c();
  1435. //printf("qs:%f %f %d\n", s->new_picture.quality, s->current_picture.quality, s->qscale);
  1436. MPV_frame_start(s, avctx);
  1437. encode_picture(s, s->picture_number);
  1438. avctx->real_pict_num = s->picture_number;
  1439. avctx->header_bits = s->header_bits;
  1440. avctx->mv_bits = s->mv_bits;
  1441. avctx->misc_bits = s->misc_bits;
  1442. avctx->i_tex_bits = s->i_tex_bits;
  1443. avctx->p_tex_bits = s->p_tex_bits;
  1444. avctx->i_count = s->i_count;
  1445. avctx->p_count = s->mb_num - s->i_count - s->skip_count; //FIXME f/b_count in avctx
  1446. avctx->skip_count = s->skip_count;
  1447. MPV_frame_end(s);
  1448. if (s->out_format == FMT_MJPEG)
  1449. mjpeg_picture_trailer(s);
  1450. if(s->flags&CODEC_FLAG_PASS1)
  1451. ff_write_pass1_stats(s);
  1452. for(i=0; i<4; i++){
  1453. avctx->error[i] += s->current_picture_ptr->error[i];
  1454. }
  1455. }
  1456. s->input_picture_number++;
  1457. flush_put_bits(&s->pb);
  1458. s->frame_bits = (pbBufPtr(&s->pb) - s->pb.buf) * 8;
  1459. s->total_bits += s->frame_bits;
  1460. avctx->frame_bits = s->frame_bits;
  1461. return pbBufPtr(&s->pb) - s->pb.buf;
  1462. }
  1463. #endif //CONFIG_ENCODERS
  1464. static inline void gmc1_motion(MpegEncContext *s,
  1465. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1466. int dest_offset,
  1467. uint8_t **ref_picture, int src_offset)
  1468. {
  1469. uint8_t *ptr;
  1470. int offset, src_x, src_y, linesize, uvlinesize;
  1471. int motion_x, motion_y;
  1472. int emu=0;
  1473. motion_x= s->sprite_offset[0][0];
  1474. motion_y= s->sprite_offset[0][1];
  1475. src_x = s->mb_x * 16 + (motion_x >> (s->sprite_warping_accuracy+1));
  1476. src_y = s->mb_y * 16 + (motion_y >> (s->sprite_warping_accuracy+1));
  1477. motion_x<<=(3-s->sprite_warping_accuracy);
  1478. motion_y<<=(3-s->sprite_warping_accuracy);
  1479. src_x = clip(src_x, -16, s->width);
  1480. if (src_x == s->width)
  1481. motion_x =0;
  1482. src_y = clip(src_y, -16, s->height);
  1483. if (src_y == s->height)
  1484. motion_y =0;
  1485. linesize = s->linesize;
  1486. uvlinesize = s->uvlinesize;
  1487. ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
  1488. dest_y+=dest_offset;
  1489. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1490. if( (unsigned)src_x >= s->h_edge_pos - 17
  1491. || (unsigned)src_y >= s->v_edge_pos - 17){
  1492. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, linesize, 17, 17, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
  1493. ptr= s->edge_emu_buffer;
  1494. }
  1495. }
  1496. if((motion_x|motion_y)&7){
  1497. s->dsp.gmc1(dest_y , ptr , linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
  1498. s->dsp.gmc1(dest_y+8, ptr+8, linesize, 16, motion_x&15, motion_y&15, 128 - s->no_rounding);
  1499. }else{
  1500. int dxy;
  1501. dxy= ((motion_x>>3)&1) | ((motion_y>>2)&2);
  1502. if (s->no_rounding){
  1503. s->dsp.put_no_rnd_pixels_tab[0][dxy](dest_y, ptr, linesize, 16);
  1504. }else{
  1505. s->dsp.put_pixels_tab [0][dxy](dest_y, ptr, linesize, 16);
  1506. }
  1507. }
  1508. if(s->flags&CODEC_FLAG_GRAY) return;
  1509. motion_x= s->sprite_offset[1][0];
  1510. motion_y= s->sprite_offset[1][1];
  1511. src_x = s->mb_x * 8 + (motion_x >> (s->sprite_warping_accuracy+1));
  1512. src_y = s->mb_y * 8 + (motion_y >> (s->sprite_warping_accuracy+1));
  1513. motion_x<<=(3-s->sprite_warping_accuracy);
  1514. motion_y<<=(3-s->sprite_warping_accuracy);
  1515. src_x = clip(src_x, -8, s->width>>1);
  1516. if (src_x == s->width>>1)
  1517. motion_x =0;
  1518. src_y = clip(src_y, -8, s->height>>1);
  1519. if (src_y == s->height>>1)
  1520. motion_y =0;
  1521. offset = (src_y * uvlinesize) + src_x + (src_offset>>1);
  1522. ptr = ref_picture[1] + offset;
  1523. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1524. if( (unsigned)src_x >= (s->h_edge_pos>>1) - 9
  1525. || (unsigned)src_y >= (s->v_edge_pos>>1) - 9){
  1526. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1527. ptr= s->edge_emu_buffer;
  1528. emu=1;
  1529. }
  1530. }
  1531. s->dsp.gmc1(dest_cb + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
  1532. ptr = ref_picture[2] + offset;
  1533. if(emu){
  1534. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1535. ptr= s->edge_emu_buffer;
  1536. }
  1537. s->dsp.gmc1(dest_cr + (dest_offset>>1), ptr, uvlinesize, 8, motion_x&15, motion_y&15, 128 - s->no_rounding);
  1538. return;
  1539. }
  1540. static inline void gmc_motion(MpegEncContext *s,
  1541. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1542. int dest_offset,
  1543. uint8_t **ref_picture, int src_offset)
  1544. {
  1545. uint8_t *ptr;
  1546. int linesize, uvlinesize;
  1547. const int a= s->sprite_warping_accuracy;
  1548. int ox, oy;
  1549. linesize = s->linesize;
  1550. uvlinesize = s->uvlinesize;
  1551. ptr = ref_picture[0] + src_offset;
  1552. dest_y+=dest_offset;
  1553. ox= s->sprite_offset[0][0] + s->sprite_delta[0][0]*s->mb_x*16 + s->sprite_delta[0][1]*s->mb_y*16;
  1554. oy= s->sprite_offset[0][1] + s->sprite_delta[1][0]*s->mb_x*16 + s->sprite_delta[1][1]*s->mb_y*16;
  1555. s->dsp.gmc(dest_y, ptr, linesize, 16,
  1556. ox,
  1557. oy,
  1558. s->sprite_delta[0][0], s->sprite_delta[0][1],
  1559. s->sprite_delta[1][0], s->sprite_delta[1][1],
  1560. a+1, (1<<(2*a+1)) - s->no_rounding,
  1561. s->h_edge_pos, s->v_edge_pos);
  1562. s->dsp.gmc(dest_y+8, ptr, linesize, 16,
  1563. ox + s->sprite_delta[0][0]*8,
  1564. oy + s->sprite_delta[1][0]*8,
  1565. s->sprite_delta[0][0], s->sprite_delta[0][1],
  1566. s->sprite_delta[1][0], s->sprite_delta[1][1],
  1567. a+1, (1<<(2*a+1)) - s->no_rounding,
  1568. s->h_edge_pos, s->v_edge_pos);
  1569. if(s->flags&CODEC_FLAG_GRAY) return;
  1570. dest_cb+=dest_offset>>1;
  1571. dest_cr+=dest_offset>>1;
  1572. ox= s->sprite_offset[1][0] + s->sprite_delta[0][0]*s->mb_x*8 + s->sprite_delta[0][1]*s->mb_y*8;
  1573. oy= s->sprite_offset[1][1] + s->sprite_delta[1][0]*s->mb_x*8 + s->sprite_delta[1][1]*s->mb_y*8;
  1574. ptr = ref_picture[1] + (src_offset>>1);
  1575. s->dsp.gmc(dest_cb, ptr, uvlinesize, 8,
  1576. ox,
  1577. oy,
  1578. s->sprite_delta[0][0], s->sprite_delta[0][1],
  1579. s->sprite_delta[1][0], s->sprite_delta[1][1],
  1580. a+1, (1<<(2*a+1)) - s->no_rounding,
  1581. s->h_edge_pos>>1, s->v_edge_pos>>1);
  1582. ptr = ref_picture[2] + (src_offset>>1);
  1583. s->dsp.gmc(dest_cr, ptr, uvlinesize, 8,
  1584. ox,
  1585. oy,
  1586. s->sprite_delta[0][0], s->sprite_delta[0][1],
  1587. s->sprite_delta[1][0], s->sprite_delta[1][1],
  1588. a+1, (1<<(2*a+1)) - s->no_rounding,
  1589. s->h_edge_pos>>1, s->v_edge_pos>>1);
  1590. }
  1591. /**
  1592. * Copies a rectangular area of samples to a temporary buffer and replicates the boarder samples.
  1593. * @param buf destination buffer
  1594. * @param src source buffer
  1595. * @param linesize number of bytes between 2 vertically adjacent samples in both the source and destination buffers
  1596. * @param block_w width of block
  1597. * @param block_h height of block
  1598. * @param src_x x coordinate of the top left sample of the block in the source buffer
  1599. * @param src_y y coordinate of the top left sample of the block in the source buffer
  1600. * @param w width of the source buffer
  1601. * @param h height of the source buffer
  1602. */
  1603. void ff_emulated_edge_mc(uint8_t *buf, uint8_t *src, int linesize, int block_w, int block_h,
  1604. int src_x, int src_y, int w, int h){
  1605. int x, y;
  1606. int start_y, start_x, end_y, end_x;
  1607. if(src_y>= h){
  1608. src+= (h-1-src_y)*linesize;
  1609. src_y=h-1;
  1610. }else if(src_y<=-block_h){
  1611. src+= (1-block_h-src_y)*linesize;
  1612. src_y=1-block_h;
  1613. }
  1614. if(src_x>= w){
  1615. src+= (w-1-src_x);
  1616. src_x=w-1;
  1617. }else if(src_x<=-block_w){
  1618. src+= (1-block_w-src_x);
  1619. src_x=1-block_w;
  1620. }
  1621. start_y= FFMAX(0, -src_y);
  1622. start_x= FFMAX(0, -src_x);
  1623. end_y= FFMIN(block_h, h-src_y);
  1624. end_x= FFMIN(block_w, w-src_x);
  1625. // copy existing part
  1626. for(y=start_y; y<end_y; y++){
  1627. for(x=start_x; x<end_x; x++){
  1628. buf[x + y*linesize]= src[x + y*linesize];
  1629. }
  1630. }
  1631. //top
  1632. for(y=0; y<start_y; y++){
  1633. for(x=start_x; x<end_x; x++){
  1634. buf[x + y*linesize]= buf[x + start_y*linesize];
  1635. }
  1636. }
  1637. //bottom
  1638. for(y=end_y; y<block_h; y++){
  1639. for(x=start_x; x<end_x; x++){
  1640. buf[x + y*linesize]= buf[x + (end_y-1)*linesize];
  1641. }
  1642. }
  1643. for(y=0; y<block_h; y++){
  1644. //left
  1645. for(x=0; x<start_x; x++){
  1646. buf[x + y*linesize]= buf[start_x + y*linesize];
  1647. }
  1648. //right
  1649. for(x=end_x; x<block_w; x++){
  1650. buf[x + y*linesize]= buf[end_x - 1 + y*linesize];
  1651. }
  1652. }
  1653. }
  1654. /* apply one mpeg motion vector to the three components */
  1655. static inline void mpeg_motion(MpegEncContext *s,
  1656. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1657. int dest_offset,
  1658. uint8_t **ref_picture, int src_offset,
  1659. int field_based, op_pixels_func (*pix_op)[4],
  1660. int motion_x, int motion_y, int h)
  1661. {
  1662. uint8_t *ptr;
  1663. int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
  1664. int emu=0;
  1665. #if 0
  1666. if(s->quarter_sample)
  1667. {
  1668. motion_x>>=1;
  1669. motion_y>>=1;
  1670. }
  1671. #endif
  1672. dxy = ((motion_y & 1) << 1) | (motion_x & 1);
  1673. src_x = s->mb_x * 16 + (motion_x >> 1);
  1674. src_y = s->mb_y * (16 >> field_based) + (motion_y >> 1);
  1675. /* WARNING: do no forget half pels */
  1676. height = s->height >> field_based;
  1677. v_edge_pos = s->v_edge_pos >> field_based;
  1678. src_x = clip(src_x, -16, s->width);
  1679. if (src_x == s->width)
  1680. dxy &= ~1;
  1681. src_y = clip(src_y, -16, height);
  1682. if (src_y == height)
  1683. dxy &= ~2;
  1684. linesize = s->current_picture.linesize[0] << field_based;
  1685. uvlinesize = s->current_picture.linesize[1] << field_based;
  1686. ptr = ref_picture[0] + (src_y * linesize) + (src_x) + src_offset;
  1687. dest_y += dest_offset;
  1688. if(s->unrestricted_mv && (s->flags&CODEC_FLAG_EMU_EDGE)){
  1689. if( (unsigned)src_x > s->h_edge_pos - (motion_x&1) - 16
  1690. || (unsigned)src_y > v_edge_pos - (motion_y&1) - h){
  1691. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - src_offset, s->linesize, 17, 17+field_based, //FIXME linesize? and uv below
  1692. src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
  1693. ptr= s->edge_emu_buffer + src_offset;
  1694. emu=1;
  1695. }
  1696. }
  1697. pix_op[0][dxy](dest_y, ptr, linesize, h);
  1698. if(s->flags&CODEC_FLAG_GRAY) return;
  1699. if (s->out_format == FMT_H263) {
  1700. dxy = 0;
  1701. if ((motion_x & 3) != 0)
  1702. dxy |= 1;
  1703. if ((motion_y & 3) != 0)
  1704. dxy |= 2;
  1705. mx = motion_x >> 2;
  1706. my = motion_y >> 2;
  1707. } else {
  1708. mx = motion_x / 2;
  1709. my = motion_y / 2;
  1710. dxy = ((my & 1) << 1) | (mx & 1);
  1711. mx >>= 1;
  1712. my >>= 1;
  1713. }
  1714. src_x = s->mb_x * 8 + mx;
  1715. src_y = s->mb_y * (8 >> field_based) + my;
  1716. src_x = clip(src_x, -8, s->width >> 1);
  1717. if (src_x == (s->width >> 1))
  1718. dxy &= ~1;
  1719. src_y = clip(src_y, -8, height >> 1);
  1720. if (src_y == (height >> 1))
  1721. dxy &= ~2;
  1722. offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
  1723. ptr = ref_picture[1] + offset;
  1724. if(emu){
  1725. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based,
  1726. src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1727. ptr= s->edge_emu_buffer + (src_offset >> 1);
  1728. }
  1729. pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
  1730. ptr = ref_picture[2] + offset;
  1731. if(emu){
  1732. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - (src_offset >> 1), s->uvlinesize, 9, 9+field_based,
  1733. src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1734. ptr= s->edge_emu_buffer + (src_offset >> 1);
  1735. }
  1736. pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
  1737. }
  1738. static inline void qpel_motion(MpegEncContext *s,
  1739. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1740. int dest_offset,
  1741. uint8_t **ref_picture, int src_offset,
  1742. int field_based, op_pixels_func (*pix_op)[4],
  1743. qpel_mc_func (*qpix_op)[16],
  1744. int motion_x, int motion_y, int h)
  1745. {
  1746. uint8_t *ptr;
  1747. int dxy, offset, mx, my, src_x, src_y, height, v_edge_pos, linesize, uvlinesize;
  1748. int emu=0;
  1749. dxy = ((motion_y & 3) << 2) | (motion_x & 3);
  1750. src_x = s->mb_x * 16 + (motion_x >> 2);
  1751. src_y = s->mb_y * (16 >> field_based) + (motion_y >> 2);
  1752. height = s->height >> field_based;
  1753. v_edge_pos = s->v_edge_pos >> field_based;
  1754. src_x = clip(src_x, -16, s->width);
  1755. if (src_x == s->width)
  1756. dxy &= ~3;
  1757. src_y = clip(src_y, -16, height);
  1758. if (src_y == height)
  1759. dxy &= ~12;
  1760. linesize = s->linesize << field_based;
  1761. uvlinesize = s->uvlinesize << field_based;
  1762. ptr = ref_picture[0] + (src_y * linesize) + src_x + src_offset;
  1763. dest_y += dest_offset;
  1764. //printf("%d %d %d\n", src_x, src_y, dxy);
  1765. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1766. if( (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 16
  1767. || (unsigned)src_y > v_edge_pos - (motion_y&3) - h ){
  1768. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - src_offset, s->linesize, 17, 17+field_based,
  1769. src_x, src_y<<field_based, s->h_edge_pos, s->v_edge_pos);
  1770. ptr= s->edge_emu_buffer + src_offset;
  1771. emu=1;
  1772. }
  1773. }
  1774. if(!field_based)
  1775. qpix_op[0][dxy](dest_y, ptr, linesize);
  1776. else{
  1777. //damn interlaced mode
  1778. //FIXME boundary mirroring is not exactly correct here
  1779. qpix_op[1][dxy](dest_y , ptr , linesize);
  1780. qpix_op[1][dxy](dest_y+8, ptr+8, linesize);
  1781. }
  1782. if(s->flags&CODEC_FLAG_GRAY) return;
  1783. if(field_based){
  1784. mx= motion_x/2;
  1785. my= motion_y>>1;
  1786. }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA2){
  1787. static const int rtab[8]= {0,0,1,1,0,0,0,1};
  1788. mx= (motion_x>>1) + rtab[motion_x&7];
  1789. my= (motion_y>>1) + rtab[motion_y&7];
  1790. }else if(s->workaround_bugs&FF_BUG_QPEL_CHROMA){
  1791. mx= (motion_x>>1)|(motion_x&1);
  1792. my= (motion_y>>1)|(motion_y&1);
  1793. }else{
  1794. mx= motion_x/2;
  1795. my= motion_y/2;
  1796. }
  1797. mx= (mx>>1)|(mx&1);
  1798. my= (my>>1)|(my&1);
  1799. dxy= (mx&1) | ((my&1)<<1);
  1800. mx>>=1;
  1801. my>>=1;
  1802. src_x = s->mb_x * 8 + mx;
  1803. src_y = s->mb_y * (8 >> field_based) + my;
  1804. src_x = clip(src_x, -8, s->width >> 1);
  1805. if (src_x == (s->width >> 1))
  1806. dxy &= ~1;
  1807. src_y = clip(src_y, -8, height >> 1);
  1808. if (src_y == (height >> 1))
  1809. dxy &= ~2;
  1810. offset = (src_y * uvlinesize) + src_x + (src_offset >> 1);
  1811. ptr = ref_picture[1] + offset;
  1812. if(emu){
  1813. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based,
  1814. src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1815. ptr= s->edge_emu_buffer + (src_offset >> 1);
  1816. }
  1817. pix_op[1][dxy](dest_cb + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
  1818. ptr = ref_picture[2] + offset;
  1819. if(emu){
  1820. ff_emulated_edge_mc(s->edge_emu_buffer, ptr - (src_offset >> 1), s->uvlinesize, 9, 9 + field_based,
  1821. src_x, src_y<<field_based, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1822. ptr= s->edge_emu_buffer + (src_offset >> 1);
  1823. }
  1824. pix_op[1][dxy](dest_cr + (dest_offset >> 1), ptr, uvlinesize, h >> 1);
  1825. }
  1826. inline int ff_h263_round_chroma(int x){
  1827. if (x >= 0)
  1828. return (h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
  1829. else {
  1830. x = -x;
  1831. return -(h263_chroma_roundtab[x & 0xf] + ((x >> 3) & ~1));
  1832. }
  1833. }
  1834. /**
  1835. * motion compesation of a single macroblock
  1836. * @param s context
  1837. * @param dest_y luma destination pointer
  1838. * @param dest_cb chroma cb/u destination pointer
  1839. * @param dest_cr chroma cr/v destination pointer
  1840. * @param dir direction (0->forward, 1->backward)
  1841. * @param ref_picture array[3] of pointers to the 3 planes of the reference picture
  1842. * @param pic_op halfpel motion compensation function (average or put normally)
  1843. * @param pic_op qpel motion compensation function (average or put normally)
  1844. * the motion vectors are taken from s->mv and the MV type from s->mv_type
  1845. */
  1846. static inline void MPV_motion(MpegEncContext *s,
  1847. uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,
  1848. int dir, uint8_t **ref_picture,
  1849. op_pixels_func (*pix_op)[4], qpel_mc_func (*qpix_op)[16])
  1850. {
  1851. int dxy, offset, mx, my, src_x, src_y, motion_x, motion_y;
  1852. int mb_x, mb_y, i;
  1853. uint8_t *ptr, *dest;
  1854. int emu=0;
  1855. mb_x = s->mb_x;
  1856. mb_y = s->mb_y;
  1857. switch(s->mv_type) {
  1858. case MV_TYPE_16X16:
  1859. #ifdef CONFIG_RISKY
  1860. if(s->mcsel){
  1861. if(s->real_sprite_warping_points==1){
  1862. gmc1_motion(s, dest_y, dest_cb, dest_cr, 0,
  1863. ref_picture, 0);
  1864. }else{
  1865. gmc_motion(s, dest_y, dest_cb, dest_cr, 0,
  1866. ref_picture, 0);
  1867. }
  1868. }else if(s->quarter_sample){
  1869. qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
  1870. ref_picture, 0,
  1871. 0, pix_op, qpix_op,
  1872. s->mv[dir][0][0], s->mv[dir][0][1], 16);
  1873. }else if(s->mspel){
  1874. ff_mspel_motion(s, dest_y, dest_cb, dest_cr,
  1875. ref_picture, pix_op,
  1876. s->mv[dir][0][0], s->mv[dir][0][1], 16);
  1877. }else
  1878. #endif
  1879. {
  1880. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  1881. ref_picture, 0,
  1882. 0, pix_op,
  1883. s->mv[dir][0][0], s->mv[dir][0][1], 16);
  1884. }
  1885. break;
  1886. case MV_TYPE_8X8:
  1887. mx = 0;
  1888. my = 0;
  1889. if(s->quarter_sample){
  1890. for(i=0;i<4;i++) {
  1891. motion_x = s->mv[dir][i][0];
  1892. motion_y = s->mv[dir][i][1];
  1893. dxy = ((motion_y & 3) << 2) | (motion_x & 3);
  1894. src_x = mb_x * 16 + (motion_x >> 2) + (i & 1) * 8;
  1895. src_y = mb_y * 16 + (motion_y >> 2) + (i >>1) * 8;
  1896. /* WARNING: do no forget half pels */
  1897. src_x = clip(src_x, -16, s->width);
  1898. if (src_x == s->width)
  1899. dxy &= ~3;
  1900. src_y = clip(src_y, -16, s->height);
  1901. if (src_y == s->height)
  1902. dxy &= ~12;
  1903. ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
  1904. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1905. if( (unsigned)src_x > s->h_edge_pos - (motion_x&3) - 8
  1906. || (unsigned)src_y > s->v_edge_pos - (motion_y&3) - 8 ){
  1907. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
  1908. ptr= s->edge_emu_buffer;
  1909. }
  1910. }
  1911. dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
  1912. qpix_op[1][dxy](dest, ptr, s->linesize);
  1913. mx += s->mv[dir][i][0]/2;
  1914. my += s->mv[dir][i][1]/2;
  1915. }
  1916. }else{
  1917. for(i=0;i<4;i++) {
  1918. motion_x = s->mv[dir][i][0];
  1919. motion_y = s->mv[dir][i][1];
  1920. dxy = ((motion_y & 1) << 1) | (motion_x & 1);
  1921. src_x = mb_x * 16 + (motion_x >> 1) + (i & 1) * 8;
  1922. src_y = mb_y * 16 + (motion_y >> 1) + (i >>1) * 8;
  1923. /* WARNING: do no forget half pels */
  1924. src_x = clip(src_x, -16, s->width);
  1925. if (src_x == s->width)
  1926. dxy &= ~1;
  1927. src_y = clip(src_y, -16, s->height);
  1928. if (src_y == s->height)
  1929. dxy &= ~2;
  1930. ptr = ref_picture[0] + (src_y * s->linesize) + (src_x);
  1931. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1932. if( (unsigned)src_x > s->h_edge_pos - (motion_x&1) - 8
  1933. || (unsigned)src_y > s->v_edge_pos - (motion_y&1) - 8){
  1934. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos);
  1935. ptr= s->edge_emu_buffer;
  1936. }
  1937. }
  1938. dest = dest_y + ((i & 1) * 8) + (i >> 1) * 8 * s->linesize;
  1939. pix_op[1][dxy](dest, ptr, s->linesize, 8);
  1940. mx += s->mv[dir][i][0];
  1941. my += s->mv[dir][i][1];
  1942. }
  1943. }
  1944. if(s->flags&CODEC_FLAG_GRAY) break;
  1945. /* In case of 8X8, we construct a single chroma motion vector
  1946. with a special rounding */
  1947. mx= ff_h263_round_chroma(mx);
  1948. my= ff_h263_round_chroma(my);
  1949. dxy = ((my & 1) << 1) | (mx & 1);
  1950. mx >>= 1;
  1951. my >>= 1;
  1952. src_x = mb_x * 8 + mx;
  1953. src_y = mb_y * 8 + my;
  1954. src_x = clip(src_x, -8, s->width/2);
  1955. if (src_x == s->width/2)
  1956. dxy &= ~1;
  1957. src_y = clip(src_y, -8, s->height/2);
  1958. if (src_y == s->height/2)
  1959. dxy &= ~2;
  1960. offset = (src_y * (s->uvlinesize)) + src_x;
  1961. ptr = ref_picture[1] + offset;
  1962. if(s->flags&CODEC_FLAG_EMU_EDGE){
  1963. if( (unsigned)src_x > (s->h_edge_pos>>1) - (dxy &1) - 8
  1964. || (unsigned)src_y > (s->v_edge_pos>>1) - (dxy>>1) - 8){
  1965. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1966. ptr= s->edge_emu_buffer;
  1967. emu=1;
  1968. }
  1969. }
  1970. pix_op[1][dxy](dest_cb, ptr, s->uvlinesize, 8);
  1971. ptr = ref_picture[2] + offset;
  1972. if(emu){
  1973. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9, src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);
  1974. ptr= s->edge_emu_buffer;
  1975. }
  1976. pix_op[1][dxy](dest_cr, ptr, s->uvlinesize, 8);
  1977. break;
  1978. case MV_TYPE_FIELD:
  1979. if (s->picture_structure == PICT_FRAME) {
  1980. if(s->quarter_sample){
  1981. /* top field */
  1982. qpel_motion(s, dest_y, dest_cb, dest_cr, 0,
  1983. ref_picture, s->field_select[dir][0] ? s->linesize : 0,
  1984. 1, pix_op, qpix_op,
  1985. s->mv[dir][0][0], s->mv[dir][0][1], 8);
  1986. /* bottom field */
  1987. qpel_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
  1988. ref_picture, s->field_select[dir][1] ? s->linesize : 0,
  1989. 1, pix_op, qpix_op,
  1990. s->mv[dir][1][0], s->mv[dir][1][1], 8);
  1991. }else{
  1992. /* top field */
  1993. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  1994. ref_picture, s->field_select[dir][0] ? s->linesize : 0,
  1995. 1, pix_op,
  1996. s->mv[dir][0][0], s->mv[dir][0][1], 8);
  1997. /* bottom field */
  1998. mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
  1999. ref_picture, s->field_select[dir][1] ? s->linesize : 0,
  2000. 1, pix_op,
  2001. s->mv[dir][1][0], s->mv[dir][1][1], 8);
  2002. }
  2003. } else {
  2004. int offset;
  2005. if(s->picture_structure == s->field_select[dir][0] + 1 || s->pict_type == B_TYPE || s->first_field){
  2006. offset= s->field_select[dir][0] ? s->linesize : 0;
  2007. }else{
  2008. ref_picture= s->current_picture.data;
  2009. offset= s->field_select[dir][0] ? s->linesize : -s->linesize;
  2010. }
  2011. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  2012. ref_picture, offset,
  2013. 0, pix_op,
  2014. s->mv[dir][0][0], s->mv[dir][0][1], 16);
  2015. }
  2016. break;
  2017. case MV_TYPE_16X8:{
  2018. int offset;
  2019. uint8_t ** ref2picture;
  2020. if(s->picture_structure == s->field_select[dir][0] + 1 || s->pict_type == B_TYPE || s->first_field){
  2021. ref2picture= ref_picture;
  2022. offset= s->field_select[dir][0] ? s->linesize : 0;
  2023. }else{
  2024. ref2picture= s->current_picture.data;
  2025. offset= s->field_select[dir][0] ? s->linesize : -s->linesize;
  2026. }
  2027. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  2028. ref2picture, offset,
  2029. 0, pix_op,
  2030. s->mv[dir][0][0], s->mv[dir][0][1], 8);
  2031. if(s->picture_structure == s->field_select[dir][1] + 1 || s->pict_type == B_TYPE || s->first_field){
  2032. ref2picture= ref_picture;
  2033. offset= s->field_select[dir][1] ? s->linesize : 0;
  2034. }else{
  2035. ref2picture= s->current_picture.data;
  2036. offset= s->field_select[dir][1] ? s->linesize : -s->linesize;
  2037. }
  2038. // I know it is ugly but this is the only way to fool emu_edge without rewrite mpeg_motion
  2039. mpeg_motion(s, dest_y+16*s->linesize, dest_cb+8*s->uvlinesize, dest_cr+8*s->uvlinesize,
  2040. 0,
  2041. ref2picture, offset,
  2042. 0, pix_op,
  2043. s->mv[dir][1][0], s->mv[dir][1][1]+16, 8);
  2044. }
  2045. break;
  2046. case MV_TYPE_DMV:
  2047. {
  2048. op_pixels_func (*dmv_pix_op)[4];
  2049. int offset;
  2050. dmv_pix_op = s->dsp.put_pixels_tab;
  2051. if(s->picture_structure == PICT_FRAME){
  2052. //put top field from top field
  2053. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  2054. ref_picture, 0,
  2055. 1, dmv_pix_op,
  2056. s->mv[dir][0][0], s->mv[dir][0][1], 8);
  2057. //put bottom field from bottom field
  2058. mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
  2059. ref_picture, s->linesize,
  2060. 1, dmv_pix_op,
  2061. s->mv[dir][0][0], s->mv[dir][0][1], 8);
  2062. dmv_pix_op = s->dsp.avg_pixels_tab;
  2063. //avg top field from bottom field
  2064. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  2065. ref_picture, s->linesize,
  2066. 1, dmv_pix_op,
  2067. s->mv[dir][2][0], s->mv[dir][2][1], 8);
  2068. //avg bottom field from top field
  2069. mpeg_motion(s, dest_y, dest_cb, dest_cr, s->linesize,
  2070. ref_picture, 0,
  2071. 1, dmv_pix_op,
  2072. s->mv[dir][3][0], s->mv[dir][3][1], 8);
  2073. }else{
  2074. offset=(s->picture_structure == PICT_BOTTOM_FIELD)?
  2075. s->linesize : 0;
  2076. //put field from the same parity
  2077. //same parity is never in the same frame
  2078. mpeg_motion(s, dest_y, dest_cb, dest_cr, 0,
  2079. ref_picture,offset,
  2080. 0,dmv_pix_op,
  2081. s->mv[dir][0][0],s->mv[dir][0][1],16);
  2082. // after put we make avg of the same block
  2083. dmv_pix_op=s->dsp.avg_pixels_tab;
  2084. //opposite parity is always in the same frame if this is second field
  2085. if(!s->first_field){
  2086. ref_picture = s->current_picture.data;
  2087. //top field is one linesize from frame beginig
  2088. offset=(s->picture_structure == PICT_BOTTOM_FIELD)?
  2089. -s->linesize : s->linesize;
  2090. }else
  2091. offset=(s->picture_structure == PICT_BOTTOM_FIELD)?
  2092. 0 : s->linesize;
  2093. //avg field from the opposite parity
  2094. mpeg_motion(s, dest_y, dest_cb, dest_cr,0,
  2095. ref_picture, offset,
  2096. 0,dmv_pix_op,
  2097. s->mv[dir][2][0],s->mv[dir][2][1],16);
  2098. }
  2099. }
  2100. break;
  2101. }
  2102. }
  2103. /* put block[] to dest[] */
  2104. static inline void put_dct(MpegEncContext *s,
  2105. DCTELEM *block, int i, uint8_t *dest, int line_size)
  2106. {
  2107. s->dct_unquantize(s, block, i, s->qscale);
  2108. s->dsp.idct_put (dest, line_size, block);
  2109. }
  2110. /* add block[] to dest[] */
  2111. static inline void add_dct(MpegEncContext *s,
  2112. DCTELEM *block, int i, uint8_t *dest, int line_size)
  2113. {
  2114. if (s->block_last_index[i] >= 0) {
  2115. s->dsp.idct_add (dest, line_size, block);
  2116. }
  2117. }
  2118. static inline void add_dequant_dct(MpegEncContext *s,
  2119. DCTELEM *block, int i, uint8_t *dest, int line_size)
  2120. {
  2121. if (s->block_last_index[i] >= 0) {
  2122. s->dct_unquantize(s, block, i, s->qscale);
  2123. s->dsp.idct_add (dest, line_size, block);
  2124. }
  2125. }
  2126. /**
  2127. * cleans dc, ac, coded_block for the current non intra MB
  2128. */
  2129. void ff_clean_intra_table_entries(MpegEncContext *s)
  2130. {
  2131. int wrap = s->block_wrap[0];
  2132. int xy = s->block_index[0];
  2133. s->dc_val[0][xy ] =
  2134. s->dc_val[0][xy + 1 ] =
  2135. s->dc_val[0][xy + wrap] =
  2136. s->dc_val[0][xy + 1 + wrap] = 1024;
  2137. /* ac pred */
  2138. memset(s->ac_val[0][xy ], 0, 32 * sizeof(int16_t));
  2139. memset(s->ac_val[0][xy + wrap], 0, 32 * sizeof(int16_t));
  2140. if (s->msmpeg4_version>=3) {
  2141. s->coded_block[xy ] =
  2142. s->coded_block[xy + 1 ] =
  2143. s->coded_block[xy + wrap] =
  2144. s->coded_block[xy + 1 + wrap] = 0;
  2145. }
  2146. /* chroma */
  2147. wrap = s->block_wrap[4];
  2148. xy = s->mb_x + 1 + (s->mb_y + 1) * wrap;
  2149. s->dc_val[1][xy] =
  2150. s->dc_val[2][xy] = 1024;
  2151. /* ac pred */
  2152. memset(s->ac_val[1][xy], 0, 16 * sizeof(int16_t));
  2153. memset(s->ac_val[2][xy], 0, 16 * sizeof(int16_t));
  2154. s->mbintra_table[s->mb_x + s->mb_y*s->mb_stride]= 0;
  2155. }
  2156. /* generic function called after a macroblock has been parsed by the
  2157. decoder or after it has been encoded by the encoder.
  2158. Important variables used:
  2159. s->mb_intra : true if intra macroblock
  2160. s->mv_dir : motion vector direction
  2161. s->mv_type : motion vector type
  2162. s->mv : motion vector
  2163. s->interlaced_dct : true if interlaced dct used (mpeg2)
  2164. */
  2165. void MPV_decode_mb(MpegEncContext *s, DCTELEM block[6][64])
  2166. {
  2167. int mb_x, mb_y;
  2168. const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;
  2169. #ifdef HAVE_XVMC
  2170. if(s->avctx->xvmc_acceleration){
  2171. XVMC_decode_mb(s);//xvmc uses pblocks
  2172. return;
  2173. }
  2174. #endif
  2175. mb_x = s->mb_x;
  2176. mb_y = s->mb_y;
  2177. s->current_picture.qscale_table[mb_xy]= s->qscale;
  2178. /* update DC predictors for P macroblocks */
  2179. if (!s->mb_intra) {
  2180. if (s->h263_pred || s->h263_aic) {
  2181. if(s->mbintra_table[mb_xy])
  2182. ff_clean_intra_table_entries(s);
  2183. } else {
  2184. s->last_dc[0] =
  2185. s->last_dc[1] =
  2186. s->last_dc[2] = 128 << s->intra_dc_precision;
  2187. }
  2188. }
  2189. else if (s->h263_pred || s->h263_aic)
  2190. s->mbintra_table[mb_xy]=1;
  2191. if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==B_TYPE))) { //FIXME precalc
  2192. uint8_t *dest_y, *dest_cb, *dest_cr;
  2193. int dct_linesize, dct_offset;
  2194. op_pixels_func (*op_pix)[4];
  2195. qpel_mc_func (*op_qpix)[16];
  2196. const int linesize= s->current_picture.linesize[0]; //not s->linesize as this woulnd be wrong for field pics
  2197. const int uvlinesize= s->current_picture.linesize[1];
  2198. /* avoid copy if macroblock skipped in last frame too */
  2199. /* skip only during decoding as we might trash the buffers during encoding a bit */
  2200. if(!s->encoding){
  2201. uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];
  2202. const int age= s->current_picture.age;
  2203. assert(age);
  2204. if (s->mb_skiped) {
  2205. s->mb_skiped= 0;
  2206. assert(s->pict_type!=I_TYPE);
  2207. (*mbskip_ptr) ++; /* indicate that this time we skiped it */
  2208. if(*mbskip_ptr >99) *mbskip_ptr= 99;
  2209. /* if previous was skipped too, then nothing to do ! */
  2210. if (*mbskip_ptr >= age && s->current_picture.reference){
  2211. return;
  2212. }
  2213. } else if(!s->current_picture.reference){
  2214. (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */
  2215. if(*mbskip_ptr >99) *mbskip_ptr= 99;
  2216. } else{
  2217. *mbskip_ptr = 0; /* not skipped */
  2218. }
  2219. }
  2220. if (s->interlaced_dct) {
  2221. dct_linesize = linesize * 2;
  2222. dct_offset = linesize;
  2223. } else {
  2224. dct_linesize = linesize;
  2225. dct_offset = linesize * 8;
  2226. }
  2227. dest_y= s->dest[0];
  2228. dest_cb= s->dest[1];
  2229. dest_cr= s->dest[2];
  2230. if (!s->mb_intra) {
  2231. /* motion handling */
  2232. /* decoding or more than one mb_type (MC was allready done otherwise) */
  2233. if(!s->encoding){
  2234. if ((!s->no_rounding) || s->pict_type==B_TYPE){
  2235. op_pix = s->dsp.put_pixels_tab;
  2236. op_qpix= s->dsp.put_qpel_pixels_tab;
  2237. }else{
  2238. op_pix = s->dsp.put_no_rnd_pixels_tab;
  2239. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  2240. }
  2241. if (s->mv_dir & MV_DIR_FORWARD) {
  2242. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  2243. op_pix = s->dsp.avg_pixels_tab;
  2244. op_qpix= s->dsp.avg_qpel_pixels_tab;
  2245. }
  2246. if (s->mv_dir & MV_DIR_BACKWARD) {
  2247. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  2248. }
  2249. }
  2250. /* skip dequant / idct if we are really late ;) */
  2251. if(s->hurry_up>1) return;
  2252. /* add dct residue */
  2253. if(s->encoding || !( s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO
  2254. || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){
  2255. add_dequant_dct(s, block[0], 0, dest_y, dct_linesize);
  2256. add_dequant_dct(s, block[1], 1, dest_y + 8, dct_linesize);
  2257. add_dequant_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
  2258. add_dequant_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
  2259. if(!(s->flags&CODEC_FLAG_GRAY)){
  2260. add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize);
  2261. add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize);
  2262. }
  2263. } else if(s->codec_id != CODEC_ID_WMV2){
  2264. add_dct(s, block[0], 0, dest_y, dct_linesize);
  2265. add_dct(s, block[1], 1, dest_y + 8, dct_linesize);
  2266. add_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
  2267. add_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
  2268. if(!(s->flags&CODEC_FLAG_GRAY)){
  2269. add_dct(s, block[4], 4, dest_cb, uvlinesize);
  2270. add_dct(s, block[5], 5, dest_cr, uvlinesize);
  2271. }
  2272. }
  2273. #ifdef CONFIG_RISKY
  2274. else{
  2275. ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);
  2276. }
  2277. #endif
  2278. } else {
  2279. /* dct only in intra block */
  2280. if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){
  2281. put_dct(s, block[0], 0, dest_y, dct_linesize);
  2282. put_dct(s, block[1], 1, dest_y + 8, dct_linesize);
  2283. put_dct(s, block[2], 2, dest_y + dct_offset, dct_linesize);
  2284. put_dct(s, block[3], 3, dest_y + dct_offset + 8, dct_linesize);
  2285. if(!(s->flags&CODEC_FLAG_GRAY)){
  2286. put_dct(s, block[4], 4, dest_cb, uvlinesize);
  2287. put_dct(s, block[5], 5, dest_cr, uvlinesize);
  2288. }
  2289. }else{
  2290. s->dsp.idct_put(dest_y , dct_linesize, block[0]);
  2291. s->dsp.idct_put(dest_y + 8, dct_linesize, block[1]);
  2292. s->dsp.idct_put(dest_y + dct_offset , dct_linesize, block[2]);
  2293. s->dsp.idct_put(dest_y + dct_offset + 8, dct_linesize, block[3]);
  2294. if(!(s->flags&CODEC_FLAG_GRAY)){
  2295. s->dsp.idct_put(dest_cb, uvlinesize, block[4]);
  2296. s->dsp.idct_put(dest_cr, uvlinesize, block[5]);
  2297. }
  2298. }
  2299. }
  2300. }
  2301. }
  2302. #ifdef CONFIG_ENCODERS
  2303. static inline void dct_single_coeff_elimination(MpegEncContext *s, int n, int threshold)
  2304. {
  2305. static const char tab[64]=
  2306. {3,2,2,1,1,1,1,1,
  2307. 1,1,1,1,1,1,1,1,
  2308. 1,1,1,1,1,1,1,1,
  2309. 0,0,0,0,0,0,0,0,
  2310. 0,0,0,0,0,0,0,0,
  2311. 0,0,0,0,0,0,0,0,
  2312. 0,0,0,0,0,0,0,0,
  2313. 0,0,0,0,0,0,0,0};
  2314. int score=0;
  2315. int run=0;
  2316. int i;
  2317. DCTELEM *block= s->block[n];
  2318. const int last_index= s->block_last_index[n];
  2319. int skip_dc;
  2320. if(threshold<0){
  2321. skip_dc=0;
  2322. threshold= -threshold;
  2323. }else
  2324. skip_dc=1;
  2325. /* are all which we could set to zero are allready zero? */
  2326. if(last_index<=skip_dc - 1) return;
  2327. for(i=0; i<=last_index; i++){
  2328. const int j = s->intra_scantable.permutated[i];
  2329. const int level = ABS(block[j]);
  2330. if(level==1){
  2331. if(skip_dc && i==0) continue;
  2332. score+= tab[run];
  2333. run=0;
  2334. }else if(level>1){
  2335. return;
  2336. }else{
  2337. run++;
  2338. }
  2339. }
  2340. if(score >= threshold) return;
  2341. for(i=skip_dc; i<=last_index; i++){
  2342. const int j = s->intra_scantable.permutated[i];
  2343. block[j]=0;
  2344. }
  2345. if(block[0]) s->block_last_index[n]= 0;
  2346. else s->block_last_index[n]= -1;
  2347. }
  2348. static inline void clip_coeffs(MpegEncContext *s, DCTELEM *block, int last_index)
  2349. {
  2350. int i;
  2351. const int maxlevel= s->max_qcoeff;
  2352. const int minlevel= s->min_qcoeff;
  2353. if(s->mb_intra){
  2354. i=1; //skip clipping of intra dc
  2355. }else
  2356. i=0;
  2357. for(;i<=last_index; i++){
  2358. const int j= s->intra_scantable.permutated[i];
  2359. int level = block[j];
  2360. if (level>maxlevel) level=maxlevel;
  2361. else if(level<minlevel) level=minlevel;
  2362. block[j]= level;
  2363. }
  2364. }
  2365. #if 0
  2366. static int pix_vcmp16x8(uint8_t *s, int stride){ //FIXME move to dsputil & optimize
  2367. int score=0;
  2368. int x,y;
  2369. for(y=0; y<7; y++){
  2370. for(x=0; x<16; x+=4){
  2371. score+= ABS(s[x ] - s[x +stride]) + ABS(s[x+1] - s[x+1+stride])
  2372. +ABS(s[x+2] - s[x+2+stride]) + ABS(s[x+3] - s[x+3+stride]);
  2373. }
  2374. s+= stride;
  2375. }
  2376. return score;
  2377. }
  2378. static int pix_diff_vcmp16x8(uint8_t *s1, uint8_t*s2, int stride){ //FIXME move to dsputil & optimize
  2379. int score=0;
  2380. int x,y;
  2381. for(y=0; y<7; y++){
  2382. for(x=0; x<16; x++){
  2383. score+= ABS(s1[x ] - s2[x ] - s1[x +stride] + s2[x +stride]);
  2384. }
  2385. s1+= stride;
  2386. s2+= stride;
  2387. }
  2388. return score;
  2389. }
  2390. #else
  2391. #define SQ(a) ((a)*(a))
  2392. static int pix_vcmp16x8(uint8_t *s, int stride){ //FIXME move to dsputil & optimize
  2393. int score=0;
  2394. int x,y;
  2395. for(y=0; y<7; y++){
  2396. for(x=0; x<16; x+=4){
  2397. score+= SQ(s[x ] - s[x +stride]) + SQ(s[x+1] - s[x+1+stride])
  2398. +SQ(s[x+2] - s[x+2+stride]) + SQ(s[x+3] - s[x+3+stride]);
  2399. }
  2400. s+= stride;
  2401. }
  2402. return score;
  2403. }
  2404. static int pix_diff_vcmp16x8(uint8_t *s1, uint8_t*s2, int stride){ //FIXME move to dsputil & optimize
  2405. int score=0;
  2406. int x,y;
  2407. for(y=0; y<7; y++){
  2408. for(x=0; x<16; x++){
  2409. score+= SQ(s1[x ] - s2[x ] - s1[x +stride] + s2[x +stride]);
  2410. }
  2411. s1+= stride;
  2412. s2+= stride;
  2413. }
  2414. return score;
  2415. }
  2416. #endif
  2417. #endif //CONFIG_ENCODERS
  2418. /**
  2419. *
  2420. * @param h is the normal height, this will be reduced automatically if needed for the last row
  2421. */
  2422. void ff_draw_horiz_band(MpegEncContext *s, int y, int h){
  2423. if (s->avctx->draw_horiz_band) {
  2424. AVFrame *src;
  2425. int offset[4];
  2426. if(s->picture_structure != PICT_FRAME){
  2427. h <<= 1;
  2428. y <<= 1;
  2429. if(s->first_field && !(s->avctx->slice_flags&SLICE_FLAG_ALLOW_FIELD)) return;
  2430. }
  2431. h= FFMIN(h, s->height - y);
  2432. if(s->pict_type==B_TYPE || s->low_delay || (s->avctx->slice_flags&SLICE_FLAG_CODED_ORDER))
  2433. src= (AVFrame*)s->current_picture_ptr;
  2434. else if(s->last_picture_ptr)
  2435. src= (AVFrame*)s->last_picture_ptr;
  2436. else
  2437. return;
  2438. if(s->pict_type==B_TYPE && s->picture_structure == PICT_FRAME && s->out_format != FMT_H264){
  2439. offset[0]=
  2440. offset[1]=
  2441. offset[2]=
  2442. offset[3]= 0;
  2443. }else{
  2444. offset[0]= y * s->linesize;;
  2445. offset[1]=
  2446. offset[2]= (y>>1) * s->uvlinesize;;
  2447. offset[3]= 0;
  2448. }
  2449. emms_c();
  2450. s->avctx->draw_horiz_band(s->avctx, src, offset,
  2451. y, s->picture_structure, h);
  2452. }
  2453. }
  2454. void ff_init_block_index(MpegEncContext *s){ //FIXME maybe rename
  2455. const int linesize= s->current_picture.linesize[0]; //not s->linesize as this woulnd be wrong for field pics
  2456. const int uvlinesize= s->current_picture.linesize[1];
  2457. s->block_index[0]= s->block_wrap[0]*(s->mb_y*2 + 1) - 1 + s->mb_x*2;
  2458. s->block_index[1]= s->block_wrap[0]*(s->mb_y*2 + 1) + s->mb_x*2;
  2459. s->block_index[2]= s->block_wrap[0]*(s->mb_y*2 + 2) - 1 + s->mb_x*2;
  2460. s->block_index[3]= s->block_wrap[0]*(s->mb_y*2 + 2) + s->mb_x*2;
  2461. s->block_index[4]= s->block_wrap[4]*(s->mb_y + 1) + s->block_wrap[0]*(s->mb_height*2 + 2) + s->mb_x;
  2462. s->block_index[5]= s->block_wrap[4]*(s->mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2) + s->mb_x;
  2463. if(s->pict_type==B_TYPE && s->avctx->draw_horiz_band && s->picture_structure==PICT_FRAME){
  2464. s->dest[0] = s->current_picture.data[0] + s->mb_x * 16 - 16;
  2465. s->dest[1] = s->current_picture.data[1] + s->mb_x * 8 - 8;
  2466. s->dest[2] = s->current_picture.data[2] + s->mb_x * 8 - 8;
  2467. }else{
  2468. s->dest[0] = s->current_picture.data[0] + (s->mb_y * 16* linesize ) + s->mb_x * 16 - 16;
  2469. s->dest[1] = s->current_picture.data[1] + (s->mb_y * 8 * uvlinesize) + s->mb_x * 8 - 8;
  2470. s->dest[2] = s->current_picture.data[2] + (s->mb_y * 8 * uvlinesize) + s->mb_x * 8 - 8;
  2471. }
  2472. }
  2473. #ifdef CONFIG_ENCODERS
  2474. static void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  2475. {
  2476. const int mb_x= s->mb_x;
  2477. const int mb_y= s->mb_y;
  2478. int i;
  2479. int skip_dct[6];
  2480. int dct_offset = s->linesize*8; //default for progressive frames
  2481. for(i=0; i<6; i++) skip_dct[i]=0;
  2482. if(s->adaptive_quant){
  2483. const int last_qp= s->qscale;
  2484. const int mb_xy= mb_x + mb_y*s->mb_stride;
  2485. s->lambda= s->lambda_table[mb_xy];
  2486. update_qscale(s);
  2487. s->dquant= s->qscale - last_qp;
  2488. if(s->out_format==FMT_H263)
  2489. s->dquant= clip(s->dquant, -2, 2); //FIXME RD
  2490. if(s->codec_id==CODEC_ID_MPEG4){
  2491. if(!s->mb_intra){
  2492. if((s->mv_dir&MV_DIRECT) || s->mv_type==MV_TYPE_8X8)
  2493. s->dquant=0;
  2494. }
  2495. }
  2496. s->qscale= last_qp + s->dquant;
  2497. s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
  2498. s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
  2499. }
  2500. if (s->mb_intra) {
  2501. uint8_t *ptr;
  2502. int wrap_y;
  2503. int emu=0;
  2504. wrap_y = s->linesize;
  2505. ptr = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  2506. if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
  2507. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
  2508. ptr= s->edge_emu_buffer;
  2509. emu=1;
  2510. }
  2511. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  2512. int progressive_score, interlaced_score;
  2513. progressive_score= pix_vcmp16x8(ptr, wrap_y ) + pix_vcmp16x8(ptr + wrap_y*8, wrap_y );
  2514. interlaced_score = pix_vcmp16x8(ptr, wrap_y*2) + pix_vcmp16x8(ptr + wrap_y , wrap_y*2);
  2515. if(progressive_score > interlaced_score + 100){
  2516. s->interlaced_dct=1;
  2517. dct_offset= wrap_y;
  2518. wrap_y<<=1;
  2519. }else
  2520. s->interlaced_dct=0;
  2521. }
  2522. s->dsp.get_pixels(s->block[0], ptr , wrap_y);
  2523. s->dsp.get_pixels(s->block[1], ptr + 8, wrap_y);
  2524. s->dsp.get_pixels(s->block[2], ptr + dct_offset , wrap_y);
  2525. s->dsp.get_pixels(s->block[3], ptr + dct_offset + 8, wrap_y);
  2526. if(s->flags&CODEC_FLAG_GRAY){
  2527. skip_dct[4]= 1;
  2528. skip_dct[5]= 1;
  2529. }else{
  2530. int wrap_c = s->uvlinesize;
  2531. ptr = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
  2532. if(emu){
  2533. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  2534. ptr= s->edge_emu_buffer;
  2535. }
  2536. s->dsp.get_pixels(s->block[4], ptr, wrap_c);
  2537. ptr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
  2538. if(emu){
  2539. ff_emulated_edge_mc(s->edge_emu_buffer, ptr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  2540. ptr= s->edge_emu_buffer;
  2541. }
  2542. s->dsp.get_pixels(s->block[5], ptr, wrap_c);
  2543. }
  2544. }else{
  2545. op_pixels_func (*op_pix)[4];
  2546. qpel_mc_func (*op_qpix)[16];
  2547. uint8_t *dest_y, *dest_cb, *dest_cr;
  2548. uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  2549. int wrap_y, wrap_c;
  2550. int emu=0;
  2551. dest_y = s->dest[0];
  2552. dest_cb = s->dest[1];
  2553. dest_cr = s->dest[2];
  2554. wrap_y = s->linesize;
  2555. wrap_c = s->uvlinesize;
  2556. ptr_y = s->new_picture.data[0] + (mb_y * 16 * wrap_y) + mb_x * 16;
  2557. ptr_cb = s->new_picture.data[1] + (mb_y * 8 * wrap_c) + mb_x * 8;
  2558. ptr_cr = s->new_picture.data[2] + (mb_y * 8 * wrap_c) + mb_x * 8;
  2559. if ((!s->no_rounding) || s->pict_type==B_TYPE){
  2560. op_pix = s->dsp.put_pixels_tab;
  2561. op_qpix= s->dsp.put_qpel_pixels_tab;
  2562. }else{
  2563. op_pix = s->dsp.put_no_rnd_pixels_tab;
  2564. op_qpix= s->dsp.put_no_rnd_qpel_pixels_tab;
  2565. }
  2566. if (s->mv_dir & MV_DIR_FORWARD) {
  2567. MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);
  2568. op_pix = s->dsp.avg_pixels_tab;
  2569. op_qpix= s->dsp.avg_qpel_pixels_tab;
  2570. }
  2571. if (s->mv_dir & MV_DIR_BACKWARD) {
  2572. MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);
  2573. }
  2574. if(mb_x*16+16 > s->width || mb_y*16+16 > s->height){
  2575. ff_emulated_edge_mc(s->edge_emu_buffer, ptr_y, wrap_y, 16, 16, mb_x*16, mb_y*16, s->width, s->height);
  2576. ptr_y= s->edge_emu_buffer;
  2577. emu=1;
  2578. }
  2579. if(s->flags&CODEC_FLAG_INTERLACED_DCT){
  2580. int progressive_score, interlaced_score;
  2581. progressive_score= pix_diff_vcmp16x8(ptr_y , dest_y , wrap_y )
  2582. + pix_diff_vcmp16x8(ptr_y + wrap_y*8, dest_y + wrap_y*8, wrap_y );
  2583. interlaced_score = pix_diff_vcmp16x8(ptr_y , dest_y , wrap_y*2)
  2584. + pix_diff_vcmp16x8(ptr_y + wrap_y , dest_y + wrap_y , wrap_y*2);
  2585. if(progressive_score > interlaced_score + 600){
  2586. s->interlaced_dct=1;
  2587. dct_offset= wrap_y;
  2588. wrap_y<<=1;
  2589. }else
  2590. s->interlaced_dct=0;
  2591. }
  2592. s->dsp.diff_pixels(s->block[0], ptr_y , dest_y , wrap_y);
  2593. s->dsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  2594. s->dsp.diff_pixels(s->block[2], ptr_y + dct_offset , dest_y + dct_offset , wrap_y);
  2595. s->dsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8, dest_y + dct_offset + 8, wrap_y);
  2596. if(s->flags&CODEC_FLAG_GRAY){
  2597. skip_dct[4]= 1;
  2598. skip_dct[5]= 1;
  2599. }else{
  2600. if(emu){
  2601. ff_emulated_edge_mc(s->edge_emu_buffer, ptr_cb, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  2602. ptr_cb= s->edge_emu_buffer;
  2603. }
  2604. s->dsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  2605. if(emu){
  2606. ff_emulated_edge_mc(s->edge_emu_buffer, ptr_cr, wrap_c, 8, 8, mb_x*8, mb_y*8, s->width>>1, s->height>>1);
  2607. ptr_cr= s->edge_emu_buffer;
  2608. }
  2609. s->dsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  2610. }
  2611. /* pre quantization */
  2612. if(s->current_picture.mc_mb_var[s->mb_stride*mb_y+ mb_x]<2*s->qscale*s->qscale){
  2613. //FIXME optimize
  2614. if(s->dsp.pix_abs8x8(ptr_y , dest_y , wrap_y) < 20*s->qscale) skip_dct[0]= 1;
  2615. if(s->dsp.pix_abs8x8(ptr_y + 8, dest_y + 8, wrap_y) < 20*s->qscale) skip_dct[1]= 1;
  2616. if(s->dsp.pix_abs8x8(ptr_y +dct_offset , dest_y +dct_offset , wrap_y) < 20*s->qscale) skip_dct[2]= 1;
  2617. if(s->dsp.pix_abs8x8(ptr_y +dct_offset+ 8, dest_y +dct_offset+ 8, wrap_y) < 20*s->qscale) skip_dct[3]= 1;
  2618. if(s->dsp.pix_abs8x8(ptr_cb , dest_cb , wrap_c) < 20*s->qscale) skip_dct[4]= 1;
  2619. if(s->dsp.pix_abs8x8(ptr_cr , dest_cr , wrap_c) < 20*s->qscale) skip_dct[5]= 1;
  2620. #if 0
  2621. {
  2622. static int stat[7];
  2623. int num=0;
  2624. for(i=0; i<6; i++)
  2625. if(skip_dct[i]) num++;
  2626. stat[num]++;
  2627. if(s->mb_x==0 && s->mb_y==0){
  2628. for(i=0; i<7; i++){
  2629. printf("%6d %1d\n", stat[i], i);
  2630. }
  2631. }
  2632. }
  2633. #endif
  2634. }
  2635. }
  2636. /* DCT & quantize */
  2637. if(s->out_format==FMT_MJPEG){
  2638. for(i=0;i<6;i++) {
  2639. int overflow;
  2640. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, 8, &overflow);
  2641. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  2642. }
  2643. }else{
  2644. for(i=0;i<6;i++) {
  2645. if(!skip_dct[i]){
  2646. int overflow;
  2647. s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  2648. // FIXME we could decide to change to quantizer instead of clipping
  2649. // JS: I don't think that would be a good idea it could lower quality instead
  2650. // of improve it. Just INTRADC clipping deserves changes in quantizer
  2651. if (overflow) clip_coeffs(s, s->block[i], s->block_last_index[i]);
  2652. }else
  2653. s->block_last_index[i]= -1;
  2654. }
  2655. if(s->luma_elim_threshold && !s->mb_intra)
  2656. for(i=0; i<4; i++)
  2657. dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  2658. if(s->chroma_elim_threshold && !s->mb_intra)
  2659. for(i=4; i<6; i++)
  2660. dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  2661. if(s->flags & CODEC_FLAG_CBP_RD){
  2662. for(i=0;i<6;i++) {
  2663. if(s->block_last_index[i] == -1)
  2664. s->coded_score[i]= INT_MAX/256;
  2665. }
  2666. }
  2667. }
  2668. if((s->flags&CODEC_FLAG_GRAY) && s->mb_intra){
  2669. s->block_last_index[4]=
  2670. s->block_last_index[5]= 0;
  2671. s->block[4][0]=
  2672. s->block[5][0]= (1024 + s->c_dc_scale/2)/ s->c_dc_scale;
  2673. }
  2674. /* huffman encode */
  2675. switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  2676. case CODEC_ID_MPEG1VIDEO:
  2677. case CODEC_ID_MPEG2VIDEO:
  2678. mpeg1_encode_mb(s, s->block, motion_x, motion_y); break;
  2679. #ifdef CONFIG_RISKY
  2680. case CODEC_ID_MPEG4:
  2681. mpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
  2682. case CODEC_ID_MSMPEG4V2:
  2683. case CODEC_ID_MSMPEG4V3:
  2684. case CODEC_ID_WMV1:
  2685. msmpeg4_encode_mb(s, s->block, motion_x, motion_y); break;
  2686. case CODEC_ID_WMV2:
  2687. ff_wmv2_encode_mb(s, s->block, motion_x, motion_y); break;
  2688. case CODEC_ID_H263:
  2689. case CODEC_ID_H263P:
  2690. case CODEC_ID_FLV1:
  2691. case CODEC_ID_RV10:
  2692. h263_encode_mb(s, s->block, motion_x, motion_y); break;
  2693. #endif
  2694. case CODEC_ID_MJPEG:
  2695. mjpeg_encode_mb(s, s->block); break;
  2696. default:
  2697. assert(0);
  2698. }
  2699. }
  2700. #endif //CONFIG_ENCODERS
  2701. /**
  2702. * combines the (truncated) bitstream to a complete frame
  2703. * @returns -1 if no complete frame could be created
  2704. */
  2705. int ff_combine_frame( MpegEncContext *s, int next, uint8_t **buf, int *buf_size){
  2706. ParseContext *pc= &s->parse_context;
  2707. #if 0
  2708. if(pc->overread){
  2709. printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
  2710. printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
  2711. }
  2712. #endif
  2713. /* copy overreaded byes from last frame into buffer */
  2714. for(; pc->overread>0; pc->overread--){
  2715. pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
  2716. }
  2717. pc->last_index= pc->index;
  2718. /* copy into buffer end return */
  2719. if(next == END_NOT_FOUND){
  2720. pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
  2721. memcpy(&pc->buffer[pc->index], *buf, *buf_size);
  2722. pc->index += *buf_size;
  2723. return -1;
  2724. }
  2725. *buf_size=
  2726. pc->overread_index= pc->index + next;
  2727. /* append to buffer */
  2728. if(pc->index){
  2729. pc->buffer= av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
  2730. memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE );
  2731. pc->index = 0;
  2732. *buf= pc->buffer;
  2733. }
  2734. /* store overread bytes */
  2735. for(;next < 0; next++){
  2736. pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
  2737. pc->overread++;
  2738. }
  2739. #if 0
  2740. if(pc->overread){
  2741. printf("overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index);
  2742. printf("%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
  2743. }
  2744. #endif
  2745. return 0;
  2746. }
  2747. void ff_mpeg_flush(AVCodecContext *avctx){
  2748. int i;
  2749. MpegEncContext *s = avctx->priv_data;
  2750. for(i=0; i<MAX_PICTURE_COUNT; i++){
  2751. if(s->picture[i].data[0] && ( s->picture[i].type == FF_BUFFER_TYPE_INTERNAL
  2752. || s->picture[i].type == FF_BUFFER_TYPE_USER))
  2753. avctx->release_buffer(avctx, (AVFrame*)&s->picture[i]);
  2754. }
  2755. s->last_picture_ptr = s->next_picture_ptr = NULL;
  2756. s->parse_context.state= -1;
  2757. s->parse_context.frame_start_found= 0;
  2758. s->parse_context.overread= 0;
  2759. s->parse_context.overread_index= 0;
  2760. s->parse_context.index= 0;
  2761. s->parse_context.last_index= 0;
  2762. }
  2763. #ifdef CONFIG_ENCODERS
  2764. void ff_copy_bits(PutBitContext *pb, uint8_t *src, int length)
  2765. {
  2766. int bytes= length>>4;
  2767. int bits= length&15;
  2768. int i;
  2769. if(length==0) return;
  2770. for(i=0; i<bytes; i++) put_bits(pb, 16, be2me_16(((uint16_t*)src)[i]));
  2771. put_bits(pb, bits, be2me_16(((uint16_t*)src)[i])>>(16-bits));
  2772. }
  2773. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2774. int i;
  2775. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  2776. /* mpeg1 */
  2777. d->mb_skip_run= s->mb_skip_run;
  2778. for(i=0; i<3; i++)
  2779. d->last_dc[i]= s->last_dc[i];
  2780. /* statistics */
  2781. d->mv_bits= s->mv_bits;
  2782. d->i_tex_bits= s->i_tex_bits;
  2783. d->p_tex_bits= s->p_tex_bits;
  2784. d->i_count= s->i_count;
  2785. d->f_count= s->f_count;
  2786. d->b_count= s->b_count;
  2787. d->skip_count= s->skip_count;
  2788. d->misc_bits= s->misc_bits;
  2789. d->last_bits= 0;
  2790. d->mb_skiped= 0;
  2791. d->qscale= s->qscale;
  2792. }
  2793. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2794. int i;
  2795. memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  2796. memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster then a loop?
  2797. /* mpeg1 */
  2798. d->mb_skip_run= s->mb_skip_run;
  2799. for(i=0; i<3; i++)
  2800. d->last_dc[i]= s->last_dc[i];
  2801. /* statistics */
  2802. d->mv_bits= s->mv_bits;
  2803. d->i_tex_bits= s->i_tex_bits;
  2804. d->p_tex_bits= s->p_tex_bits;
  2805. d->i_count= s->i_count;
  2806. d->f_count= s->f_count;
  2807. d->b_count= s->b_count;
  2808. d->skip_count= s->skip_count;
  2809. d->misc_bits= s->misc_bits;
  2810. d->mb_intra= s->mb_intra;
  2811. d->mb_skiped= s->mb_skiped;
  2812. d->mv_type= s->mv_type;
  2813. d->mv_dir= s->mv_dir;
  2814. d->pb= s->pb;
  2815. if(s->data_partitioning){
  2816. d->pb2= s->pb2;
  2817. d->tex_pb= s->tex_pb;
  2818. }
  2819. d->block= s->block;
  2820. for(i=0; i<6; i++)
  2821. d->block_last_index[i]= s->block_last_index[i];
  2822. d->interlaced_dct= s->interlaced_dct;
  2823. d->qscale= s->qscale;
  2824. }
  2825. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  2826. PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  2827. int *dmin, int *next_block, int motion_x, int motion_y)
  2828. {
  2829. int score;
  2830. uint8_t *dest_backup[3];
  2831. copy_context_before_encode(s, backup, type);
  2832. s->block= s->blocks[*next_block];
  2833. s->pb= pb[*next_block];
  2834. if(s->data_partitioning){
  2835. s->pb2 = pb2 [*next_block];
  2836. s->tex_pb= tex_pb[*next_block];
  2837. }
  2838. if(*next_block){
  2839. memcpy(dest_backup, s->dest, sizeof(s->dest));
  2840. s->dest[0] = s->me.scratchpad;
  2841. s->dest[1] = s->me.scratchpad + 16;
  2842. s->dest[2] = s->me.scratchpad + 16 + 8;
  2843. assert(2*s->uvlinesize == s->linesize); //should be no prob for encoding
  2844. assert(s->linesize >= 64); //FIXME
  2845. }
  2846. encode_mb(s, motion_x, motion_y);
  2847. score= get_bit_count(&s->pb);
  2848. if(s->data_partitioning){
  2849. score+= get_bit_count(&s->pb2);
  2850. score+= get_bit_count(&s->tex_pb);
  2851. }
  2852. if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  2853. MPV_decode_mb(s, s->block);
  2854. score *= s->lambda2;
  2855. score += sse_mb(s) << FF_LAMBDA_SHIFT;
  2856. }
  2857. if(*next_block){
  2858. memcpy(s->dest, dest_backup, sizeof(s->dest));
  2859. }
  2860. if(score<*dmin){
  2861. *dmin= score;
  2862. *next_block^=1;
  2863. copy_context_after_encode(best, s, type);
  2864. }
  2865. }
  2866. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  2867. uint32_t *sq = squareTbl + 256;
  2868. int acc=0;
  2869. int x,y;
  2870. if(w==16 && h==16)
  2871. return s->dsp.sse[0](NULL, src1, src2, stride);
  2872. else if(w==8 && h==8)
  2873. return s->dsp.sse[1](NULL, src1, src2, stride);
  2874. for(y=0; y<h; y++){
  2875. for(x=0; x<w; x++){
  2876. acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  2877. }
  2878. }
  2879. assert(acc>=0);
  2880. return acc;
  2881. }
  2882. static int sse_mb(MpegEncContext *s){
  2883. int w= 16;
  2884. int h= 16;
  2885. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2886. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2887. if(w==16 && h==16)
  2888. return s->dsp.sse[0](NULL, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize)
  2889. +s->dsp.sse[1](NULL, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize)
  2890. +s->dsp.sse[1](NULL, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize);
  2891. else
  2892. return sse(s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
  2893. +sse(s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
  2894. +sse(s, s->new_picture.data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
  2895. }
  2896. static void encode_picture(MpegEncContext *s, int picture_number)
  2897. {
  2898. int mb_x, mb_y, pdif = 0;
  2899. int i;
  2900. int bits;
  2901. MpegEncContext best_s, backup_s;
  2902. uint8_t bit_buf[2][3000];
  2903. uint8_t bit_buf2[2][3000];
  2904. uint8_t bit_buf_tex[2][3000];
  2905. PutBitContext pb[2], pb2[2], tex_pb[2];
  2906. for(i=0; i<2; i++){
  2907. init_put_bits(&pb [i], bit_buf [i], 3000);
  2908. init_put_bits(&pb2 [i], bit_buf2 [i], 3000);
  2909. init_put_bits(&tex_pb[i], bit_buf_tex[i], 3000);
  2910. }
  2911. s->picture_number = picture_number;
  2912. /* Reset the average MB variance */
  2913. s->current_picture.mb_var_sum = 0;
  2914. s->current_picture.mc_mb_var_sum = 0;
  2915. #ifdef CONFIG_RISKY
  2916. /* we need to initialize some time vars before we can encode b-frames */
  2917. // RAL: Condition added for MPEG1VIDEO
  2918. if (s->codec_id == CODEC_ID_MPEG1VIDEO || s->codec_id == CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->h263_msmpeg4))
  2919. ff_set_mpeg4_time(s, s->picture_number);
  2920. #endif
  2921. s->scene_change_score=0;
  2922. s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME ratedistoration
  2923. if(s->pict_type==I_TYPE){
  2924. if(s->msmpeg4_version >= 3) s->no_rounding=1;
  2925. else s->no_rounding=0;
  2926. }else if(s->pict_type!=B_TYPE){
  2927. if(s->flipflop_rounding || s->codec_id == CODEC_ID_H263P || s->codec_id == CODEC_ID_MPEG4)
  2928. s->no_rounding ^= 1;
  2929. }
  2930. /* Estimate motion for every MB */
  2931. s->mb_intra=0; //for the rate distoration & bit compare functions
  2932. if(s->pict_type != I_TYPE){
  2933. if(s->pict_type != B_TYPE){
  2934. if((s->avctx->pre_me && s->last_non_b_pict_type==I_TYPE) || s->avctx->pre_me==2){
  2935. s->me.pre_pass=1;
  2936. s->me.dia_size= s->avctx->pre_dia_size;
  2937. for(mb_y=s->mb_height-1; mb_y >=0 ; mb_y--) {
  2938. for(mb_x=s->mb_width-1; mb_x >=0 ; mb_x--) {
  2939. s->mb_x = mb_x;
  2940. s->mb_y = mb_y;
  2941. ff_pre_estimate_p_frame_motion(s, mb_x, mb_y);
  2942. }
  2943. }
  2944. s->me.pre_pass=0;
  2945. }
  2946. }
  2947. s->me.dia_size= s->avctx->dia_size;
  2948. for(mb_y=0; mb_y < s->mb_height; mb_y++) {
  2949. s->block_index[0]= s->block_wrap[0]*(mb_y*2 + 1) - 1;
  2950. s->block_index[1]= s->block_wrap[0]*(mb_y*2 + 1);
  2951. s->block_index[2]= s->block_wrap[0]*(mb_y*2 + 2) - 1;
  2952. s->block_index[3]= s->block_wrap[0]*(mb_y*2 + 2);
  2953. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2954. s->mb_x = mb_x;
  2955. s->mb_y = mb_y;
  2956. s->block_index[0]+=2;
  2957. s->block_index[1]+=2;
  2958. s->block_index[2]+=2;
  2959. s->block_index[3]+=2;
  2960. /* compute motion vector & mb_type and store in context */
  2961. if(s->pict_type==B_TYPE)
  2962. ff_estimate_b_frame_motion(s, mb_x, mb_y);
  2963. else
  2964. ff_estimate_p_frame_motion(s, mb_x, mb_y);
  2965. }
  2966. }
  2967. }else /* if(s->pict_type == I_TYPE) */{
  2968. /* I-Frame */
  2969. //FIXME do we need to zero them?
  2970. memset(s->motion_val[0], 0, sizeof(int16_t)*(s->mb_width*2 + 2)*(s->mb_height*2 + 2)*2);
  2971. memset(s->p_mv_table , 0, sizeof(int16_t)*(s->mb_stride)*s->mb_height*2);
  2972. memset(s->mb_type , MB_TYPE_INTRA, sizeof(uint8_t)*s->mb_stride*s->mb_height);
  2973. if(!s->fixed_qscale){
  2974. /* finding spatial complexity for I-frame rate control */
  2975. for(mb_y=0; mb_y < s->mb_height; mb_y++) {
  2976. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2977. int xx = mb_x * 16;
  2978. int yy = mb_y * 16;
  2979. uint8_t *pix = s->new_picture.data[0] + (yy * s->linesize) + xx;
  2980. int varc;
  2981. int sum = s->dsp.pix_sum(pix, s->linesize);
  2982. varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)(sum*sum))>>8) + 500 + 128)>>8;
  2983. s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  2984. s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  2985. s->current_picture.mb_var_sum += varc;
  2986. }
  2987. }
  2988. }
  2989. }
  2990. emms_c();
  2991. if(s->scene_change_score > s->avctx->scenechange_threshold && s->pict_type == P_TYPE){
  2992. s->pict_type= I_TYPE;
  2993. memset(s->mb_type , MB_TYPE_INTRA, sizeof(uint8_t)*s->mb_stride*s->mb_height);
  2994. //printf("Scene change detected, encoding as I Frame %d %d\n", s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  2995. }
  2996. if(!s->umvplus){
  2997. if(s->pict_type==P_TYPE || s->pict_type==S_TYPE) {
  2998. s->f_code= ff_get_best_fcode(s, s->p_mv_table, MB_TYPE_INTER);
  2999. ff_fix_long_p_mvs(s);
  3000. }
  3001. if(s->pict_type==B_TYPE){
  3002. int a, b;
  3003. a = ff_get_best_fcode(s, s->b_forw_mv_table, MB_TYPE_FORWARD);
  3004. b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, MB_TYPE_BIDIR);
  3005. s->f_code = FFMAX(a, b);
  3006. a = ff_get_best_fcode(s, s->b_back_mv_table, MB_TYPE_BACKWARD);
  3007. b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, MB_TYPE_BIDIR);
  3008. s->b_code = FFMAX(a, b);
  3009. ff_fix_long_b_mvs(s, s->b_forw_mv_table, s->f_code, MB_TYPE_FORWARD);
  3010. ff_fix_long_b_mvs(s, s->b_back_mv_table, s->b_code, MB_TYPE_BACKWARD);
  3011. ff_fix_long_b_mvs(s, s->b_bidir_forw_mv_table, s->f_code, MB_TYPE_BIDIR);
  3012. ff_fix_long_b_mvs(s, s->b_bidir_back_mv_table, s->b_code, MB_TYPE_BIDIR);
  3013. }
  3014. }
  3015. if (!s->fixed_qscale)
  3016. s->current_picture.quality = ff_rate_estimate_qscale(s);
  3017. if(s->adaptive_quant){
  3018. #ifdef CONFIG_RISKY
  3019. switch(s->codec_id){
  3020. case CODEC_ID_MPEG4:
  3021. ff_clean_mpeg4_qscales(s);
  3022. break;
  3023. case CODEC_ID_H263:
  3024. case CODEC_ID_H263P:
  3025. case CODEC_ID_FLV1:
  3026. ff_clean_h263_qscales(s);
  3027. break;
  3028. }
  3029. #endif
  3030. s->lambda= s->lambda_table[0];
  3031. //FIXME broken
  3032. }else
  3033. s->lambda= s->current_picture.quality;
  3034. //printf("%d %d\n", s->avctx->global_quality, s->current_picture.quality);
  3035. update_qscale(s);
  3036. if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==I_TYPE && !(s->flags & CODEC_FLAG_QSCALE))
  3037. s->qscale= 3; //reduce cliping problems
  3038. if (s->out_format == FMT_MJPEG) {
  3039. /* for mjpeg, we do include qscale in the matrix */
  3040. s->intra_matrix[0] = ff_mpeg1_default_intra_matrix[0];
  3041. for(i=1;i<64;i++){
  3042. int j= s->dsp.idct_permutation[i];
  3043. s->intra_matrix[j] = CLAMP_TO_8BIT((ff_mpeg1_default_intra_matrix[i] * s->qscale) >> 3);
  3044. }
  3045. convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,
  3046. s->intra_matrix, s->intra_quant_bias, 8, 8);
  3047. }
  3048. //FIXME var duplication
  3049. s->current_picture.key_frame= s->pict_type == I_TYPE;
  3050. s->current_picture.pict_type= s->pict_type;
  3051. if(s->current_picture.key_frame)
  3052. s->picture_in_gop_number=0;
  3053. s->last_bits= get_bit_count(&s->pb);
  3054. switch(s->out_format) {
  3055. case FMT_MJPEG:
  3056. mjpeg_picture_header(s);
  3057. break;
  3058. #ifdef CONFIG_RISKY
  3059. case FMT_H263:
  3060. if (s->codec_id == CODEC_ID_WMV2)
  3061. ff_wmv2_encode_picture_header(s, picture_number);
  3062. else if (s->h263_msmpeg4)
  3063. msmpeg4_encode_picture_header(s, picture_number);
  3064. else if (s->h263_pred)
  3065. mpeg4_encode_picture_header(s, picture_number);
  3066. else if (s->h263_rv10)
  3067. rv10_encode_picture_header(s, picture_number);
  3068. else if (s->codec_id == CODEC_ID_FLV1)
  3069. ff_flv_encode_picture_header(s, picture_number);
  3070. else
  3071. h263_encode_picture_header(s, picture_number);
  3072. break;
  3073. #endif
  3074. case FMT_MPEG1:
  3075. mpeg1_encode_picture_header(s, picture_number);
  3076. break;
  3077. case FMT_H264:
  3078. break;
  3079. }
  3080. bits= get_bit_count(&s->pb);
  3081. s->header_bits= bits - s->last_bits;
  3082. s->last_bits= bits;
  3083. s->mv_bits=0;
  3084. s->misc_bits=0;
  3085. s->i_tex_bits=0;
  3086. s->p_tex_bits=0;
  3087. s->i_count=0;
  3088. s->f_count=0;
  3089. s->b_count=0;
  3090. s->skip_count=0;
  3091. for(i=0; i<3; i++){
  3092. /* init last dc values */
  3093. /* note: quant matrix value (8) is implied here */
  3094. s->last_dc[i] = 128;
  3095. s->current_picture_ptr->error[i] = 0;
  3096. }
  3097. s->mb_skip_run = 0;
  3098. s->last_mv[0][0][0] = 0;
  3099. s->last_mv[0][0][1] = 0;
  3100. s->last_mv[1][0][0] = 0;
  3101. s->last_mv[1][0][1] = 0;
  3102. s->last_mv_dir = 0;
  3103. #ifdef CONFIG_RISKY
  3104. switch(s->codec_id){
  3105. case CODEC_ID_H263:
  3106. case CODEC_ID_H263P:
  3107. case CODEC_ID_FLV1:
  3108. s->gob_index = ff_h263_get_gob_height(s);
  3109. break;
  3110. case CODEC_ID_MPEG4:
  3111. if(s->partitioned_frame)
  3112. ff_mpeg4_init_partitions(s);
  3113. break;
  3114. }
  3115. #endif
  3116. s->resync_mb_x=0;
  3117. s->resync_mb_y=0;
  3118. s->first_slice_line = 1;
  3119. s->ptr_lastgob = s->pb.buf;
  3120. for(mb_y=0; mb_y < s->mb_height; mb_y++) {
  3121. s->mb_x=0;
  3122. s->mb_y= mb_y;
  3123. s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];
  3124. s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];
  3125. ff_init_block_index(s);
  3126. for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  3127. const int xy= mb_y*s->mb_stride + mb_x;
  3128. int mb_type= s->mb_type[xy];
  3129. // int d;
  3130. int dmin= INT_MAX;
  3131. s->mb_x = mb_x;
  3132. ff_update_block_index(s);
  3133. /* write gob / video packet header */
  3134. #ifdef CONFIG_RISKY
  3135. if(s->rtp_mode && mb_y + mb_x>0){
  3136. int current_packet_size, is_gob_start;
  3137. current_packet_size= pbBufPtr(&s->pb) - s->ptr_lastgob;
  3138. is_gob_start=0;
  3139. if(s->codec_id==CODEC_ID_MPEG4){
  3140. if(current_packet_size >= s->rtp_payload_size){
  3141. if(s->partitioned_frame){
  3142. ff_mpeg4_merge_partitions(s);
  3143. ff_mpeg4_init_partitions(s);
  3144. }
  3145. ff_mpeg4_encode_video_packet_header(s);
  3146. if(s->flags&CODEC_FLAG_PASS1){
  3147. int bits= get_bit_count(&s->pb);
  3148. s->misc_bits+= bits - s->last_bits;
  3149. s->last_bits= bits;
  3150. }
  3151. ff_mpeg4_clean_buffers(s);
  3152. is_gob_start=1;
  3153. }
  3154. }else if(s->codec_id==CODEC_ID_MPEG1VIDEO){
  3155. if( current_packet_size >= s->rtp_payload_size
  3156. && s->mb_skip_run==0){
  3157. ff_mpeg1_encode_slice_header(s);
  3158. ff_mpeg1_clean_buffers(s);
  3159. is_gob_start=1;
  3160. }
  3161. }else if(s->codec_id==CODEC_ID_MPEG2VIDEO){
  3162. if( ( current_packet_size >= s->rtp_payload_size || mb_x==0)
  3163. && s->mb_skip_run==0){
  3164. ff_mpeg1_encode_slice_header(s);
  3165. ff_mpeg1_clean_buffers(s);
  3166. is_gob_start=1;
  3167. }
  3168. }else{
  3169. if(current_packet_size >= s->rtp_payload_size
  3170. && s->mb_x==0 && s->mb_y%s->gob_index==0){
  3171. h263_encode_gob_header(s, mb_y);
  3172. is_gob_start=1;
  3173. }
  3174. }
  3175. if(is_gob_start){
  3176. s->ptr_lastgob = pbBufPtr(&s->pb);
  3177. s->first_slice_line=1;
  3178. s->resync_mb_x=mb_x;
  3179. s->resync_mb_y=mb_y;
  3180. }
  3181. }
  3182. #endif
  3183. if( (s->resync_mb_x == s->mb_x)
  3184. && s->resync_mb_y+1 == s->mb_y){
  3185. s->first_slice_line=0;
  3186. }
  3187. s->mb_skiped=0;
  3188. if(mb_type & (mb_type-1)){ // more than 1 MB type possible
  3189. int next_block=0;
  3190. int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  3191. copy_context_before_encode(&backup_s, s, -1);
  3192. backup_s.pb= s->pb;
  3193. best_s.data_partitioning= s->data_partitioning;
  3194. best_s.partitioned_frame= s->partitioned_frame;
  3195. if(s->data_partitioning){
  3196. backup_s.pb2= s->pb2;
  3197. backup_s.tex_pb= s->tex_pb;
  3198. }
  3199. if(mb_type&MB_TYPE_INTER){
  3200. s->mv_dir = MV_DIR_FORWARD;
  3201. s->mv_type = MV_TYPE_16X16;
  3202. s->mb_intra= 0;
  3203. s->mv[0][0][0] = s->p_mv_table[xy][0];
  3204. s->mv[0][0][1] = s->p_mv_table[xy][1];
  3205. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER, pb, pb2, tex_pb,
  3206. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3207. }
  3208. if(mb_type&MB_TYPE_SKIPED){
  3209. s->mv_dir = MV_DIR_FORWARD;
  3210. s->mv_type = MV_TYPE_16X16;
  3211. s->mb_intra= 0;
  3212. s->mv[0][0][0] = 0;
  3213. s->mv[0][0][1] = 0;
  3214. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_SKIPED, pb, pb2, tex_pb,
  3215. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3216. }
  3217. if(mb_type&MB_TYPE_INTER4V){
  3218. s->mv_dir = MV_DIR_FORWARD;
  3219. s->mv_type = MV_TYPE_8X8;
  3220. s->mb_intra= 0;
  3221. for(i=0; i<4; i++){
  3222. s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
  3223. s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
  3224. }
  3225. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTER4V, pb, pb2, tex_pb,
  3226. &dmin, &next_block, 0, 0);
  3227. }
  3228. if(mb_type&MB_TYPE_FORWARD){
  3229. s->mv_dir = MV_DIR_FORWARD;
  3230. s->mv_type = MV_TYPE_16X16;
  3231. s->mb_intra= 0;
  3232. s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  3233. s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  3234. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_FORWARD, pb, pb2, tex_pb,
  3235. &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3236. }
  3237. if(mb_type&MB_TYPE_BACKWARD){
  3238. s->mv_dir = MV_DIR_BACKWARD;
  3239. s->mv_type = MV_TYPE_16X16;
  3240. s->mb_intra= 0;
  3241. s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  3242. s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  3243. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  3244. &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  3245. }
  3246. if(mb_type&MB_TYPE_BIDIR){
  3247. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3248. s->mv_type = MV_TYPE_16X16;
  3249. s->mb_intra= 0;
  3250. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  3251. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  3252. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  3253. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  3254. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_BIDIR, pb, pb2, tex_pb,
  3255. &dmin, &next_block, 0, 0);
  3256. }
  3257. if(mb_type&MB_TYPE_DIRECT){
  3258. int mx= s->b_direct_mv_table[xy][0];
  3259. int my= s->b_direct_mv_table[xy][1];
  3260. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  3261. s->mb_intra= 0;
  3262. #ifdef CONFIG_RISKY
  3263. ff_mpeg4_set_direct_mv(s, mx, my);
  3264. #endif
  3265. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_DIRECT, pb, pb2, tex_pb,
  3266. &dmin, &next_block, mx, my);
  3267. }
  3268. if(mb_type&MB_TYPE_INTRA){
  3269. s->mv_dir = 0;
  3270. s->mv_type = MV_TYPE_16X16;
  3271. s->mb_intra= 1;
  3272. s->mv[0][0][0] = 0;
  3273. s->mv[0][0][1] = 0;
  3274. encode_mb_hq(s, &backup_s, &best_s, MB_TYPE_INTRA, pb, pb2, tex_pb,
  3275. &dmin, &next_block, 0, 0);
  3276. if(s->h263_pred || s->h263_aic){
  3277. if(best_s.mb_intra)
  3278. s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  3279. else
  3280. ff_clean_intra_table_entries(s); //old mode?
  3281. }
  3282. }
  3283. copy_context_after_encode(s, &best_s, -1);
  3284. pb_bits_count= get_bit_count(&s->pb);
  3285. flush_put_bits(&s->pb);
  3286. ff_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  3287. s->pb= backup_s.pb;
  3288. if(s->data_partitioning){
  3289. pb2_bits_count= get_bit_count(&s->pb2);
  3290. flush_put_bits(&s->pb2);
  3291. ff_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  3292. s->pb2= backup_s.pb2;
  3293. tex_pb_bits_count= get_bit_count(&s->tex_pb);
  3294. flush_put_bits(&s->tex_pb);
  3295. ff_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  3296. s->tex_pb= backup_s.tex_pb;
  3297. }
  3298. s->last_bits= get_bit_count(&s->pb);
  3299. #ifdef CONFIG_RISKY
  3300. if (s->out_format == FMT_H263 && s->pict_type!=B_TYPE)
  3301. ff_h263_update_motion_val(s);
  3302. #endif
  3303. if(next_block==0){
  3304. s->dsp.put_pixels_tab[0][0](s->dest[0], s->me.scratchpad , s->linesize ,16);
  3305. s->dsp.put_pixels_tab[1][0](s->dest[1], s->me.scratchpad + 16, s->uvlinesize, 8);
  3306. s->dsp.put_pixels_tab[1][0](s->dest[2], s->me.scratchpad + 24, s->uvlinesize, 8);
  3307. }
  3308. if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  3309. MPV_decode_mb(s, s->block);
  3310. } else {
  3311. int motion_x, motion_y;
  3312. int intra_score;
  3313. int inter_score= s->current_picture.mb_cmp_score[mb_x + mb_y*s->mb_stride];
  3314. if(s->avctx->mb_decision==FF_MB_DECISION_SIMPLE && s->pict_type==P_TYPE){ //FIXME check if the mess is usefull at all
  3315. /* get luma score */
  3316. if((s->avctx->mb_cmp&0xFF)==FF_CMP_SSE){
  3317. intra_score= (s->current_picture.mb_var[mb_x + mb_y*s->mb_stride]<<8) - 500; //FIXME dont scale it down so we dont have to fix it
  3318. }else{
  3319. uint8_t *dest_y;
  3320. int mean= s->current_picture.mb_mean[mb_x + mb_y*s->mb_stride]; //FIXME
  3321. mean*= 0x01010101;
  3322. dest_y = s->new_picture.data[0] + (mb_y * 16 * s->linesize ) + mb_x * 16;
  3323. for(i=0; i<16; i++){
  3324. *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 0]) = mean;
  3325. *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 4]) = mean;
  3326. *(uint32_t*)(&s->me.scratchpad[i*s->linesize+ 8]) = mean;
  3327. *(uint32_t*)(&s->me.scratchpad[i*s->linesize+12]) = mean;
  3328. }
  3329. s->mb_intra=1;
  3330. intra_score= s->dsp.mb_cmp[0](s, s->me.scratchpad, dest_y, s->linesize);
  3331. /* printf("intra:%7d inter:%7d var:%7d mc_var.%7d\n", intra_score>>8, inter_score>>8,
  3332. s->current_picture.mb_var[mb_x + mb_y*s->mb_stride],
  3333. s->current_picture.mc_mb_var[mb_x + mb_y*s->mb_stride]);*/
  3334. }
  3335. /* get chroma score */
  3336. if(s->avctx->mb_cmp&FF_CMP_CHROMA){
  3337. int i;
  3338. s->mb_intra=1;
  3339. for(i=1; i<3; i++){
  3340. uint8_t *dest_c;
  3341. int mean;
  3342. if(s->out_format == FMT_H263){
  3343. mean= (s->dc_val[i][mb_x + (mb_y+1)*(s->mb_width+2)] + 4)>>3; //FIXME not exact but simple ;)
  3344. }else{
  3345. mean= (s->last_dc[i] + 4)>>3;
  3346. }
  3347. dest_c = s->new_picture.data[i] + (mb_y * 8 * (s->uvlinesize)) + mb_x * 8;
  3348. mean*= 0x01010101;
  3349. for(i=0; i<8; i++){
  3350. *(uint32_t*)(&s->me.scratchpad[i*s->uvlinesize+ 0]) = mean;
  3351. *(uint32_t*)(&s->me.scratchpad[i*s->uvlinesize+ 4]) = mean;
  3352. }
  3353. intra_score+= s->dsp.mb_cmp[1](s, s->me.scratchpad, dest_c, s->uvlinesize);
  3354. }
  3355. }
  3356. /* bias */
  3357. switch(s->avctx->mb_cmp&0xFF){
  3358. default:
  3359. case FF_CMP_SAD:
  3360. intra_score+= 32*s->qscale;
  3361. break;
  3362. case FF_CMP_SSE:
  3363. intra_score+= 24*s->qscale*s->qscale;
  3364. break;
  3365. case FF_CMP_SATD:
  3366. intra_score+= 96*s->qscale;
  3367. break;
  3368. case FF_CMP_DCT:
  3369. intra_score+= 48*s->qscale;
  3370. break;
  3371. case FF_CMP_BIT:
  3372. intra_score+= 16;
  3373. break;
  3374. case FF_CMP_PSNR:
  3375. case FF_CMP_RD:
  3376. intra_score+= (s->qscale*s->qscale*109*8 + 64)>>7;
  3377. break;
  3378. }
  3379. if(intra_score < inter_score)
  3380. mb_type= MB_TYPE_INTRA;
  3381. }
  3382. s->mv_type=MV_TYPE_16X16;
  3383. // only one MB-Type possible
  3384. switch(mb_type){
  3385. case MB_TYPE_INTRA:
  3386. s->mv_dir = 0;
  3387. s->mb_intra= 1;
  3388. motion_x= s->mv[0][0][0] = 0;
  3389. motion_y= s->mv[0][0][1] = 0;
  3390. break;
  3391. case MB_TYPE_INTER:
  3392. s->mv_dir = MV_DIR_FORWARD;
  3393. s->mb_intra= 0;
  3394. motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  3395. motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  3396. break;
  3397. case MB_TYPE_INTER4V:
  3398. s->mv_dir = MV_DIR_FORWARD;
  3399. s->mv_type = MV_TYPE_8X8;
  3400. s->mb_intra= 0;
  3401. for(i=0; i<4; i++){
  3402. s->mv[0][i][0] = s->motion_val[s->block_index[i]][0];
  3403. s->mv[0][i][1] = s->motion_val[s->block_index[i]][1];
  3404. }
  3405. motion_x= motion_y= 0;
  3406. break;
  3407. case MB_TYPE_DIRECT:
  3408. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  3409. s->mb_intra= 0;
  3410. motion_x=s->b_direct_mv_table[xy][0];
  3411. motion_y=s->b_direct_mv_table[xy][1];
  3412. #ifdef CONFIG_RISKY
  3413. ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  3414. #endif
  3415. break;
  3416. case MB_TYPE_BIDIR:
  3417. s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3418. s->mb_intra= 0;
  3419. motion_x=0;
  3420. motion_y=0;
  3421. s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  3422. s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  3423. s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  3424. s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  3425. break;
  3426. case MB_TYPE_BACKWARD:
  3427. s->mv_dir = MV_DIR_BACKWARD;
  3428. s->mb_intra= 0;
  3429. motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  3430. motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  3431. break;
  3432. case MB_TYPE_FORWARD:
  3433. s->mv_dir = MV_DIR_FORWARD;
  3434. s->mb_intra= 0;
  3435. motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  3436. motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  3437. // printf(" %d %d ", motion_x, motion_y);
  3438. break;
  3439. default:
  3440. motion_x=motion_y=0; //gcc warning fix
  3441. av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  3442. }
  3443. encode_mb(s, motion_x, motion_y);
  3444. // RAL: Update last macrobloc type
  3445. s->last_mv_dir = s->mv_dir;
  3446. #ifdef CONFIG_RISKY
  3447. if (s->out_format == FMT_H263 && s->pict_type!=B_TYPE)
  3448. ff_h263_update_motion_val(s);
  3449. #endif
  3450. MPV_decode_mb(s, s->block);
  3451. }
  3452. /* clean the MV table in IPS frames for direct mode in B frames */
  3453. if(s->mb_intra /* && I,P,S_TYPE */){
  3454. s->p_mv_table[xy][0]=0;
  3455. s->p_mv_table[xy][1]=0;
  3456. }
  3457. if(s->flags&CODEC_FLAG_PSNR){
  3458. int w= 16;
  3459. int h= 16;
  3460. if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  3461. if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  3462. s->current_picture_ptr->error[0] += sse(
  3463. s, s->new_picture.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  3464. s->dest[0], w, h, s->linesize);
  3465. s->current_picture_ptr->error[1] += sse(
  3466. s, s->new_picture.data[1] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,
  3467. s->dest[1], w>>1, h>>1, s->uvlinesize);
  3468. s->current_picture_ptr->error[2] += sse(
  3469. s, s->new_picture .data[2] + s->mb_x*8 + s->mb_y*s->uvlinesize*8,
  3470. s->dest[2], w>>1, h>>1, s->uvlinesize);
  3471. }
  3472. //printf("MB %d %d bits\n", s->mb_x+s->mb_y*s->mb_stride, get_bit_count(&s->pb));
  3473. }
  3474. }
  3475. emms_c();
  3476. #ifdef CONFIG_RISKY
  3477. if(s->codec_id==CODEC_ID_MPEG4 && s->partitioned_frame)
  3478. ff_mpeg4_merge_partitions(s);
  3479. if (s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == I_TYPE)
  3480. msmpeg4_encode_ext_header(s);
  3481. if(s->codec_id==CODEC_ID_MPEG4)
  3482. ff_mpeg4_stuffing(&s->pb);
  3483. #endif
  3484. //if (s->gob_number)
  3485. // fprintf(stderr,"\nNumber of GOB: %d", s->gob_number);
  3486. /* Send the last GOB if RTP */
  3487. if (s->rtp_mode) {
  3488. flush_put_bits(&s->pb);
  3489. pdif = pbBufPtr(&s->pb) - s->ptr_lastgob;
  3490. /* Call the RTP callback to send the last GOB */
  3491. if (s->rtp_callback)
  3492. s->rtp_callback(s->ptr_lastgob, pdif, s->gob_number);
  3493. s->ptr_lastgob = pbBufPtr(&s->pb);
  3494. //fprintf(stderr,"\nGOB: %2d size: %d (last)", s->gob_number, pdif);
  3495. }
  3496. }
  3497. void ff_denoise_dct(MpegEncContext *s, DCTELEM *block){
  3498. const int intra= s->mb_intra;
  3499. int i;
  3500. for(i=0; i<64; i++){
  3501. int level= block[i];
  3502. if(level){
  3503. if(level>0){
  3504. s->dct_error_sum[intra][i] += level;
  3505. level -= s->dct_offset[intra][i];
  3506. if(level<0) level=0;
  3507. }else{
  3508. s->dct_error_sum[intra][i] -= level;
  3509. level += s->dct_offset[intra][i];
  3510. if(level>0) level=0;
  3511. }
  3512. block[i]= level;
  3513. }
  3514. }
  3515. }
  3516. static int dct_quantize_trellis_c(MpegEncContext *s,
  3517. DCTELEM *block, int n,
  3518. int qscale, int *overflow){
  3519. const int *qmat;
  3520. const uint8_t *scantable= s->intra_scantable.scantable;
  3521. int max=0;
  3522. unsigned int threshold1, threshold2;
  3523. int bias=0;
  3524. int run_tab[65];
  3525. int level_tab[65];
  3526. int score_tab[65];
  3527. int last_run=0;
  3528. int last_level=0;
  3529. int last_score= 0;
  3530. int last_i= 0;
  3531. int not_coded_score= 0;
  3532. int coeff[3][64];
  3533. int coeff_count[64];
  3534. int qmul, qadd, start_i, last_non_zero, i, dc;
  3535. const int esc_length= s->ac_esc_length;
  3536. uint8_t * length;
  3537. uint8_t * last_length;
  3538. int score_limit=0;
  3539. int left_limit= 0;
  3540. const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  3541. const int patch_table= s->out_format == FMT_MPEG1 && !s->mb_intra;
  3542. s->dsp.fdct (block);
  3543. if(s->dct_error_sum)
  3544. ff_denoise_dct(s, block);
  3545. qmul= qscale*16;
  3546. qadd= ((qscale-1)|1)*8;
  3547. if (s->mb_intra) {
  3548. int q;
  3549. if (!s->h263_aic) {
  3550. if (n < 4)
  3551. q = s->y_dc_scale;
  3552. else
  3553. q = s->c_dc_scale;
  3554. q = q << 3;
  3555. } else{
  3556. /* For AIC we skip quant/dequant of INTRADC */
  3557. q = 1 << 3;
  3558. qadd=0;
  3559. }
  3560. /* note: block[0] is assumed to be positive */
  3561. block[0] = (block[0] + (q >> 1)) / q;
  3562. start_i = 1;
  3563. last_non_zero = 0;
  3564. qmat = s->q_intra_matrix[qscale];
  3565. if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  3566. bias= 1<<(QMAT_SHIFT-1);
  3567. length = s->intra_ac_vlc_length;
  3568. last_length= s->intra_ac_vlc_last_length;
  3569. } else {
  3570. start_i = 0;
  3571. last_non_zero = -1;
  3572. qmat = s->q_inter_matrix[qscale];
  3573. length = s->inter_ac_vlc_length;
  3574. last_length= s->inter_ac_vlc_last_length;
  3575. }
  3576. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3577. threshold2= (threshold1<<1);
  3578. for(i=start_i; i<64; i++) {
  3579. const int j = scantable[i];
  3580. const int k= i-start_i;
  3581. int level = block[j];
  3582. level = level * qmat[j];
  3583. // if( bias+level >= (1<<(QMAT_SHIFT - 3))
  3584. // || bias-level >= (1<<(QMAT_SHIFT - 3))){
  3585. if(((unsigned)(level+threshold1))>threshold2){
  3586. if(level>0){
  3587. level= (bias + level)>>QMAT_SHIFT;
  3588. coeff[0][k]= level;
  3589. coeff[1][k]= level-1;
  3590. // coeff[2][k]= level-2;
  3591. }else{
  3592. level= (bias - level)>>QMAT_SHIFT;
  3593. coeff[0][k]= -level;
  3594. coeff[1][k]= -level+1;
  3595. // coeff[2][k]= -level+2;
  3596. }
  3597. coeff_count[k]= FFMIN(level, 2);
  3598. assert(coeff_count[k]);
  3599. max |=level;
  3600. last_non_zero = i;
  3601. }else{
  3602. coeff[0][k]= (level>>31)|1;
  3603. coeff_count[k]= 1;
  3604. }
  3605. }
  3606. *overflow= s->max_qcoeff < max; //overflow might have happend
  3607. if(last_non_zero < start_i){
  3608. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  3609. return last_non_zero;
  3610. }
  3611. score_tab[0]= 0;
  3612. if(patch_table){
  3613. // length[UNI_AC_ENC_INDEX(0, 63)]=
  3614. // length[UNI_AC_ENC_INDEX(0, 65)]= 2;
  3615. }
  3616. for(i=0; i<=last_non_zero - start_i; i++){
  3617. int level_index, run, j;
  3618. const int dct_coeff= block[ scantable[i + start_i] ];
  3619. const int zero_distoration= dct_coeff*dct_coeff;
  3620. int best_score=256*256*256*120;
  3621. last_score += zero_distoration;
  3622. not_coded_score += zero_distoration;
  3623. for(level_index=0; level_index < coeff_count[i]; level_index++){
  3624. int distoration;
  3625. int level= coeff[level_index][i];
  3626. int unquant_coeff;
  3627. assert(level);
  3628. if(s->out_format == FMT_H263){
  3629. if(level>0){
  3630. unquant_coeff= level*qmul + qadd;
  3631. }else{
  3632. unquant_coeff= level*qmul - qadd;
  3633. }
  3634. }else{ //MPEG1
  3635. j= s->dsp.idct_permutation[ scantable[i + start_i] ]; //FIXME optimize
  3636. if(s->mb_intra){
  3637. if (level < 0) {
  3638. unquant_coeff = (int)((-level) * qscale * s->intra_matrix[j]) >> 3;
  3639. unquant_coeff = -((unquant_coeff - 1) | 1);
  3640. } else {
  3641. unquant_coeff = (int)( level * qscale * s->intra_matrix[j]) >> 3;
  3642. unquant_coeff = (unquant_coeff - 1) | 1;
  3643. }
  3644. }else{
  3645. if (level < 0) {
  3646. unquant_coeff = ((((-level) << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  3647. unquant_coeff = -((unquant_coeff - 1) | 1);
  3648. } else {
  3649. unquant_coeff = ((( level << 1) + 1) * qscale * ((int) s->inter_matrix[j])) >> 4;
  3650. unquant_coeff = (unquant_coeff - 1) | 1;
  3651. }
  3652. }
  3653. unquant_coeff<<= 3;
  3654. }
  3655. distoration= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff);
  3656. level+=64;
  3657. if((level&(~127)) == 0){
  3658. for(run=0; run<=i - left_limit; run++){
  3659. int score= distoration + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3660. score += score_tab[i-run];
  3661. if(score < best_score){
  3662. best_score=
  3663. score_tab[i+1]= score;
  3664. run_tab[i+1]= run;
  3665. level_tab[i+1]= level-64;
  3666. }
  3667. }
  3668. if(s->out_format == FMT_H263){
  3669. for(run=0; run<=i - left_limit; run++){
  3670. int score= distoration + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3671. score += score_tab[i-run];
  3672. if(score < last_score){
  3673. last_score= score;
  3674. last_run= run;
  3675. last_level= level-64;
  3676. last_i= i+1;
  3677. }
  3678. }
  3679. }
  3680. }else{
  3681. distoration += esc_length*lambda;
  3682. for(run=0; run<=i - left_limit; run++){
  3683. int score= distoration + score_tab[i-run];
  3684. if(score < best_score){
  3685. best_score=
  3686. score_tab[i+1]= score;
  3687. run_tab[i+1]= run;
  3688. level_tab[i+1]= level-64;
  3689. }
  3690. }
  3691. if(s->out_format == FMT_H263){
  3692. for(run=0; run<=i - left_limit; run++){
  3693. int score= distoration + score_tab[i-run];
  3694. if(score < last_score){
  3695. last_score= score;
  3696. last_run= run;
  3697. last_level= level-64;
  3698. last_i= i+1;
  3699. }
  3700. }
  3701. }
  3702. }
  3703. }
  3704. for(j=left_limit; j<=i; j++){
  3705. score_tab[j] += zero_distoration;
  3706. }
  3707. score_limit+= zero_distoration;
  3708. if(score_tab[i+1] < score_limit)
  3709. score_limit= score_tab[i+1];
  3710. //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  3711. while(score_tab[ left_limit ] > score_limit + lambda) left_limit++;
  3712. if(patch_table){
  3713. // length[UNI_AC_ENC_INDEX(0, 63)]=
  3714. // length[UNI_AC_ENC_INDEX(0, 65)]= 3;
  3715. }
  3716. }
  3717. if(s->out_format != FMT_H263){
  3718. last_score= 256*256*256*120;
  3719. for(i= left_limit; i<=last_non_zero - start_i + 1; i++){
  3720. int score= score_tab[i];
  3721. if(i) score += lambda*2; //FIXME exacter?
  3722. if(score < last_score){
  3723. last_score= score;
  3724. last_i= i;
  3725. last_level= level_tab[i];
  3726. last_run= run_tab[i];
  3727. }
  3728. }
  3729. }
  3730. s->coded_score[n] = last_score - not_coded_score;
  3731. dc= block[0];
  3732. last_non_zero= last_i - 1 + start_i;
  3733. memset(block + start_i, 0, (64-start_i)*sizeof(DCTELEM));
  3734. if(last_non_zero < start_i)
  3735. return last_non_zero;
  3736. if(last_non_zero == 0 && start_i == 0){
  3737. int best_level= 0;
  3738. int best_score= dc * dc;
  3739. for(i=0; i<coeff_count[0]; i++){
  3740. int level= coeff[i][0];
  3741. int unquant_coeff, score, distoration;
  3742. if(s->out_format == FMT_H263){
  3743. if(level>0){
  3744. unquant_coeff= (level*qmul + qadd)>>3;
  3745. }else{
  3746. unquant_coeff= (level*qmul - qadd)>>3;
  3747. }
  3748. }else{ //MPEG1
  3749. if (level < 0) {
  3750. unquant_coeff = ((((-level) << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  3751. unquant_coeff = -((unquant_coeff - 1) | 1);
  3752. } else {
  3753. unquant_coeff = ((( level << 1) + 1) * qscale * ((int) s->inter_matrix[0])) >> 4;
  3754. unquant_coeff = (unquant_coeff - 1) | 1;
  3755. }
  3756. }
  3757. unquant_coeff = (unquant_coeff + 4) >> 3;
  3758. unquant_coeff<<= 3 + 3;
  3759. distoration= (unquant_coeff - dc) * (unquant_coeff - dc);
  3760. level+=64;
  3761. if((level&(~127)) == 0)
  3762. score= distoration + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  3763. else
  3764. score= distoration + esc_length*lambda;
  3765. if(score < best_score){
  3766. best_score= score;
  3767. best_level= level - 64;
  3768. }
  3769. }
  3770. block[0]= best_level;
  3771. s->coded_score[n] = best_score - dc*dc;
  3772. if(best_level == 0) return -1;
  3773. else return last_non_zero;
  3774. }
  3775. i= last_i;
  3776. assert(last_level);
  3777. //FIXME use permutated scantable
  3778. block[ s->dsp.idct_permutation[ scantable[last_non_zero] ] ]= last_level;
  3779. i -= last_run + 1;
  3780. for(;i>0 ; i -= run_tab[i] + 1){
  3781. const int j= s->dsp.idct_permutation[ scantable[i - 1 + start_i] ];
  3782. block[j]= level_tab[i];
  3783. assert(block[j]);
  3784. }
  3785. return last_non_zero;
  3786. }
  3787. static int dct_quantize_c(MpegEncContext *s,
  3788. DCTELEM *block, int n,
  3789. int qscale, int *overflow)
  3790. {
  3791. int i, j, level, last_non_zero, q;
  3792. const int *qmat;
  3793. const uint8_t *scantable= s->intra_scantable.scantable;
  3794. int bias;
  3795. int max=0;
  3796. unsigned int threshold1, threshold2;
  3797. s->dsp.fdct (block);
  3798. if(s->dct_error_sum)
  3799. ff_denoise_dct(s, block);
  3800. if (s->mb_intra) {
  3801. if (!s->h263_aic) {
  3802. if (n < 4)
  3803. q = s->y_dc_scale;
  3804. else
  3805. q = s->c_dc_scale;
  3806. q = q << 3;
  3807. } else
  3808. /* For AIC we skip quant/dequant of INTRADC */
  3809. q = 1 << 3;
  3810. /* note: block[0] is assumed to be positive */
  3811. block[0] = (block[0] + (q >> 1)) / q;
  3812. i = 1;
  3813. last_non_zero = 0;
  3814. qmat = s->q_intra_matrix[qscale];
  3815. bias= s->intra_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3816. } else {
  3817. i = 0;
  3818. last_non_zero = -1;
  3819. qmat = s->q_inter_matrix[qscale];
  3820. bias= s->inter_quant_bias<<(QMAT_SHIFT - QUANT_BIAS_SHIFT);
  3821. }
  3822. threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3823. threshold2= (threshold1<<1);
  3824. for(;i<64;i++) {
  3825. j = scantable[i];
  3826. level = block[j];
  3827. level = level * qmat[j];
  3828. // if( bias+level >= (1<<QMAT_SHIFT)
  3829. // || bias-level >= (1<<QMAT_SHIFT)){
  3830. if(((unsigned)(level+threshold1))>threshold2){
  3831. if(level>0){
  3832. level= (bias + level)>>QMAT_SHIFT;
  3833. block[j]= level;
  3834. }else{
  3835. level= (bias - level)>>QMAT_SHIFT;
  3836. block[j]= -level;
  3837. }
  3838. max |=level;
  3839. last_non_zero = i;
  3840. }else{
  3841. block[j]=0;
  3842. }
  3843. }
  3844. *overflow= s->max_qcoeff < max; //overflow might have happend
  3845. /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  3846. if (s->dsp.idct_permutation_type != FF_NO_IDCT_PERM)
  3847. ff_block_permute(block, s->dsp.idct_permutation, scantable, last_non_zero);
  3848. return last_non_zero;
  3849. }
  3850. #endif //CONFIG_ENCODERS
  3851. static void dct_unquantize_mpeg1_c(MpegEncContext *s,
  3852. DCTELEM *block, int n, int qscale)
  3853. {
  3854. int i, level, nCoeffs;
  3855. const uint16_t *quant_matrix;
  3856. nCoeffs= s->block_last_index[n];
  3857. if (s->mb_intra) {
  3858. if (n < 4)
  3859. block[0] = block[0] * s->y_dc_scale;
  3860. else
  3861. block[0] = block[0] * s->c_dc_scale;
  3862. /* XXX: only mpeg1 */
  3863. quant_matrix = s->intra_matrix;
  3864. for(i=1;i<=nCoeffs;i++) {
  3865. int j= s->intra_scantable.permutated[i];
  3866. level = block[j];
  3867. if (level) {
  3868. if (level < 0) {
  3869. level = -level;
  3870. level = (int)(level * qscale * quant_matrix[j]) >> 3;
  3871. level = (level - 1) | 1;
  3872. level = -level;
  3873. } else {
  3874. level = (int)(level * qscale * quant_matrix[j]) >> 3;
  3875. level = (level - 1) | 1;
  3876. }
  3877. #ifdef PARANOID
  3878. if (level < -2048 || level > 2047)
  3879. fprintf(stderr, "unquant error %d %d\n", i, level);
  3880. #endif
  3881. block[j] = level;
  3882. }
  3883. }
  3884. } else {
  3885. i = 0;
  3886. quant_matrix = s->inter_matrix;
  3887. for(;i<=nCoeffs;i++) {
  3888. int j= s->intra_scantable.permutated[i];
  3889. level = block[j];
  3890. if (level) {
  3891. if (level < 0) {
  3892. level = -level;
  3893. level = (((level << 1) + 1) * qscale *
  3894. ((int) (quant_matrix[j]))) >> 4;
  3895. level = (level - 1) | 1;
  3896. level = -level;
  3897. } else {
  3898. level = (((level << 1) + 1) * qscale *
  3899. ((int) (quant_matrix[j]))) >> 4;
  3900. level = (level - 1) | 1;
  3901. }
  3902. #ifdef PARANOID
  3903. if (level < -2048 || level > 2047)
  3904. fprintf(stderr, "unquant error %d %d\n", i, level);
  3905. #endif
  3906. block[j] = level;
  3907. }
  3908. }
  3909. }
  3910. }
  3911. static void dct_unquantize_mpeg2_c(MpegEncContext *s,
  3912. DCTELEM *block, int n, int qscale)
  3913. {
  3914. int i, level, nCoeffs;
  3915. const uint16_t *quant_matrix;
  3916. if(s->alternate_scan) nCoeffs= 63;
  3917. else nCoeffs= s->block_last_index[n];
  3918. if (s->mb_intra) {
  3919. if (n < 4)
  3920. block[0] = block[0] * s->y_dc_scale;
  3921. else
  3922. block[0] = block[0] * s->c_dc_scale;
  3923. quant_matrix = s->intra_matrix;
  3924. for(i=1;i<=nCoeffs;i++) {
  3925. int j= s->intra_scantable.permutated[i];
  3926. level = block[j];
  3927. if (level) {
  3928. if (level < 0) {
  3929. level = -level;
  3930. level = (int)(level * qscale * quant_matrix[j]) >> 3;
  3931. level = -level;
  3932. } else {
  3933. level = (int)(level * qscale * quant_matrix[j]) >> 3;
  3934. }
  3935. #ifdef PARANOID
  3936. if (level < -2048 || level > 2047)
  3937. fprintf(stderr, "unquant error %d %d\n", i, level);
  3938. #endif
  3939. block[j] = level;
  3940. }
  3941. }
  3942. } else {
  3943. int sum=-1;
  3944. i = 0;
  3945. quant_matrix = s->inter_matrix;
  3946. for(;i<=nCoeffs;i++) {
  3947. int j= s->intra_scantable.permutated[i];
  3948. level = block[j];
  3949. if (level) {
  3950. if (level < 0) {
  3951. level = -level;
  3952. level = (((level << 1) + 1) * qscale *
  3953. ((int) (quant_matrix[j]))) >> 4;
  3954. level = -level;
  3955. } else {
  3956. level = (((level << 1) + 1) * qscale *
  3957. ((int) (quant_matrix[j]))) >> 4;
  3958. }
  3959. #ifdef PARANOID
  3960. if (level < -2048 || level > 2047)
  3961. fprintf(stderr, "unquant error %d %d\n", i, level);
  3962. #endif
  3963. block[j] = level;
  3964. sum+=level;
  3965. }
  3966. }
  3967. block[63]^=sum&1;
  3968. }
  3969. }
  3970. static void dct_unquantize_h263_c(MpegEncContext *s,
  3971. DCTELEM *block, int n, int qscale)
  3972. {
  3973. int i, level, qmul, qadd;
  3974. int nCoeffs;
  3975. assert(s->block_last_index[n]>=0);
  3976. qadd = (qscale - 1) | 1;
  3977. qmul = qscale << 1;
  3978. if (s->mb_intra) {
  3979. if (!s->h263_aic) {
  3980. if (n < 4)
  3981. block[0] = block[0] * s->y_dc_scale;
  3982. else
  3983. block[0] = block[0] * s->c_dc_scale;
  3984. }else
  3985. qadd = 0;
  3986. i = 1;
  3987. nCoeffs= 63; //does not allways use zigzag table
  3988. } else {
  3989. i = 0;
  3990. nCoeffs= s->inter_scantable.raster_end[ s->block_last_index[n] ];
  3991. }
  3992. for(;i<=nCoeffs;i++) {
  3993. level = block[i];
  3994. if (level) {
  3995. if (level < 0) {
  3996. level = level * qmul - qadd;
  3997. } else {
  3998. level = level * qmul + qadd;
  3999. }
  4000. #ifdef PARANOID
  4001. if (level < -2048 || level > 2047)
  4002. fprintf(stderr, "unquant error %d %d\n", i, level);
  4003. #endif
  4004. block[i] = level;
  4005. }
  4006. }
  4007. }
  4008. static const AVOption mpeg4_options[] =
  4009. {
  4010. AVOPTION_CODEC_INT("bitrate", "desired video bitrate", bit_rate, 4, 240000000, 800000),
  4011. AVOPTION_CODEC_INT("ratetol", "number of bits the bitstream is allowed to diverge from the reference"
  4012. "the reference can be CBR (for CBR pass1) or VBR (for pass2)",
  4013. bit_rate_tolerance, 4, 240000000, 8000),
  4014. AVOPTION_CODEC_INT("qmin", "minimum quantizer", qmin, 1, 31, 2),
  4015. AVOPTION_CODEC_INT("qmax", "maximum quantizer", qmax, 1, 31, 31),
  4016. AVOPTION_CODEC_STRING("rc_eq", "rate control equation",
  4017. rc_eq, "tex^qComp,option1,options2", 0),
  4018. AVOPTION_CODEC_INT("rc_minrate", "rate control minimum bitrate",
  4019. rc_min_rate, 4, 24000000, 0),
  4020. AVOPTION_CODEC_INT("rc_maxrate", "rate control maximum bitrate",
  4021. rc_max_rate, 4, 24000000, 0),
  4022. AVOPTION_CODEC_DOUBLE("rc_buf_aggresivity", "rate control buffer aggresivity",
  4023. rc_buffer_aggressivity, 4, 24000000, 0),
  4024. AVOPTION_CODEC_DOUBLE("rc_initial_cplx", "initial complexity for pass1 ratecontrol",
  4025. rc_initial_cplx, 0., 9999999., 0),
  4026. AVOPTION_CODEC_DOUBLE("i_quant_factor", "qscale factor between p and i frames",
  4027. i_quant_factor, 0., 0., 0),
  4028. AVOPTION_CODEC_DOUBLE("i_quant_offset", "qscale offset between p and i frames",
  4029. i_quant_factor, -999999., 999999., 0),
  4030. AVOPTION_CODEC_INT("dct_algo", "dct alghorithm",
  4031. dct_algo, 0, 5, 0), // fixme - "Auto,FastInt,Int,MMX,MLib,Altivec"
  4032. AVOPTION_CODEC_DOUBLE("lumi_masking", "luminance masking",
  4033. lumi_masking, 0., 999999., 0),
  4034. AVOPTION_CODEC_DOUBLE("temporal_cplx_masking", "temporary complexity masking",
  4035. temporal_cplx_masking, 0., 999999., 0),
  4036. AVOPTION_CODEC_DOUBLE("spatial_cplx_masking", "spatial complexity masking",
  4037. spatial_cplx_masking, 0., 999999., 0),
  4038. AVOPTION_CODEC_DOUBLE("p_masking", "p block masking",
  4039. p_masking, 0., 999999., 0),
  4040. AVOPTION_CODEC_DOUBLE("dark_masking", "darkness masking",
  4041. dark_masking, 0., 999999., 0),
  4042. AVOPTION_CODEC_INT("idct_algo", "idct alghorithm",
  4043. idct_algo, 0, 8, 0), // fixme - "Auto,Int,Simple,SimpleMMX,LibMPEG2MMX,PS2,MLib,ARM,Altivec"
  4044. AVOPTION_CODEC_INT("mb_qmin", "minimum MB quantizer",
  4045. mb_qmin, 0, 8, 0),
  4046. AVOPTION_CODEC_INT("mb_qmax", "maximum MB quantizer",
  4047. mb_qmin, 0, 8, 0),
  4048. AVOPTION_CODEC_INT("me_cmp", "ME compare function",
  4049. me_cmp, 0, 24000000, 0),
  4050. AVOPTION_CODEC_INT("me_sub_cmp", "subpixel ME compare function",
  4051. me_sub_cmp, 0, 24000000, 0),
  4052. AVOPTION_CODEC_INT("dia_size", "ME diamond size & shape",
  4053. dia_size, 0, 24000000, 0),
  4054. AVOPTION_CODEC_INT("last_predictor_count", "amount of previous MV predictors",
  4055. last_predictor_count, 0, 24000000, 0),
  4056. AVOPTION_CODEC_INT("pre_me", "pre pass for ME",
  4057. pre_me, 0, 24000000, 0),
  4058. AVOPTION_CODEC_INT("me_pre_cmp", "ME pre pass compare function",
  4059. me_pre_cmp, 0, 24000000, 0),
  4060. AVOPTION_CODEC_INT("me_range", "maximum ME search range",
  4061. me_range, 0, 24000000, 0),
  4062. AVOPTION_CODEC_INT("pre_dia_size", "ME pre pass diamod size & shape",
  4063. pre_dia_size, 0, 24000000, 0),
  4064. AVOPTION_CODEC_INT("me_subpel_quality", "subpel ME quality",
  4065. me_subpel_quality, 0, 24000000, 0),
  4066. AVOPTION_CODEC_INT("me_range", "maximum ME search range",
  4067. me_range, 0, 24000000, 0),
  4068. AVOPTION_CODEC_FLAG("psnr", "calculate PSNR of compressed frames",
  4069. flags, CODEC_FLAG_PSNR, 0),
  4070. AVOPTION_CODEC_RCOVERRIDE("rc_override", "ratecontrol override (=startframe,endframe,qscale,quality_factor)",
  4071. rc_override),
  4072. AVOPTION_SUB(avoptions_common),
  4073. AVOPTION_END()
  4074. };
  4075. #ifdef CONFIG_ENCODERS
  4076. AVCodec mpeg1video_encoder = {
  4077. "mpeg1video",
  4078. CODEC_TYPE_VIDEO,
  4079. CODEC_ID_MPEG1VIDEO,
  4080. sizeof(MpegEncContext),
  4081. MPV_encode_init,
  4082. MPV_encode_picture,
  4083. MPV_encode_end,
  4084. };
  4085. #ifdef CONFIG_RISKY
  4086. AVCodec mpeg2video_encoder = {
  4087. "mpeg2video",
  4088. CODEC_TYPE_VIDEO,
  4089. CODEC_ID_MPEG2VIDEO,
  4090. sizeof(MpegEncContext),
  4091. MPV_encode_init,
  4092. MPV_encode_picture,
  4093. MPV_encode_end,
  4094. };
  4095. AVCodec h263_encoder = {
  4096. "h263",
  4097. CODEC_TYPE_VIDEO,
  4098. CODEC_ID_H263,
  4099. sizeof(MpegEncContext),
  4100. MPV_encode_init,
  4101. MPV_encode_picture,
  4102. MPV_encode_end,
  4103. };
  4104. AVCodec h263p_encoder = {
  4105. "h263p",
  4106. CODEC_TYPE_VIDEO,
  4107. CODEC_ID_H263P,
  4108. sizeof(MpegEncContext),
  4109. MPV_encode_init,
  4110. MPV_encode_picture,
  4111. MPV_encode_end,
  4112. };
  4113. AVCodec flv_encoder = {
  4114. "flv",
  4115. CODEC_TYPE_VIDEO,
  4116. CODEC_ID_FLV1,
  4117. sizeof(MpegEncContext),
  4118. MPV_encode_init,
  4119. MPV_encode_picture,
  4120. MPV_encode_end,
  4121. };
  4122. AVCodec rv10_encoder = {
  4123. "rv10",
  4124. CODEC_TYPE_VIDEO,
  4125. CODEC_ID_RV10,
  4126. sizeof(MpegEncContext),
  4127. MPV_encode_init,
  4128. MPV_encode_picture,
  4129. MPV_encode_end,
  4130. };
  4131. AVCodec mpeg4_encoder = {
  4132. "mpeg4",
  4133. CODEC_TYPE_VIDEO,
  4134. CODEC_ID_MPEG4,
  4135. sizeof(MpegEncContext),
  4136. MPV_encode_init,
  4137. MPV_encode_picture,
  4138. MPV_encode_end,
  4139. .options = mpeg4_options,
  4140. };
  4141. AVCodec msmpeg4v1_encoder = {
  4142. "msmpeg4v1",
  4143. CODEC_TYPE_VIDEO,
  4144. CODEC_ID_MSMPEG4V1,
  4145. sizeof(MpegEncContext),
  4146. MPV_encode_init,
  4147. MPV_encode_picture,
  4148. MPV_encode_end,
  4149. .options = mpeg4_options,
  4150. };
  4151. AVCodec msmpeg4v2_encoder = {
  4152. "msmpeg4v2",
  4153. CODEC_TYPE_VIDEO,
  4154. CODEC_ID_MSMPEG4V2,
  4155. sizeof(MpegEncContext),
  4156. MPV_encode_init,
  4157. MPV_encode_picture,
  4158. MPV_encode_end,
  4159. .options = mpeg4_options,
  4160. };
  4161. AVCodec msmpeg4v3_encoder = {
  4162. "msmpeg4",
  4163. CODEC_TYPE_VIDEO,
  4164. CODEC_ID_MSMPEG4V3,
  4165. sizeof(MpegEncContext),
  4166. MPV_encode_init,
  4167. MPV_encode_picture,
  4168. MPV_encode_end,
  4169. .options = mpeg4_options,
  4170. };
  4171. AVCodec wmv1_encoder = {
  4172. "wmv1",
  4173. CODEC_TYPE_VIDEO,
  4174. CODEC_ID_WMV1,
  4175. sizeof(MpegEncContext),
  4176. MPV_encode_init,
  4177. MPV_encode_picture,
  4178. MPV_encode_end,
  4179. .options = mpeg4_options,
  4180. };
  4181. #endif
  4182. AVCodec mjpeg_encoder = {
  4183. "mjpeg",
  4184. CODEC_TYPE_VIDEO,
  4185. CODEC_ID_MJPEG,
  4186. sizeof(MpegEncContext),
  4187. MPV_encode_init,
  4188. MPV_encode_picture,
  4189. MPV_encode_end,
  4190. };
  4191. #endif //CONFIG_ENCODERS