Merge svn changes up to r28549
[mplayer.git] / libmpcodecs / vd_ffmpeg.c
blob1395f524ee26c82a215586322b53403ea8648c06
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4 #include <time.h>
6 #include "config.h"
7 #include "mp_msg.h"
8 #include "help_mp.h"
9 #include "options.h"
10 #include "av_opts.h"
12 #include "libavutil/common.h"
13 #include "libavutil/intreadwrite.h"
14 #include "mpbswap.h"
16 #include "vd_internal.h"
18 static const vd_info_t info = {
19 "FFmpeg's libavcodec codec family",
20 "ffmpeg",
21 "A'rpi",
22 "A'rpi, Michael, Alex",
23 "native codecs"
26 LIBVD_EXTERN(ffmpeg)
28 #include "libavcodec/avcodec.h"
30 #if CONFIG_XVMC
31 #include "xvmc_render.h"
32 #endif
34 int avcodec_initialized=0;
36 typedef struct {
37 AVCodecContext *avctx;
38 AVFrame *pic;
39 enum PixelFormat pix_fmt;
40 int do_slices;
41 int do_dr1;
42 int vo_initialized;
43 int best_csp;
44 int b_age;
45 int ip_age[2];
46 int qp_stat[32];
47 double qp_sum;
48 double inv_qp_sum;
49 int ip_count;
50 int b_count;
51 AVRational last_sample_aspect_ratio;
52 int lowres;
53 } vd_ffmpeg_ctx;
55 #include "m_option.h"
57 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
58 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
60 #if CONFIG_XVMC
61 static enum PixelFormat get_format(struct AVCodecContext * avctx,
62 const enum PixelFormat * pix_fmt);
63 static int mc_get_buffer(AVCodecContext *avctx, AVFrame *pic);
64 static void mc_release_buffer(AVCodecContext *avctx, AVFrame *pic);
65 static void mc_render_slice(struct AVCodecContext *s,
66 const AVFrame *src, int offset[4],
67 int y, int type, int height);
68 #endif
70 const m_option_t lavc_decode_opts_conf[]={
71 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
72 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
73 OPT_FLAG_ON("gray", lavc_param.gray, 0),
74 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
75 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
76 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
77 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
78 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
79 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
80 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
81 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
82 OPT_STRING("lowres", lavc_param.lowres_str, 0),
83 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
84 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
85 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
86 OPT_INTRANGE("threads", lavc_param.threads, 0, 1, 8),
87 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
88 OPT_STRING("o", lavc_param.avopt, 0),
89 {NULL, NULL, 0, 0, 0, 0, NULL}
92 static enum AVDiscard str2AVDiscard(char *str) {
93 if (!str) return AVDISCARD_DEFAULT;
94 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
95 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
96 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
97 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
98 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
99 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
100 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
101 return AVDISCARD_DEFAULT;
104 // to set/get/query special features/parameters
105 static int control(sh_video_t *sh,int cmd,void* arg,...){
106 vd_ffmpeg_ctx *ctx = sh->context;
107 AVCodecContext *avctx = ctx->avctx;
108 switch(cmd){
109 case VDCTRL_QUERY_FORMAT:
111 int format =(*((int*)arg));
112 if( format == ctx->best_csp ) return CONTROL_TRUE;//supported
113 // possible conversions:
114 switch( format ){
115 case IMGFMT_YV12:
116 case IMGFMT_IYUV:
117 case IMGFMT_I420:
118 // "converted" using pointer/stride modification
119 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
120 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
121 break;
122 #if CONFIG_XVMC
123 case IMGFMT_XVMC_IDCT_MPEG2:
124 case IMGFMT_XVMC_MOCO_MPEG2:
125 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
126 #endif
128 return CONTROL_FALSE;
130 break;
131 case VDCTRL_RESYNC_STREAM:
132 avcodec_flush_buffers(avctx);
133 return CONTROL_TRUE;
134 case VDCTRL_QUERY_UNSEEN_FRAMES:
135 return avctx->has_b_frames + 10;
137 return CONTROL_UNKNOWN;
140 static void mp_msp_av_log_callback(void* ptr, int level, const char* fmt, va_list vl)
142 static int print_prefix=1;
143 AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
144 int type= MSGT_FIXME;
145 int mp_level;
146 char buf[256];
148 switch(level){
149 case AV_LOG_DEBUG: mp_level= MSGL_V ; break;
150 case AV_LOG_INFO : mp_level= MSGL_INFO; break;
151 case AV_LOG_ERROR: mp_level= MSGL_ERR ; break;
152 default : mp_level= MSGL_ERR ; break;
155 if (!mp_msg_test(type, mp_level)) return;
157 if(ptr){
158 if(!strcmp(avc->class_name, "AVCodecContext")){
159 AVCodecContext * s= ptr;
160 if(s->codec){
161 if(s->codec->type == CODEC_TYPE_AUDIO){
162 if(s->codec->decode)
163 type= MSGT_DECAUDIO;
164 }else if(s->codec->type == CODEC_TYPE_VIDEO){
165 if(s->codec->decode)
166 type= MSGT_DECVIDEO;
168 //FIXME subtitles, encoders (what msgt for them? there is no appropriate ...)
170 }else if(!strcmp(avc->class_name, "AVFormatContext")){
171 #if 0 //needs libavformat include FIXME iam too lazy to do this cleanly,probably the whole should be moved out of this file ...
172 AVFormatContext * s= ptr;
173 if(s->iformat)
174 type= MSGT_DEMUXER;
175 else if(s->oformat)
176 type= MSGT_MUXER;
177 #endif
181 if(print_prefix && avc) {
182 mp_msg(type, mp_level, "[%s @ %p]", avc->item_name(ptr), avc);
185 print_prefix= strchr(fmt, '\n') != NULL;
186 vsnprintf(buf, sizeof(buf), fmt, vl);
187 mp_msg(type, mp_level, buf);
190 // init driver
191 static int init(sh_video_t *sh){
192 struct lavc_param *lavc_param = &sh->opts->lavc_param;
193 AVCodecContext *avctx;
194 vd_ffmpeg_ctx *ctx;
195 AVCodec *lavc_codec;
196 int lowres_w=0;
197 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
199 if(!avcodec_initialized){
200 avcodec_init();
201 avcodec_register_all();
202 avcodec_initialized=1;
203 av_log_set_callback(mp_msp_av_log_callback);
206 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
207 if (!ctx)
208 return 0;
209 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
211 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
212 if(!lavc_codec){
213 mp_msg(MSGT_DECVIDEO,MSGL_ERR,MSGTR_MissingLAVCcodec,sh->codec->dll);
214 uninit(sh);
215 return 0;
218 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
219 ctx->do_slices=1;
221 if(lavc_codec->capabilities&CODEC_CAP_DR1 && !do_vis_debug && lavc_codec->id != CODEC_ID_H264 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO && lavc_codec->id != CODEC_ID_ROQ)
222 ctx->do_dr1=1;
223 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
224 ctx->ip_count= ctx->b_count= 0;
226 ctx->pic = avcodec_alloc_frame();
227 ctx->avctx = avcodec_alloc_context();
228 avctx = ctx->avctx;
230 #if CONFIG_XVMC
232 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
233 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedCodec);
234 assert(ctx->do_dr1);//these are must to!
235 assert(ctx->do_slices); //it is (vo_)ffmpeg bug if this fails
236 avctx->flags|= CODEC_FLAG_EMU_EDGE;//do i need that??!!
237 avctx->get_format= get_format;//for now only this decoder will use it
238 avctx->get_buffer= mc_get_buffer;
239 avctx->release_buffer= mc_release_buffer;
240 avctx->draw_horiz_band = mc_render_slice;
241 avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
242 }else
243 #endif /* CONFIG_XVMC */
244 if(ctx->do_dr1){
245 avctx->flags|= CODEC_FLAG_EMU_EDGE;
246 avctx->get_buffer= get_buffer;
247 avctx->release_buffer= release_buffer;
248 avctx->reget_buffer= get_buffer;
251 avctx->flags|= lavc_param->bitexact;
253 avctx->width = sh->disp_w;
254 avctx->height= sh->disp_h;
255 avctx->workaround_bugs= lavc_param->workaround_bugs;
256 avctx->error_recognition= lavc_param->error_resilience;
257 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
258 avctx->flags2|= lavc_param->fast;
259 avctx->codec_tag= sh->format;
260 avctx->stream_codec_tag= sh->video.fccHandler;
261 avctx->idct_algo= lavc_param->idct_algo;
262 avctx->error_concealment= lavc_param->error_concealment;
263 avctx->debug= lavc_param->debug;
264 if (lavc_param->debug)
265 av_log_set_level(AV_LOG_DEBUG);
266 avctx->debug_mv= lavc_param->vismv;
267 avctx->skip_top = lavc_param->skip_top;
268 avctx->skip_bottom= lavc_param->skip_bottom;
269 if(lavc_param->lowres_str != NULL)
271 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
272 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
273 ctx->lowres = 0;
274 avctx->lowres = ctx->lowres;
276 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
277 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
278 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
280 if(lavc_param->avopt){
281 if(parse_avopts(avctx, lavc_param->avopt) < 0){
282 mp_msg(MSGT_DECVIDEO,MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
283 uninit(sh);
284 return 0;
288 mp_dbg(MSGT_DECVIDEO,MSGL_DBG2,"libavcodec.size: %d x %d\n",avctx->width,avctx->height);
289 switch (sh->format) {
290 case mmioFOURCC('S','V','Q','3'):
291 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
292 in the phony AVI header if demux_lavf is used. The first case is
293 handled here; the second case falls through to the next section. */
294 if (sh->ImageDesc) {
295 avctx->extradata_size = (*(int*)sh->ImageDesc) - sizeof(int);
296 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
297 memcpy(avctx->extradata, ((int*)sh->ImageDesc)+1, avctx->extradata_size);
298 break;
300 /* fallthrough */
302 case mmioFOURCC('A','V','R','n'):
303 case mmioFOURCC('M','J','P','G'):
304 /* AVRn stores huffman table in AVI header */
305 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
306 MJPG fourcc :( */
307 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
308 break;
309 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
310 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
311 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
312 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
314 #if 0
316 int x;
317 uint8_t *p = avctx->extradata;
319 for (x=0; x<avctx->extradata_size; x++)
320 mp_msg(MSGT_DECVIDEO, MSGL_INFO,"[%x] ", p[x]);
321 mp_msg(MSGT_DECVIDEO, MSGL_INFO,"\n");
323 #endif
324 break;
326 case mmioFOURCC('R', 'V', '1', '0'):
327 case mmioFOURCC('R', 'V', '1', '3'):
328 case mmioFOURCC('R', 'V', '2', '0'):
329 case mmioFOURCC('R', 'V', '3', '0'):
330 case mmioFOURCC('R', 'V', '4', '0'):
331 if(sh->bih->biSize<sizeof(*sh->bih)+8){
332 /* only 1 packet per frame & sub_id from fourcc */
333 avctx->extradata_size= 8;
334 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
335 ((uint32_t*)avctx->extradata)[0] = 0;
336 ((uint32_t*)avctx->extradata)[1] =
337 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
338 } else {
339 /* has extra slice header (demux_rm or rm->avi streamcopy) */
340 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
341 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
342 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
344 avctx->sub_id= AV_RB32(avctx->extradata+4);
346 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
347 break;
349 default:
350 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
351 break;
352 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
353 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
354 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
355 break;
357 /* Pass palette to codec */
358 if (sh->bih && (sh->bih->biBitCount <= 8)) {
359 avctx->palctrl = calloc(1,sizeof(AVPaletteControl));
360 avctx->palctrl->palette_changed = 1;
361 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
362 /* Palette size in biSize */
363 memcpy(avctx->palctrl->palette, sh->bih+1,
364 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
365 else
366 /* Palette size in biClrUsed */
367 memcpy(avctx->palctrl->palette, sh->bih+1,
368 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
371 if(sh->bih)
372 avctx->bits_per_coded_sample= sh->bih->biBitCount;
374 if(lavc_param->threads > 1)
375 avcodec_thread_init(avctx, lavc_param->threads);
376 /* open it */
377 if (avcodec_open(avctx, lavc_codec) < 0) {
378 mp_msg(MSGT_DECVIDEO,MSGL_ERR, MSGTR_CantOpenCodec);
379 uninit(sh);
380 return 0;
382 mp_msg(MSGT_DECVIDEO,MSGL_V,"INFO: libavcodec init OK!\n");
383 return 1; //mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h,IMGFMT_YV12);
386 // uninit driver
387 static void uninit(sh_video_t *sh){
388 vd_ffmpeg_ctx *ctx = sh->context;
389 AVCodecContext *avctx = ctx->avctx;
391 if(sh->opts->lavc_param.vstats){
392 int i;
393 for(i=1; i<32; i++){
394 mp_msg(MSGT_DECVIDEO, MSGL_INFO,"QP: %d, count: %d\n", i, ctx->qp_stat[i]);
396 mp_msg(MSGT_DECVIDEO, MSGL_INFO,MSGTR_MPCODECS_ArithmeticMeanOfQP,
397 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
398 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
402 if (avctx) {
403 if (avctx->codec && avcodec_close(avctx) < 0)
404 mp_msg(MSGT_DECVIDEO,MSGL_ERR, MSGTR_CantCloseCodec);
406 av_freep(&avctx->extradata);
407 av_freep(&avctx->palctrl);
408 av_freep(&avctx->slice_offset);
411 av_freep(&avctx);
412 av_freep(&ctx->pic);
413 if (ctx)
414 free(ctx);
417 static void draw_slice(struct AVCodecContext *s,
418 const AVFrame *src, int offset[4],
419 int y, int type, int height){
420 sh_video_t * sh = s->opaque;
421 uint8_t *source[3]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
422 #if 0
423 int start=0, i;
424 int width= s->width;
425 vd_ffmpeg_ctx *ctx = sh->context;
426 int skip_stride= ((width << ctx->lowres)+15)>>4;
427 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
428 int threshold= s->coded_frame->age;
429 if(s->pict_type!=B_TYPE){
430 for(i=0; i*16<width+16; i++){
431 if(i*16>=width || skip[i]>=threshold){
432 if(start==i) start++;
433 else{
434 uint8_t *src2[3]= {src[0] + start*16,
435 src[1] + start*8,
436 src[2] + start*8};
437 //printf("%2d-%2d x %d\n", start, i, y);
438 mpcodecs_draw_slice (sh,src2, stride, (i-start)*16, height, start*16, y);
439 start= i+1;
443 }else
444 #endif
445 if (y < sh->disp_h) {
446 mpcodecs_draw_slice (sh, source, src->linesize, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
451 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
452 vd_ffmpeg_ctx *ctx = sh->context;
453 AVCodecContext *avctx = ctx->avctx;
454 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
455 int width, height;
457 width = avctx->width;
458 height = avctx->height;
460 // HACK!
461 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
462 // use dimensions from BIH to avoid black borders at the right and bottom.
463 if (sh->bih && sh->ImageDesc) {
464 width = sh->bih->biWidth >> ctx->lowres;
465 height = sh->bih->biHeight >> ctx->lowres;
468 // it is possible another vo buffers to be used after vo config()
469 // lavc reset its buffers on width/heigh change but not on aspect change!!!
470 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
471 width != sh->disp_w ||
472 height != sh->disp_h ||
473 pix_fmt != ctx->pix_fmt ||
474 !ctx->vo_initialized)
476 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
477 if (sh->aspect == 0 ||
478 av_cmp_q(avctx->sample_aspect_ratio,
479 ctx->last_sample_aspect_ratio))
480 sh->aspect = aspect;
481 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
482 sh->disp_w = width;
483 sh->disp_h = height;
484 ctx->pix_fmt = pix_fmt;
485 switch(pix_fmt){
486 // YUVJ are YUV formats that use the full Y range and not just
487 // 16 - 235 (see colorspaces.txt).
488 // Currently they are all treated the same way.
489 case PIX_FMT_YUV410P: ctx->best_csp=IMGFMT_YVU9;break; //svq1
490 case PIX_FMT_YUVJ420P:
491 case PIX_FMT_YUV420P: ctx->best_csp=IMGFMT_YV12;break; //mpegs
492 case PIX_FMT_YUVJ422P:
493 case PIX_FMT_YUV422P: ctx->best_csp=IMGFMT_422P;break; //mjpeg / huffyuv
494 case PIX_FMT_YUVJ444P:
495 case PIX_FMT_YUV444P: ctx->best_csp=IMGFMT_444P;break; //photo jpeg
496 case PIX_FMT_YUV411P: ctx->best_csp=IMGFMT_411P;break; //dv ntsc
497 case PIX_FMT_YUYV422: ctx->best_csp=IMGFMT_YUY2;break; //huffyuv perhaps in the future
498 case PIX_FMT_RGB24 : ctx->best_csp=IMGFMT_RGB24;break; //qtrle
499 case PIX_FMT_RGB32: ctx->best_csp=IMGFMT_BGR32;break; //huffyuv / mjpeg
500 case PIX_FMT_BGR24 : ctx->best_csp=IMGFMT_BGR24;break; //8bps
501 case PIX_FMT_RGB555: ctx->best_csp=IMGFMT_BGR15;break; //rpza,cram
502 case PIX_FMT_RGB565: ctx->best_csp=IMGFMT_BGR16;break; //4xm
503 case PIX_FMT_GRAY8: ctx->best_csp=IMGFMT_Y800;break; // gray jpeg
504 case PIX_FMT_PAL8: ctx->best_csp=IMGFMT_BGR8;break; //8bps,mrle,cram
505 #if CONFIG_XVMC
506 case PIX_FMT_XVMC_MPEG2_MC:ctx->best_csp=IMGFMT_XVMC_MOCO_MPEG2;break;
507 case PIX_FMT_XVMC_MPEG2_IDCT:ctx->best_csp=IMGFMT_XVMC_IDCT_MPEG2;break;
508 #endif
509 default:
510 ctx->best_csp=0;
512 if (!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h, ctx->best_csp))
513 return -1;
514 ctx->vo_initialized = 1;
516 return 0;
519 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
520 sh_video_t * sh = avctx->opaque;
521 vd_ffmpeg_ctx *ctx = sh->context;
522 mp_image_t* mpi=NULL;
523 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
524 int type= MP_IMGTYPE_IPB;
525 int width= avctx->width;
526 int height= avctx->height;
527 int align=15;
528 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
529 if(avctx->pix_fmt == PIX_FMT_YUV410P)
530 align=63; //yes seriously, its really needed (16x16 chroma blocks in SVQ1 -> 64x64)
532 if (pic->buffer_hints) {
533 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
534 type = MP_IMGTYPE_TEMP;
535 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
536 flags |= MP_IMGFLAG_READABLE;
537 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
538 type = MP_IMGTYPE_STATIC;
539 flags |= MP_IMGFLAG_PRESERVE;
541 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
542 type = MP_IMGTYPE_STATIC;
543 flags |= MP_IMGFLAG_PRESERVE;
545 flags|=(!avctx->hurry_up && ctx->do_slices) ?
546 MP_IMGFLAG_DRAW_CALLBACK:0;
547 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
548 } else {
549 if(!pic->reference){
550 ctx->b_count++;
551 flags|=(!avctx->hurry_up && ctx->do_slices) ?
552 MP_IMGFLAG_DRAW_CALLBACK:0;
553 }else{
554 ctx->ip_count++;
555 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
556 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
560 if(init_vo(sh,avctx->pix_fmt) < 0){
561 avctx->release_buffer= avcodec_default_release_buffer;
562 avctx->get_buffer= avcodec_default_get_buffer;
563 return avctx->get_buffer(avctx, pic);
566 if (!pic->buffer_hints) {
567 if(ctx->b_count>1 || ctx->ip_count>2){
568 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_DRIFailure);
570 ctx->do_dr1=0; //FIXME
571 avctx->get_buffer= avcodec_default_get_buffer;
572 return avctx->get_buffer(avctx, pic);
575 if(avctx->has_b_frames){
576 type= MP_IMGTYPE_IPB;
577 }else{
578 type= MP_IMGTYPE_IP;
580 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
583 mpi= mpcodecs_get_image(sh,type, flags,
584 (width+align)&(~align), (height+align)&(~align));
586 // ok, let's see what did we get:
587 if( mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
588 !(mpi->flags&MP_IMGFLAG_DIRECT)){
589 // nice, filter/vo likes draw_callback :)
590 avctx->draw_horiz_band= draw_slice;
591 } else
592 avctx->draw_horiz_band= NULL;
594 // Palette support: libavcodec copies palette to *data[1]
595 if (mpi->bpp == 8)
596 mpi->planes[1] = av_malloc(AVPALETTE_SIZE);
598 pic->data[0]= mpi->planes[0];
599 pic->data[1]= mpi->planes[1];
600 pic->data[2]= mpi->planes[2];
602 #if 0
603 assert(mpi->width >= ((width +align)&(~align)));
604 assert(mpi->height >= ((height+align)&(~align)));
605 assert(mpi->stride[0] >= mpi->width);
606 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
607 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
608 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
610 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
611 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
612 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
613 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
614 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
615 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
617 #endif
619 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
620 * lavc will check that and die with an error message, if its not true
622 pic->linesize[0]= mpi->stride[0];
623 pic->linesize[1]= mpi->stride[1];
624 pic->linesize[2]= mpi->stride[2];
626 pic->opaque = mpi;
627 //printf("%X\n", (int)mpi->planes[0]);
628 #if 0
629 if(mpi->flags&MP_IMGFLAG_DIRECT)
630 printf("D");
631 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
632 printf("S");
633 else
634 printf(".");
635 #endif
636 if(pic->reference){
637 pic->age= ctx->ip_age[0];
639 ctx->ip_age[0]= ctx->ip_age[1]+1;
640 ctx->ip_age[1]= 1;
641 ctx->b_age++;
642 }else{
643 pic->age= ctx->b_age;
645 ctx->ip_age[0]++;
646 ctx->ip_age[1]++;
647 ctx->b_age=1;
649 pic->type= FF_BUFFER_TYPE_USER;
650 return 0;
653 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
654 mp_image_t* mpi= pic->opaque;
655 sh_video_t * sh = avctx->opaque;
656 vd_ffmpeg_ctx *ctx = sh->context;
657 int i;
659 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
661 if(ctx->ip_count <= 2 && ctx->b_count<=1){
662 if(mpi->flags&MP_IMGFLAG_PRESERVE)
663 ctx->ip_count--;
664 else
665 ctx->b_count--;
668 // Palette support: free palette buffer allocated in get_buffer
669 if ( mpi && (mpi->bpp == 8))
670 av_freep(&mpi->planes[1]);
672 if(pic->type!=FF_BUFFER_TYPE_USER){
673 avcodec_default_release_buffer(avctx, pic);
674 return;
677 for(i=0; i<4; i++){
678 pic->data[i]= NULL;
680 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
683 // copypaste from demux_real.c - it should match to get it working!
684 //FIXME put into some header
685 typedef struct dp_hdr_s {
686 uint32_t chunks; // number of chunks
687 uint32_t timestamp; // timestamp from packet header
688 uint32_t len; // length of actual data
689 uint32_t chunktab; // offset to chunk offset array
690 } dp_hdr_t;
692 static void swap_palette(void *pal) {
693 int i;
694 uint32_t *p = pal;
695 for (i = 0; i < AVPALETTE_COUNT; i++)
696 p[i] = le2me_32(p[i]);
699 // decode a frame
700 static mp_image_t* decode(sh_video_t *sh,void* data,int len,int flags){
701 int got_picture=0;
702 int ret;
703 vd_ffmpeg_ctx *ctx = sh->context;
704 AVFrame *pic= ctx->pic;
705 AVCodecContext *avctx = ctx->avctx;
706 struct lavc_param *lavc_param = &sh->opts->lavc_param;
707 mp_image_t* mpi=NULL;
708 int dr1= ctx->do_dr1;
710 if(len<=0) return NULL; // skipped frame
712 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
713 if (!dr1)
714 avctx->draw_horiz_band=NULL;
715 avctx->opaque=sh;
716 if(ctx->vo_initialized && !(flags&3) && !dr1){
717 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
718 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
719 sh->disp_w, sh->disp_h);
720 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
721 // vd core likes slices!
722 avctx->draw_horiz_band=draw_slice;
726 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
728 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
729 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
730 ret = avcodec_decode_video(avctx, pic,
731 &got_picture, data, len);
733 dr1= ctx->do_dr1;
734 if(ret<0) mp_msg(MSGT_DECVIDEO,MSGL_WARN, "Error while decoding frame!\n");
735 //printf("repeat: %d\n", pic->repeat_pict);
736 //-- vstats generation
737 while(lavc_param->vstats){ // always one time loop
738 static FILE *fvstats=NULL;
739 char filename[20];
740 static long long int all_len=0;
741 static int frame_number=0;
742 static double all_frametime=0.0;
743 AVFrame *pic= avctx->coded_frame;
744 double quality=0.0;
746 if(!fvstats) {
747 time_t today2;
748 struct tm *today;
749 today2 = time(NULL);
750 today = localtime(&today2);
751 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
752 today->tm_min, today->tm_sec);
753 fvstats = fopen(filename,"w");
754 if(!fvstats) {
755 perror("fopen");
756 lavc_param->vstats=0; // disable block
757 break;
758 /*exit(1);*/
762 // average MB quantizer
764 int x, y;
765 int w = ((avctx->width << ctx->lowres)+15) >> 4;
766 int h = ((avctx->height << ctx->lowres)+15) >> 4;
767 int8_t *q = pic->qscale_table;
768 for( y = 0; y < h; y++ ) {
769 for( x = 0; x < w; x++ )
770 quality += (double)*(q+x);
771 q += pic->qstride;
773 quality /= w * h;
776 all_len+=len;
777 all_frametime+=sh->frametime;
778 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
779 ++frame_number, quality, len, (double)all_len/1024);
780 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
781 all_frametime, (double)(len*8)/sh->frametime/1000.0,
782 (double)(all_len*8)/all_frametime/1000.0);
783 switch(pic->pict_type){
784 case FF_I_TYPE:
785 fprintf(fvstats, "type= I\n");
786 break;
787 case FF_P_TYPE:
788 fprintf(fvstats, "type= P\n");
789 break;
790 case FF_S_TYPE:
791 fprintf(fvstats, "type= S\n");
792 break;
793 case FF_B_TYPE:
794 fprintf(fvstats, "type= B\n");
795 break;
796 default:
797 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
798 break;
801 ctx->qp_stat[(int)(quality+0.5)]++;
802 ctx->qp_sum += quality;
803 ctx->inv_qp_sum += 1.0/(double)quality;
805 break;
807 //--
809 if(!got_picture) return NULL; // skipped image
811 if(init_vo(sh,avctx->pix_fmt) < 0) return NULL;
813 if(dr1 && pic->opaque){
814 mpi= (mp_image_t*)pic->opaque;
817 if(!mpi)
818 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
819 avctx->width, avctx->height);
820 if(!mpi){ // temporary!
821 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_CouldntAllocateImageForCodec);
822 return NULL;
825 if(!dr1){
826 mpi->planes[0]=pic->data[0];
827 mpi->planes[1]=pic->data[1];
828 mpi->planes[2]=pic->data[2];
829 mpi->stride[0]=pic->linesize[0];
830 mpi->stride[1]=pic->linesize[1];
831 mpi->stride[2]=pic->linesize[2];
834 if (!mpi->planes[0])
835 return NULL;
837 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
838 // we have 422p but user wants 420p
839 mpi->stride[1]*=2;
840 mpi->stride[2]*=2;
843 #ifdef WORDS_BIGENDIAN
844 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
845 if (mpi->bpp == 8)
846 swap_palette(mpi->planes[1]);
847 #endif
848 /* to comfirm with newer lavc style */
849 mpi->qscale =pic->qscale_table;
850 mpi->qstride=pic->qstride;
851 mpi->pict_type=pic->pict_type;
852 mpi->qscale_type= pic->qscale_type;
853 mpi->fields = MP_IMGFIELD_ORDERED;
854 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
855 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
856 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
858 return mpi;
861 #if CONFIG_XVMC
862 static enum PixelFormat get_format(struct AVCodecContext * avctx,
863 const enum PixelFormat * fmt){
864 sh_video_t * sh = avctx->opaque;
865 int i;
867 if(avctx->xvmc_acceleration){
868 vd_ffmpeg_ctx *ctx = sh->context;
869 avctx->get_buffer= mc_get_buffer;
870 avctx->release_buffer= mc_release_buffer;
871 avctx->draw_horiz_band = mc_render_slice;
872 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedMPEG2);
873 assert(ctx->do_dr1);//these are must to!
874 assert(ctx->do_slices); //it is (vo_)ffmpeg bug if this fails
875 avctx->flags|= CODEC_FLAG_EMU_EDGE;//do i need that??!!
876 avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
878 for(i=0;fmt[i]!=-1;i++){
879 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_TryingPixfmt,i);
880 if( init_vo(sh,fmt[i]) >= 0)
881 return fmt[i];
883 return fmt[0];
886 static int mc_get_buffer(AVCodecContext *avctx, AVFrame *pic){
887 sh_video_t * sh = avctx->opaque;
888 vd_ffmpeg_ctx *ctx = sh->context;
889 mp_image_t* mpi=NULL;
890 struct xvmc_render_state * render;
891 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE|
892 MP_IMGFLAG_DRAW_CALLBACK;
894 // printf("vd_ffmpeg::mc_get_buffer (xvmc) %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
895 if(!avctx->xvmc_acceleration){
896 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_McGetBufferShouldWorkOnlyWithXVMC);
897 assert(0);
898 exit(1);
899 // return -1;//!!fixme check error conditions
901 assert(avctx->draw_horiz_band == mc_render_slice);
902 assert(avctx->release_buffer == mc_release_buffer);
903 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
904 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_get_buffer\n");
906 if(init_vo(sh,avctx->pix_fmt) < 0){
907 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_UnexpectedInitVoError);
908 exit(1);
909 // return -1;//!!fixme check error conditions
914 if(!pic->reference){
915 ctx->b_count++;
916 }else{
917 ctx->ip_count++;
918 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE;
921 mpi= mpcodecs_get_image(sh, MP_IMGTYPE_IPB,flags ,
922 avctx->width, avctx->height);
923 if(mpi==NULL){
924 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_UnrecoverableErrorRenderBuffersNotTaken);
925 assert(0);
926 exit(1);
927 // return -1;//!!fixme check error conditions in ffmpeg
930 if( (mpi->flags & MP_IMGFLAG_DIRECT) == 0){
931 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_OnlyBuffersAllocatedByVoXvmcAllowed);
932 assert(0);
933 exit(1);
934 // return -1;//!!fixme check error conditions in ffmpeg
937 pic->data[0]= mpi->planes[0];
938 pic->data[1]= mpi->planes[1];
939 pic->data[2]= mpi->planes[2];
942 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
943 * lavc will check that and die with an error message, if its not true
945 pic->linesize[0]= mpi->stride[0];
946 pic->linesize[1]= mpi->stride[1];
947 pic->linesize[2]= mpi->stride[2];
949 pic->opaque = mpi;
951 if(pic->reference){
952 //I or P frame
953 pic->age= ctx->ip_age[0];
955 ctx->ip_age[0]= ctx->ip_age[1]+1;
956 ctx->ip_age[1]= 1;
957 ctx->b_age++;
958 }else{
959 //B frame
960 pic->age= ctx->b_age;
962 ctx->ip_age[0]++;
963 ctx->ip_age[1]++;
964 ctx->b_age=1;
967 pic->type= FF_BUFFER_TYPE_USER;
969 render=(struct xvmc_render_state*)mpi->priv;//same as data[2]
970 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
971 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_get_buffer (render=%p)\n",render);
972 assert(render != 0);
973 assert(render->magic == MP_XVMC_RENDER_MAGIC);
974 render->state |= MP_XVMC_STATE_PREDICTION;
975 return 0;
979 static void mc_release_buffer(AVCodecContext *avctx, AVFrame *pic){
980 mp_image_t* mpi= pic->opaque;
981 sh_video_t * sh = avctx->opaque;
982 vd_ffmpeg_ctx *ctx = sh->context;
983 struct xvmc_render_state * render;
984 int i;
987 if(ctx->ip_count <= 2 && ctx->b_count<=1){
988 if(mpi->flags&MP_IMGFLAG_PRESERVE)
989 ctx->ip_count--;
990 else
991 ctx->b_count--;
994 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
995 //mark the surface as not requared for prediction
996 render=(struct xvmc_render_state*)pic->data[2];//same as mpi->priv
997 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
998 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_release_buffer (render=%p)\n",render);
999 assert(render!=NULL);
1000 assert(render->magic==MP_XVMC_RENDER_MAGIC);
1001 render->state&=~MP_XVMC_STATE_PREDICTION;
1002 for(i=0; i<4; i++){
1003 pic->data[i]= NULL;
1007 static void mc_render_slice(struct AVCodecContext *s,
1008 const AVFrame *src, int offset[4],
1009 int y, int type, int height){
1010 int width= s->width;
1011 sh_video_t * sh = s->opaque;
1012 uint8_t *source[3]= {src->data[0], src->data[1], src->data[2]};
1014 assert(src->linesize[0]==0 && src->linesize[1]==0 && src->linesize[2]==0);
1015 assert(offset[0]==0 && offset[1]==0 && offset[2]==0);
1017 mpcodecs_draw_slice (sh, source, src->linesize, width, height, 0, y);
1021 #endif /* CONFIG_XVMC */