Translation system changes part 2: replace macros by strings
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
blob78d3eb5b7af54817b97eac5e96a5318a81680b81
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"
15 #include "fmt-conversion.h"
17 #include "vd_internal.h"
19 static const vd_info_t info = {
20 "FFmpeg's libavcodec codec family",
21 "ffmpeg",
22 "A'rpi",
23 "A'rpi, Michael, Alex",
24 "native codecs"
27 LIBVD_EXTERN(ffmpeg)
29 #include "libavcodec/avcodec.h"
31 #if CONFIG_XVMC
32 #include "libavcodec/xvmc.h"
33 #endif
35 int avcodec_initialized=0;
37 typedef struct {
38 AVCodecContext *avctx;
39 AVFrame *pic;
40 enum PixelFormat pix_fmt;
41 int do_slices;
42 int do_dr1;
43 int vo_initialized;
44 int best_csp;
45 int b_age;
46 int ip_age[2];
47 int qp_stat[32];
48 double qp_sum;
49 double inv_qp_sum;
50 int ip_count;
51 int b_count;
52 AVRational last_sample_aspect_ratio;
53 int lowres;
54 } vd_ffmpeg_ctx;
56 #include "m_option.h"
58 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
59 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
60 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
61 int offset[4], int y, int type, int height);
63 static enum PixelFormat get_format(struct AVCodecContext *avctx,
64 const enum PixelFormat *pix_fmt);
66 const m_option_t lavc_decode_opts_conf[]={
67 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
68 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
69 OPT_FLAG_ON("gray", lavc_param.gray, 0),
70 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
71 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
72 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
73 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
74 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
75 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
76 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
77 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
78 OPT_STRING("lowres", lavc_param.lowres_str, 0),
79 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
80 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
81 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
82 OPT_INTRANGE("threads", lavc_param.threads, 0, 1, 8),
83 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
84 OPT_STRING("o", lavc_param.avopt, 0),
85 {NULL, NULL, 0, 0, 0, 0, NULL}
88 static enum AVDiscard str2AVDiscard(char *str) {
89 if (!str) return AVDISCARD_DEFAULT;
90 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
91 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
92 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
93 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
94 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
95 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
96 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
97 return AVDISCARD_DEFAULT;
100 // to set/get/query special features/parameters
101 static int control(sh_video_t *sh, int cmd, void *arg, ...){
102 vd_ffmpeg_ctx *ctx = sh->context;
103 AVCodecContext *avctx = ctx->avctx;
104 switch(cmd){
105 case VDCTRL_QUERY_FORMAT:
107 int format =(*((int *)arg));
108 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
109 // possible conversions:
110 switch(format){
111 case IMGFMT_YV12:
112 case IMGFMT_IYUV:
113 case IMGFMT_I420:
114 // "converted" using pointer/stride modification
115 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
116 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
117 break;
118 #if CONFIG_XVMC
119 case IMGFMT_XVMC_IDCT_MPEG2:
120 case IMGFMT_XVMC_MOCO_MPEG2:
121 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
122 #endif
124 return CONTROL_FALSE;
126 case VDCTRL_RESYNC_STREAM:
127 avcodec_flush_buffers(avctx);
128 return CONTROL_TRUE;
129 case VDCTRL_QUERY_UNSEEN_FRAMES:;
130 int delay = avctx->has_b_frames;
131 #ifdef FF_THREAD_FRAME
132 // FFmpeg-mt has extra delay when using frame threading
133 if (avctx->thread_type & FF_THREAD_FRAME)
134 delay += avctx->thread_count - 1;
135 #endif
136 return delay + 10;
138 return CONTROL_UNKNOWN;
141 static void mp_msp_av_log_callback(void *ptr, int level, const char *fmt, va_list vl)
143 static int print_prefix=1;
144 AVClass *avc= ptr ? *(AVClass **)ptr : NULL;
145 int type= MSGT_FIXME;
146 int mp_level;
147 char buf[256];
149 switch(level){
150 case AV_LOG_DEBUG: mp_level= MSGL_V ; break;
151 case AV_LOG_INFO : mp_level= MSGL_INFO; break;
152 case AV_LOG_ERROR: mp_level= MSGL_ERR ; break;
153 default : mp_level= MSGL_ERR ; break;
156 if (!mp_msg_test(type, mp_level)) return;
158 if(ptr){
159 if(!strcmp(avc->class_name, "AVCodecContext")){
160 AVCodecContext *s= ptr;
161 if(s->codec){
162 if(s->codec->type == CODEC_TYPE_AUDIO){
163 if(s->codec->decode)
164 type= MSGT_DECAUDIO;
165 }else if(s->codec->type == CODEC_TYPE_VIDEO){
166 if(s->codec->decode)
167 type= MSGT_DECVIDEO;
169 //FIXME subtitles, encoders (what msgt for them? there is no appropriate ...)
171 }else if(!strcmp(avc->class_name, "AVFormatContext")){
172 #if 0 //needs libavformat include FIXME iam too lazy to do this cleanly, probably the whole should be moved out of this file ...
173 AVFormatContext *s= ptr;
174 if(s->iformat)
175 type= MSGT_DEMUXER;
176 else if(s->oformat)
177 type= MSGT_MUXER;
178 #endif
182 if(print_prefix && avc) {
183 mp_msg(type, mp_level, "[%s @ %p]", avc->item_name(ptr), avc);
186 print_prefix= strchr(fmt, '\n') != NULL;
187 vsnprintf(buf, sizeof(buf), fmt, vl);
188 mp_msg(type, mp_level, buf);
191 static void set_format_params(struct AVCodecContext *avctx, enum PixelFormat fmt){
192 int imgfmt;
193 imgfmt = pixfmt2imgfmt(fmt);
194 if (IMGFMT_IS_XVMC(imgfmt) || IMGFMT_IS_VDPAU(imgfmt)) {
195 sh_video_t *sh = avctx->opaque;
196 vd_ffmpeg_ctx *ctx = sh->context;
197 ctx->do_dr1 = 1;
198 ctx->do_slices = 1;
199 avctx->thread_count = 1;
200 avctx->get_buffer = get_buffer;
201 avctx->release_buffer = release_buffer;
202 avctx->reget_buffer = get_buffer;
203 avctx->draw_horiz_band = draw_slice;
204 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] XVMC-accelerated MPEG-2.\n");
205 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
209 // init driver
210 static int init(sh_video_t *sh){
211 struct lavc_param *lavc_param = &sh->opts->lavc_param;
212 AVCodecContext *avctx;
213 vd_ffmpeg_ctx *ctx;
214 AVCodec *lavc_codec;
215 int lowres_w=0;
216 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
218 if(!avcodec_initialized){
219 avcodec_init();
220 avcodec_register_all();
221 avcodec_initialized=1;
222 av_log_set_callback(mp_msp_av_log_callback);
225 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
226 if (!ctx)
227 return 0;
228 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
230 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
231 if(!lavc_codec){
232 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
233 uninit(sh);
234 return 0;
237 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
238 ctx->do_slices=1;
240 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)
241 ctx->do_dr1=1;
242 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
243 ctx->ip_count= ctx->b_count= 0;
245 ctx->pic = avcodec_alloc_frame();
246 ctx->avctx = avcodec_alloc_context();
247 avctx = ctx->avctx;
248 avctx->opaque = sh;
250 #if CONFIG_VDPAU
251 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU){
252 avctx->get_format = get_format;
254 #endif /* CONFIG_VDPAU */
255 #if CONFIG_XVMC
256 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
257 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] XVMC accelerated codec.\n");
258 avctx->get_format= get_format;//for now only this decoder will use it
259 // HACK around badly placed checks in mpeg_mc_decode_init
260 set_format_params(avctx, PIX_FMT_XVMC_MPEG2_IDCT);
262 #endif /* CONFIG_XVMC */
263 if(ctx->do_dr1){
264 avctx->flags|= CODEC_FLAG_EMU_EDGE;
265 avctx->get_buffer= get_buffer;
266 avctx->release_buffer= release_buffer;
267 avctx->reget_buffer= get_buffer;
270 avctx->flags|= lavc_param->bitexact;
272 avctx->width = sh->disp_w;
273 avctx->height= sh->disp_h;
274 avctx->workaround_bugs= lavc_param->workaround_bugs;
275 avctx->error_recognition= lavc_param->error_resilience;
276 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
277 avctx->flags2|= lavc_param->fast;
278 avctx->codec_tag= sh->format;
279 avctx->stream_codec_tag= sh->video.fccHandler;
280 avctx->idct_algo= lavc_param->idct_algo;
281 avctx->error_concealment= lavc_param->error_concealment;
282 avctx->debug= lavc_param->debug;
283 if (lavc_param->debug)
284 av_log_set_level(AV_LOG_DEBUG);
285 avctx->debug_mv= lavc_param->vismv;
286 avctx->skip_top = lavc_param->skip_top;
287 avctx->skip_bottom= lavc_param->skip_bottom;
288 if(lavc_param->lowres_str != NULL)
290 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
291 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
292 ctx->lowres = 0;
293 avctx->lowres = ctx->lowres;
295 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
296 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
297 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
299 if(lavc_param->avopt){
300 if(parse_avopts(avctx, lavc_param->avopt) < 0){
301 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
302 uninit(sh);
303 return 0;
307 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
308 switch (sh->format) {
309 case mmioFOURCC('S','V','Q','3'):
310 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
311 in the phony AVI header if demux_lavf is used. The first case is
312 handled here; the second case falls through to the next section. */
313 if (sh->ImageDesc) {
314 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
315 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
316 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
317 break;
319 /* fallthrough */
321 case mmioFOURCC('A','V','R','n'):
322 case mmioFOURCC('M','J','P','G'):
323 /* AVRn stores huffman table in AVI header */
324 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
325 MJPG fourcc :( */
326 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
327 break;
328 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
329 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
330 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
331 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
333 #if 0
335 int x;
336 uint8_t *p = avctx->extradata;
338 for (x=0; x<avctx->extradata_size; x++)
339 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
340 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
342 #endif
343 break;
345 case mmioFOURCC('R', 'V', '1', '0'):
346 case mmioFOURCC('R', 'V', '1', '3'):
347 case mmioFOURCC('R', 'V', '2', '0'):
348 case mmioFOURCC('R', 'V', '3', '0'):
349 case mmioFOURCC('R', 'V', '4', '0'):
350 if(sh->bih->biSize<sizeof(*sh->bih)+8){
351 /* only 1 packet per frame & sub_id from fourcc */
352 avctx->extradata_size= 8;
353 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
354 ((uint32_t *)avctx->extradata)[0] = 0;
355 ((uint32_t *)avctx->extradata)[1] =
356 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
357 } else {
358 /* has extra slice header (demux_rm or rm->avi streamcopy) */
359 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
360 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
361 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
363 avctx->sub_id= AV_RB32(avctx->extradata+4);
365 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
366 break;
368 default:
369 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
370 break;
371 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
372 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
373 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
374 break;
376 /* Pass palette to codec */
377 if (sh->bih && (sh->bih->biBitCount <= 8)) {
378 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
379 avctx->palctrl->palette_changed = 1;
380 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
381 /* Palette size in biSize */
382 memcpy(avctx->palctrl->palette, sh->bih+1,
383 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
384 else
385 /* Palette size in biClrUsed */
386 memcpy(avctx->palctrl->palette, sh->bih+1,
387 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
390 if(sh->bih)
391 avctx->bits_per_coded_sample= sh->bih->biBitCount;
393 if(lavc_param->threads > 1)
394 avcodec_thread_init(avctx, lavc_param->threads);
395 /* open it */
396 if (avcodec_open(avctx, lavc_codec) < 0) {
397 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
398 uninit(sh);
399 return 0;
401 // this is necessary in case get_format was never called and init_vo is
402 // too late e.g. for H.264 VDPAU
403 set_format_params(avctx, avctx->pix_fmt);
404 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
405 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
408 // uninit driver
409 static void uninit(sh_video_t *sh){
410 vd_ffmpeg_ctx *ctx = sh->context;
411 AVCodecContext *avctx = ctx->avctx;
413 if(sh->opts->lavc_param.vstats){
414 int i;
415 for(i=1; i<32; i++){
416 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
418 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
419 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
420 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
424 if (avctx) {
425 if (avctx->codec && avcodec_close(avctx) < 0)
426 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
428 av_freep(&avctx->extradata);
429 av_freep(&avctx->palctrl);
430 av_freep(&avctx->slice_offset);
433 av_freep(&avctx);
434 av_freep(&ctx->pic);
435 if (ctx)
436 free(ctx);
439 static void draw_slice(struct AVCodecContext *s,
440 const AVFrame *src, int offset[4],
441 int y, int type, int height){
442 sh_video_t *sh = s->opaque;
443 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
444 #if 0
445 int start=0, i;
446 int width= s->width;
447 vd_ffmpeg_ctx *ctx = sh->context;
448 int skip_stride= ((width << ctx->lowres)+15)>>4;
449 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
450 int threshold= s->coded_frame->age;
451 if(s->pict_type!=B_TYPE){
452 for(i=0; i*16<width+16; i++){
453 if(i*16>=width || skip[i]>=threshold){
454 if(start==i) start++;
455 else{
456 uint8_t *src2[3]= {src[0] + start*16,
457 src[1] + start*8,
458 src[2] + start*8};
459 //printf("%2d-%2d x %d\n", start, i, y);
460 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
461 start= i+1;
465 }else
466 #endif
467 if (y < sh->disp_h) {
468 mpcodecs_draw_slice (sh, source, src->linesize, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
473 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
474 vd_ffmpeg_ctx *ctx = sh->context;
475 AVCodecContext *avctx = ctx->avctx;
476 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
477 int width, height;
479 width = avctx->width;
480 height = avctx->height;
482 // HACK!
483 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
484 // use dimensions from BIH to avoid black borders at the right and bottom.
485 if (sh->bih && sh->ImageDesc) {
486 width = sh->bih->biWidth >> ctx->lowres;
487 height = sh->bih->biHeight >> ctx->lowres;
490 // it is possible another vo buffers to be used after vo config()
491 // lavc reset its buffers on width/heigh change but not on aspect change!!!
492 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
493 width != sh->disp_w ||
494 height != sh->disp_h ||
495 pix_fmt != ctx->pix_fmt ||
496 !ctx->vo_initialized)
498 // this is a special-case HACK for MPEG-1/2 VDPAU that uses neither get_format nor
499 // sets the value correctly in avcodec_open.
500 set_format_params(avctx, avctx->pix_fmt);
501 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
502 if (sh->aspect == 0 ||
503 av_cmp_q(avctx->sample_aspect_ratio,
504 ctx->last_sample_aspect_ratio))
505 sh->aspect = aspect;
506 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
507 sh->disp_w = width;
508 sh->disp_h = height;
509 ctx->pix_fmt = pix_fmt;
510 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
511 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
512 return -1;
513 ctx->vo_initialized = 1;
515 return 0;
518 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
519 sh_video_t *sh = avctx->opaque;
520 vd_ffmpeg_ctx *ctx = sh->context;
521 mp_image_t *mpi=NULL;
522 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
523 int type= MP_IMGTYPE_IPB;
524 int width= avctx->width;
525 int height= avctx->height;
526 int align=15;
527 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
528 if(avctx->pix_fmt == PIX_FMT_YUV410P)
529 align=63; //yes seriously, its really needed (16x16 chroma blocks in SVQ1 -> 64x64)
531 if (pic->buffer_hints) {
532 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
533 type = MP_IMGTYPE_TEMP;
534 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
535 flags |= MP_IMGFLAG_READABLE;
536 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
537 type = MP_IMGTYPE_STATIC;
538 flags |= MP_IMGFLAG_PRESERVE;
540 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
541 type = MP_IMGTYPE_STATIC;
542 flags |= MP_IMGFLAG_PRESERVE;
544 flags|=(!avctx->hurry_up && ctx->do_slices) ?
545 MP_IMGFLAG_DRAW_CALLBACK:0;
546 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
547 } else {
548 if(!pic->reference){
549 ctx->b_count++;
550 flags|=(!avctx->hurry_up && ctx->do_slices) ?
551 MP_IMGFLAG_DRAW_CALLBACK:0;
552 }else{
553 ctx->ip_count++;
554 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
555 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
559 if(init_vo(sh, avctx->pix_fmt) < 0){
560 avctx->release_buffer= avcodec_default_release_buffer;
561 avctx->get_buffer= avcodec_default_get_buffer;
562 return avctx->get_buffer(avctx, pic);
565 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
566 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
567 } else
568 if (!pic->buffer_hints) {
569 if(ctx->b_count>1 || ctx->ip_count>2){
570 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
572 ctx->do_dr1=0; //FIXME
573 avctx->get_buffer= avcodec_default_get_buffer;
574 return avctx->get_buffer(avctx, pic);
577 if(avctx->has_b_frames){
578 type= MP_IMGTYPE_IPB;
579 }else{
580 type= MP_IMGTYPE_IP;
582 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
585 mpi= mpcodecs_get_image(sh, type, flags,
586 (width+align)&(~align), (height+align)&(~align));
587 if (!mpi) return -1;
589 // ok, let's see what did we get:
590 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
591 !(mpi->flags&MP_IMGFLAG_DIRECT)){
592 // nice, filter/vo likes draw_callback :)
593 avctx->draw_horiz_band= draw_slice;
594 } else
595 avctx->draw_horiz_band= NULL;
596 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
597 avctx->draw_horiz_band= draw_slice;
599 #if CONFIG_XVMC
600 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
601 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
602 avctx->draw_horiz_band= draw_slice;
603 if(!avctx->xvmc_acceleration) {
604 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
605 assert(0);
606 exit(1);
607 // return -1;//!!fixme check error conditions in ffmpeg
609 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
610 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
611 assert(0);
612 exit(1);
613 // return -1;//!!fixme check error conditions in ffmpeg
615 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
616 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
617 assert(render != 0);
618 assert(render->xvmc_id == AV_XVMC_ID);
619 render->state |= AV_XVMC_STATE_PREDICTION;
621 #endif
623 // Palette support: libavcodec copies palette to *data[1]
624 if (mpi->bpp == 8)
625 mpi->planes[1] = av_malloc(AVPALETTE_SIZE);
627 pic->data[0]= mpi->planes[0];
628 pic->data[1]= mpi->planes[1];
629 pic->data[2]= mpi->planes[2];
631 #if 0
632 assert(mpi->width >= ((width +align)&(~align)));
633 assert(mpi->height >= ((height+align)&(~align)));
634 assert(mpi->stride[0] >= mpi->width);
635 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
636 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
637 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
639 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
640 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
641 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
642 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
643 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
644 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
646 #endif
648 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
649 * lavc will check that and die with an error message, if its not true
651 pic->linesize[0]= mpi->stride[0];
652 pic->linesize[1]= mpi->stride[1];
653 pic->linesize[2]= mpi->stride[2];
655 pic->opaque = mpi;
656 //printf("%X\n", (int)mpi->planes[0]);
657 #if 0
658 if(mpi->flags&MP_IMGFLAG_DIRECT)
659 printf("D");
660 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
661 printf("S");
662 else
663 printf(".");
664 #endif
665 if(pic->reference){
666 pic->age= ctx->ip_age[0];
668 ctx->ip_age[0]= ctx->ip_age[1]+1;
669 ctx->ip_age[1]= 1;
670 ctx->b_age++;
671 }else{
672 pic->age= ctx->b_age;
674 ctx->ip_age[0]++;
675 ctx->ip_age[1]++;
676 ctx->b_age=1;
678 pic->type= FF_BUFFER_TYPE_USER;
679 return 0;
682 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
683 mp_image_t *mpi= pic->opaque;
684 sh_video_t *sh = avctx->opaque;
685 vd_ffmpeg_ctx *ctx = sh->context;
686 int i;
688 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
690 if(ctx->ip_count <= 2 && ctx->b_count<=1){
691 if(mpi->flags&MP_IMGFLAG_PRESERVE)
692 ctx->ip_count--;
693 else
694 ctx->b_count--;
697 if (mpi) {
698 // Palette support: free palette buffer allocated in get_buffer
699 if (mpi->bpp == 8)
700 av_freep(&mpi->planes[1]);
701 #if CONFIG_XVMC
702 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
703 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
704 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
705 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
706 assert(render!=NULL);
707 assert(render->xvmc_id == AV_XVMC_ID);
708 render->state&=~AV_XVMC_STATE_PREDICTION;
710 #endif
711 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
712 mpi->usage_count--;
715 if(pic->type!=FF_BUFFER_TYPE_USER){
716 avcodec_default_release_buffer(avctx, pic);
717 return;
720 for(i=0; i<4; i++){
721 pic->data[i]= NULL;
723 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
726 // copypaste from demux_real.c - it should match to get it working!
727 //FIXME put into some header
728 typedef struct dp_hdr_s {
729 uint32_t chunks; // number of chunks
730 uint32_t timestamp; // timestamp from packet header
731 uint32_t len; // length of actual data
732 uint32_t chunktab; // offset to chunk offset array
733 } dp_hdr_t;
735 static void swap_palette(void *pal) {
736 int i;
737 uint32_t *p = pal;
738 for (i = 0; i < AVPALETTE_COUNT; i++)
739 p[i] = le2me_32(p[i]);
742 // decode a frame
743 static mp_image_t *decode(sh_video_t *sh, void *data, int len, int flags){
744 int got_picture=0;
745 int ret;
746 vd_ffmpeg_ctx *ctx = sh->context;
747 AVFrame *pic= ctx->pic;
748 AVCodecContext *avctx = ctx->avctx;
749 struct lavc_param *lavc_param = &sh->opts->lavc_param;
750 mp_image_t *mpi=NULL;
751 int dr1= ctx->do_dr1;
753 if(len<=0) return NULL; // skipped frame
755 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
756 if (!dr1)
757 avctx->draw_horiz_band=NULL;
758 if(ctx->vo_initialized && !(flags&3) && !dr1){
759 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
760 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
761 sh->disp_w, sh->disp_h);
762 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
763 // vd core likes slices!
764 avctx->draw_horiz_band=draw_slice;
768 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
770 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
771 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
772 ret = avcodec_decode_video(avctx, pic,
773 &got_picture, data, len);
775 dr1= ctx->do_dr1;
776 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
777 //printf("repeat: %d\n", pic->repeat_pict);
778 //-- vstats generation
779 while(lavc_param->vstats){ // always one time loop
780 static FILE *fvstats=NULL;
781 char filename[20];
782 static long long int all_len=0;
783 static int frame_number=0;
784 static double all_frametime=0.0;
785 AVFrame *pic= avctx->coded_frame;
786 double quality=0.0;
788 if(!fvstats) {
789 time_t today2;
790 struct tm *today;
791 today2 = time(NULL);
792 today = localtime(&today2);
793 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
794 today->tm_min, today->tm_sec);
795 fvstats = fopen(filename, "w");
796 if(!fvstats) {
797 perror("fopen");
798 lavc_param->vstats=0; // disable block
799 break;
800 /*exit(1);*/
804 // average MB quantizer
806 int x, y;
807 int w = ((avctx->width << ctx->lowres)+15) >> 4;
808 int h = ((avctx->height << ctx->lowres)+15) >> 4;
809 int8_t *q = pic->qscale_table;
810 for(y = 0; y < h; y++) {
811 for(x = 0; x < w; x++)
812 quality += (double)*(q+x);
813 q += pic->qstride;
815 quality /= w * h;
818 all_len+=len;
819 all_frametime+=sh->frametime;
820 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
821 ++frame_number, quality, len, (double)all_len/1024);
822 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
823 all_frametime, (double)(len*8)/sh->frametime/1000.0,
824 (double)(all_len*8)/all_frametime/1000.0);
825 switch(pic->pict_type){
826 case FF_I_TYPE:
827 fprintf(fvstats, "type= I\n");
828 break;
829 case FF_P_TYPE:
830 fprintf(fvstats, "type= P\n");
831 break;
832 case FF_S_TYPE:
833 fprintf(fvstats, "type= S\n");
834 break;
835 case FF_B_TYPE:
836 fprintf(fvstats, "type= B\n");
837 break;
838 default:
839 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
840 break;
843 ctx->qp_stat[(int)(quality+0.5)]++;
844 ctx->qp_sum += quality;
845 ctx->inv_qp_sum += 1.0/(double)quality;
847 break;
849 //--
851 if(!got_picture) return NULL; // skipped image
853 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
855 if(dr1 && pic->opaque){
856 mpi= (mp_image_t *)pic->opaque;
859 if(!mpi)
860 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
861 avctx->width, avctx->height);
862 if(!mpi){ // temporary!
863 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
864 return NULL;
867 if(!dr1){
868 mpi->planes[0]=pic->data[0];
869 mpi->planes[1]=pic->data[1];
870 mpi->planes[2]=pic->data[2];
871 mpi->stride[0]=pic->linesize[0];
872 mpi->stride[1]=pic->linesize[1];
873 mpi->stride[2]=pic->linesize[2];
876 if (!mpi->planes[0])
877 return NULL;
879 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
880 // we have 422p but user wants 420p
881 mpi->stride[1]*=2;
882 mpi->stride[2]*=2;
885 #ifdef WORDS_BIGENDIAN
886 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
887 if (mpi->bpp == 8)
888 swap_palette(mpi->planes[1]);
889 #endif
890 /* to comfirm with newer lavc style */
891 mpi->qscale =pic->qscale_table;
892 mpi->qstride=pic->qstride;
893 mpi->pict_type=pic->pict_type;
894 mpi->qscale_type= pic->qscale_type;
895 mpi->fields = MP_IMGFIELD_ORDERED;
896 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
897 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
898 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
900 return mpi;
903 #if CONFIG_XVMC || CONFIG_VDPAU
904 static enum PixelFormat get_format(struct AVCodecContext *avctx,
905 const enum PixelFormat *fmt){
906 enum PixelFormat selected_format;
907 int imgfmt;
908 sh_video_t *sh = avctx->opaque;
909 int i;
911 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
912 imgfmt = pixfmt2imgfmt(fmt[i]);
913 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
914 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
915 if(init_vo(sh, fmt[i]) >= 0) {
916 break;
919 selected_format = fmt[i];
920 set_format_params(avctx, selected_format);
921 return selected_format;
923 #endif /* CONFIG_XVMC || CONFIG_VDPAU */