demux_mkv: remove useless code
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
bloba89e0a4dbec24d606455bd3a32cc1392a74ac434
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 "ffmpeg_files/intreadwrite.h"
14 #include "mpbswap.h"
15 #include "fmt-conversion.h"
17 #include "vd.h"
18 #include "img_format.h"
19 #include "libmpdemux/stheader.h"
20 #include "codec-cfg.h"
22 static const vd_info_t info = {
23 "FFmpeg's libavcodec codec family",
24 "ffmpeg",
25 "A'rpi",
26 "A'rpi, Michael, Alex",
27 "native codecs"
30 #include "libavcodec/avcodec.h"
32 #if AVPALETTE_SIZE > 1024
33 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
34 #endif
36 #if CONFIG_XVMC
37 #include "libavcodec/xvmc.h"
38 #endif
40 int avcodec_initialized=0;
42 typedef struct {
43 AVCodecContext *avctx;
44 AVFrame *pic;
45 enum PixelFormat pix_fmt;
46 int do_slices;
47 int do_dr1;
48 int vo_initialized;
49 int best_csp;
50 int b_age;
51 int ip_age[2];
52 int qp_stat[32];
53 double qp_sum;
54 double inv_qp_sum;
55 int ip_count;
56 int b_count;
57 AVRational last_sample_aspect_ratio;
58 int lowres;
59 } vd_ffmpeg_ctx;
61 #include "m_option.h"
63 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
64 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
65 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
66 int offset[4], int y, int type, int height);
68 static enum PixelFormat get_format(struct AVCodecContext *avctx,
69 const enum PixelFormat *pix_fmt);
70 static void uninit(struct sh_video *sh);
72 const m_option_t lavc_decode_opts_conf[]={
73 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
74 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
75 OPT_FLAG_ON("gray", lavc_param.gray, 0),
76 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
77 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
78 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
79 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
80 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
81 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
82 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
83 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
84 OPT_STRING("lowres", lavc_param.lowres_str, 0),
85 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
86 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
87 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
88 OPT_INTRANGE("threads", lavc_param.threads, 0, 1, 8),
89 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
90 OPT_STRING("o", lavc_param.avopt, 0),
91 {NULL, NULL, 0, 0, 0, 0, NULL}
94 static enum AVDiscard str2AVDiscard(char *str) {
95 if (!str) return AVDISCARD_DEFAULT;
96 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
97 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
98 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
99 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
100 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
101 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
102 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
103 return AVDISCARD_DEFAULT;
106 // to set/get/query special features/parameters
107 static int control(sh_video_t *sh, int cmd, void *arg, ...){
108 vd_ffmpeg_ctx *ctx = sh->context;
109 AVCodecContext *avctx = ctx->avctx;
110 switch(cmd){
111 case VDCTRL_QUERY_FORMAT:
113 int format =(*((int *)arg));
114 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
115 // possible conversions:
116 switch(format){
117 case IMGFMT_YV12:
118 case IMGFMT_IYUV:
119 case IMGFMT_I420:
120 // "converted" using pointer/stride modification
121 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
122 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
123 break;
124 #if CONFIG_XVMC
125 case IMGFMT_XVMC_IDCT_MPEG2:
126 case IMGFMT_XVMC_MOCO_MPEG2:
127 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
128 #endif
130 return CONTROL_FALSE;
132 case VDCTRL_RESYNC_STREAM:
133 avcodec_flush_buffers(avctx);
134 return CONTROL_TRUE;
135 case VDCTRL_QUERY_UNSEEN_FRAMES:;
136 int delay = avctx->has_b_frames;
137 #ifdef FF_THREAD_FRAME
138 // FFmpeg-mt has extra delay when using frame threading
139 if (avctx->thread_type & FF_THREAD_FRAME)
140 delay += avctx->thread_count - 1;
141 #endif
142 return delay + 10;
144 return CONTROL_UNKNOWN;
147 static void set_format_params(struct AVCodecContext *avctx, enum PixelFormat fmt){
148 int imgfmt;
149 imgfmt = pixfmt2imgfmt(fmt);
150 if (IMGFMT_IS_XVMC(imgfmt) || IMGFMT_IS_VDPAU(imgfmt)) {
151 sh_video_t *sh = avctx->opaque;
152 vd_ffmpeg_ctx *ctx = sh->context;
153 ctx->do_dr1 = 1;
154 ctx->do_slices = 1;
155 avctx->thread_count = 1;
156 avctx->get_buffer = get_buffer;
157 avctx->release_buffer = release_buffer;
158 avctx->reget_buffer = get_buffer;
159 avctx->draw_horiz_band = draw_slice;
160 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] XVMC-accelerated MPEG-2.\n");
161 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
165 // init driver
166 static int init(sh_video_t *sh){
167 struct lavc_param *lavc_param = &sh->opts->lavc_param;
168 AVCodecContext *avctx;
169 vd_ffmpeg_ctx *ctx;
170 AVCodec *lavc_codec;
171 int lowres_w=0;
172 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
174 if(!avcodec_initialized){
175 avcodec_init();
176 avcodec_register_all();
177 avcodec_initialized=1;
180 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
181 if (!ctx)
182 return 0;
183 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
185 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
186 if(!lavc_codec){
187 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
188 uninit(sh);
189 return 0;
192 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
193 ctx->do_slices=1;
195 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)
196 ctx->do_dr1=1;
197 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
198 ctx->ip_count= ctx->b_count= 0;
200 ctx->pic = avcodec_alloc_frame();
201 ctx->avctx = avcodec_alloc_context();
202 avctx = ctx->avctx;
203 avctx->opaque = sh;
204 avctx->codec_type = CODEC_TYPE_VIDEO;
205 avctx->codec_id = lavc_codec->id;
207 #if CONFIG_VDPAU
208 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU){
209 avctx->get_format = get_format;
211 #endif /* CONFIG_VDPAU */
212 #if CONFIG_XVMC
213 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
214 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] XVMC accelerated codec.\n");
215 avctx->get_format= get_format;//for now only this decoder will use it
216 // HACK around badly placed checks in mpeg_mc_decode_init
217 set_format_params(avctx, PIX_FMT_XVMC_MPEG2_IDCT);
219 #endif /* CONFIG_XVMC */
220 if(ctx->do_dr1){
221 avctx->flags|= CODEC_FLAG_EMU_EDGE;
222 avctx->get_buffer= get_buffer;
223 avctx->release_buffer= release_buffer;
224 avctx->reget_buffer= get_buffer;
227 avctx->flags|= lavc_param->bitexact;
229 avctx->width = sh->disp_w;
230 avctx->height= sh->disp_h;
231 avctx->workaround_bugs= lavc_param->workaround_bugs;
232 avctx->error_recognition= lavc_param->error_resilience;
233 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
234 avctx->flags2|= lavc_param->fast;
235 avctx->codec_tag= sh->format;
236 avctx->stream_codec_tag= sh->video.fccHandler;
237 avctx->idct_algo= lavc_param->idct_algo;
238 avctx->error_concealment= lavc_param->error_concealment;
239 avctx->debug= lavc_param->debug;
240 if (lavc_param->debug)
241 av_log_set_level(AV_LOG_DEBUG);
242 avctx->debug_mv= lavc_param->vismv;
243 avctx->skip_top = lavc_param->skip_top;
244 avctx->skip_bottom= lavc_param->skip_bottom;
245 if(lavc_param->lowres_str != NULL)
247 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
248 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
249 ctx->lowres = 0;
250 avctx->lowres = ctx->lowres;
252 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
253 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
254 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
256 if(lavc_param->avopt){
257 if(parse_avopts(avctx, lavc_param->avopt) < 0){
258 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
259 uninit(sh);
260 return 0;
264 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
265 switch (sh->format) {
266 case mmioFOURCC('S','V','Q','3'):
267 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
268 in the phony AVI header if demux_lavf is used. The first case is
269 handled here; the second case falls through to the next section. */
270 if (sh->ImageDesc) {
271 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
272 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
273 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
274 break;
276 /* fallthrough */
278 case mmioFOURCC('A','V','R','n'):
279 case mmioFOURCC('M','J','P','G'):
280 /* AVRn stores huffman table in AVI header */
281 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
282 MJPG fourcc :( */
283 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
284 break;
285 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
286 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
287 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
288 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
290 #if 0
292 int x;
293 uint8_t *p = avctx->extradata;
295 for (x=0; x<avctx->extradata_size; x++)
296 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
297 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
299 #endif
300 break;
302 case mmioFOURCC('R', 'V', '1', '0'):
303 case mmioFOURCC('R', 'V', '1', '3'):
304 case mmioFOURCC('R', 'V', '2', '0'):
305 case mmioFOURCC('R', 'V', '3', '0'):
306 case mmioFOURCC('R', 'V', '4', '0'):
307 if(sh->bih->biSize<sizeof(*sh->bih)+8){
308 /* only 1 packet per frame & sub_id from fourcc */
309 avctx->extradata_size= 8;
310 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
311 ((uint32_t *)avctx->extradata)[0] = 0;
312 ((uint32_t *)avctx->extradata)[1] =
313 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
314 } else {
315 /* has extra slice header (demux_rm or rm->avi streamcopy) */
316 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
317 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
318 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
320 avctx->sub_id= AV_RB32(avctx->extradata+4);
322 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
323 break;
325 default:
326 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
327 break;
328 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
329 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
330 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
331 break;
333 /* Pass palette to codec */
334 if (sh->bih && (sh->bih->biBitCount <= 8)) {
335 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
336 avctx->palctrl->palette_changed = 1;
337 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
338 /* Palette size in biSize */
339 memcpy(avctx->palctrl->palette, sh->bih+1,
340 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
341 else
342 /* Palette size in biClrUsed */
343 memcpy(avctx->palctrl->palette, sh->bih+1,
344 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
347 if(sh->bih)
348 avctx->bits_per_coded_sample= sh->bih->biBitCount;
350 if(lavc_param->threads > 1)
351 avcodec_thread_init(avctx, lavc_param->threads);
352 /* open it */
353 if (avcodec_open(avctx, lavc_codec) < 0) {
354 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
355 uninit(sh);
356 return 0;
358 // this is necessary in case get_format was never called and init_vo is
359 // too late e.g. for H.264 VDPAU
360 set_format_params(avctx, avctx->pix_fmt);
361 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
362 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
365 // uninit driver
366 static void uninit(sh_video_t *sh){
367 vd_ffmpeg_ctx *ctx = sh->context;
368 AVCodecContext *avctx = ctx->avctx;
370 if(sh->opts->lavc_param.vstats){
371 int i;
372 for(i=1; i<32; i++){
373 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
375 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
376 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
377 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
381 if (avctx) {
382 if (avctx->codec && avcodec_close(avctx) < 0)
383 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
385 av_freep(&avctx->extradata);
386 av_freep(&avctx->palctrl);
387 av_freep(&avctx->slice_offset);
390 av_freep(&avctx);
391 av_freep(&ctx->pic);
392 if (ctx)
393 free(ctx);
396 static void draw_slice(struct AVCodecContext *s,
397 const AVFrame *src, int offset[4],
398 int y, int type, int height){
399 sh_video_t *sh = s->opaque;
400 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
401 #if 0
402 int start=0, i;
403 int width= s->width;
404 vd_ffmpeg_ctx *ctx = sh->context;
405 int skip_stride= ((width << ctx->lowres)+15)>>4;
406 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
407 int threshold= s->coded_frame->age;
408 if(s->pict_type!=B_TYPE){
409 for(i=0; i*16<width+16; i++){
410 if(i*16>=width || skip[i]>=threshold){
411 if(start==i) start++;
412 else{
413 uint8_t *src2[3]= {src[0] + start*16,
414 src[1] + start*8,
415 src[2] + start*8};
416 //printf("%2d-%2d x %d\n", start, i, y);
417 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
418 start= i+1;
422 }else
423 #endif
424 if (y < sh->disp_h) {
425 mpcodecs_draw_slice (sh, source, src->linesize, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
430 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
431 vd_ffmpeg_ctx *ctx = sh->context;
432 AVCodecContext *avctx = ctx->avctx;
433 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
434 int width, height;
436 width = avctx->width;
437 height = avctx->height;
439 // HACK!
440 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
441 // use dimensions from BIH to avoid black borders at the right and bottom.
442 if (sh->bih && sh->ImageDesc) {
443 width = sh->bih->biWidth >> ctx->lowres;
444 height = sh->bih->biHeight >> ctx->lowres;
447 // it is possible another vo buffers to be used after vo config()
448 // lavc reset its buffers on width/heigh change but not on aspect change!!!
449 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
450 width != sh->disp_w ||
451 height != sh->disp_h ||
452 pix_fmt != ctx->pix_fmt ||
453 !ctx->vo_initialized)
455 // this is a special-case HACK for MPEG-1/2 VDPAU that uses neither get_format nor
456 // sets the value correctly in avcodec_open.
457 set_format_params(avctx, avctx->pix_fmt);
458 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
459 if (sh->aspect == 0 ||
460 av_cmp_q(avctx->sample_aspect_ratio,
461 ctx->last_sample_aspect_ratio))
462 sh->aspect = aspect;
463 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
464 sh->disp_w = width;
465 sh->disp_h = height;
466 ctx->pix_fmt = pix_fmt;
467 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
468 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
469 return -1;
470 ctx->vo_initialized = 1;
472 return 0;
475 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
476 sh_video_t *sh = avctx->opaque;
477 vd_ffmpeg_ctx *ctx = sh->context;
478 mp_image_t *mpi=NULL;
479 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
480 int type= MP_IMGTYPE_IPB;
481 int width= avctx->width;
482 int height= avctx->height;
483 avcodec_align_dimensions(avctx, &width, &height);
484 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
486 if (pic->buffer_hints) {
487 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
488 type = MP_IMGTYPE_TEMP;
489 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
490 flags |= MP_IMGFLAG_READABLE;
491 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
492 type = MP_IMGTYPE_STATIC;
493 flags |= MP_IMGFLAG_PRESERVE;
495 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
496 type = MP_IMGTYPE_STATIC;
497 flags |= MP_IMGFLAG_PRESERVE;
499 flags|=(!avctx->hurry_up && ctx->do_slices) ?
500 MP_IMGFLAG_DRAW_CALLBACK:0;
501 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
502 } else {
503 if(!pic->reference){
504 ctx->b_count++;
505 flags|=(!avctx->hurry_up && ctx->do_slices) ?
506 MP_IMGFLAG_DRAW_CALLBACK:0;
507 }else{
508 ctx->ip_count++;
509 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
510 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
514 if(init_vo(sh, avctx->pix_fmt) < 0){
515 avctx->release_buffer= avcodec_default_release_buffer;
516 avctx->get_buffer= avcodec_default_get_buffer;
517 return avctx->get_buffer(avctx, pic);
520 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
521 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
522 } else
523 if (!pic->buffer_hints) {
524 if(ctx->b_count>1 || ctx->ip_count>2){
525 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
527 ctx->do_dr1=0; //FIXME
528 avctx->get_buffer= avcodec_default_get_buffer;
529 return avctx->get_buffer(avctx, pic);
532 if(avctx->has_b_frames){
533 type= MP_IMGTYPE_IPB;
534 }else{
535 type= MP_IMGTYPE_IP;
537 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
540 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
541 flags |= MP_IMGFLAG_RGB_PALETTE;
542 mpi= mpcodecs_get_image(sh, type, flags, width, height);
543 if (!mpi) return -1;
545 // ok, let's see what did we get:
546 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
547 !(mpi->flags&MP_IMGFLAG_DIRECT)){
548 // nice, filter/vo likes draw_callback :)
549 avctx->draw_horiz_band= draw_slice;
550 } else
551 avctx->draw_horiz_band= NULL;
552 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
553 avctx->draw_horiz_band= draw_slice;
555 #if CONFIG_XVMC
556 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
557 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
558 avctx->draw_horiz_band= draw_slice;
559 if(!avctx->xvmc_acceleration) {
560 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
561 assert(0);
562 exit(1);
563 // return -1;//!!fixme check error conditions in ffmpeg
565 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
566 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
567 assert(0);
568 exit(1);
569 // return -1;//!!fixme check error conditions in ffmpeg
571 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
572 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
573 assert(render != 0);
574 assert(render->xvmc_id == AV_XVMC_ID);
575 render->state |= AV_XVMC_STATE_PREDICTION;
577 #endif
579 pic->data[0]= mpi->planes[0];
580 pic->data[1]= mpi->planes[1];
581 pic->data[2]= mpi->planes[2];
583 #if 0
584 assert(mpi->width >= ((width +align)&(~align)));
585 assert(mpi->height >= ((height+align)&(~align)));
586 assert(mpi->stride[0] >= mpi->width);
587 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
588 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
589 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
591 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
592 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
593 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
594 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
595 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
596 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
598 #endif
600 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
601 * lavc will check that and die with an error message, if its not true
603 pic->linesize[0]= mpi->stride[0];
604 pic->linesize[1]= mpi->stride[1];
605 pic->linesize[2]= mpi->stride[2];
607 pic->opaque = mpi;
608 //printf("%X\n", (int)mpi->planes[0]);
609 #if 0
610 if(mpi->flags&MP_IMGFLAG_DIRECT)
611 printf("D");
612 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
613 printf("S");
614 else
615 printf(".");
616 #endif
617 if(pic->reference){
618 pic->age= ctx->ip_age[0];
620 ctx->ip_age[0]= ctx->ip_age[1]+1;
621 ctx->ip_age[1]= 1;
622 ctx->b_age++;
623 }else{
624 pic->age= ctx->b_age;
626 ctx->ip_age[0]++;
627 ctx->ip_age[1]++;
628 ctx->b_age=1;
630 pic->type= FF_BUFFER_TYPE_USER;
632 /* The libavcodec reordered_opaque functionality is implemented by
633 * a similar copy in avcodec_default_get_buffer() and without a
634 * workaround like this it'd stop working when a custom buffer
635 * callback is used.
637 pic->reordered_opaque = avctx->reordered_opaque;
638 return 0;
641 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
642 mp_image_t *mpi= pic->opaque;
643 sh_video_t *sh = avctx->opaque;
644 vd_ffmpeg_ctx *ctx = sh->context;
645 int i;
647 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
649 if(ctx->ip_count <= 2 && ctx->b_count<=1){
650 if(mpi->flags&MP_IMGFLAG_PRESERVE)
651 ctx->ip_count--;
652 else
653 ctx->b_count--;
656 if (mpi) {
657 // Palette support: free palette buffer allocated in get_buffer
658 if (mpi->bpp == 8)
659 av_freep(&mpi->planes[1]);
660 #if CONFIG_XVMC
661 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
662 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
663 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
664 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
665 assert(render!=NULL);
666 assert(render->xvmc_id == AV_XVMC_ID);
667 render->state&=~AV_XVMC_STATE_PREDICTION;
669 #endif
670 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
671 mpi->usage_count--;
674 if(pic->type!=FF_BUFFER_TYPE_USER){
675 avcodec_default_release_buffer(avctx, pic);
676 return;
679 for(i=0; i<4; i++){
680 pic->data[i]= NULL;
682 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
685 // copypaste from demux_real.c - it should match to get it working!
686 //FIXME put into some header
687 typedef struct dp_hdr_s {
688 uint32_t chunks; // number of chunks
689 uint32_t timestamp; // timestamp from packet header
690 uint32_t len; // length of actual data
691 uint32_t chunktab; // offset to chunk offset array
692 } dp_hdr_t;
694 static void swap_palette(void *pal) {
695 int i;
696 uint32_t *p = pal;
697 for (i = 0; i < AVPALETTE_COUNT; i++)
698 p[i] = le2me_32(p[i]);
701 // decode a frame
702 static struct mp_image *decode(struct sh_video *sh, void *data, int len,
703 int flags, double *reordered_pts)
705 int got_picture=0;
706 int ret;
707 vd_ffmpeg_ctx *ctx = sh->context;
708 AVFrame *pic= ctx->pic;
709 AVCodecContext *avctx = ctx->avctx;
710 struct lavc_param *lavc_param = &sh->opts->lavc_param;
711 mp_image_t *mpi=NULL;
712 int dr1= ctx->do_dr1;
713 AVPacket pkt;
715 if(len<=0) return NULL; // skipped frame
717 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
718 if (!dr1)
719 avctx->draw_horiz_band=NULL;
720 if(ctx->vo_initialized && !(flags&3) && !dr1){
721 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
722 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
723 sh->disp_w, sh->disp_h);
724 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
725 // vd core likes slices!
726 avctx->draw_horiz_band=draw_slice;
730 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
732 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
733 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
734 av_init_packet(&pkt);
735 pkt.data = data;
736 pkt.size = len;
737 // HACK: make PNGs decode normally instead of as CorePNG delta frames
738 pkt.flags = PKT_FLAG_KEY;
739 // The avcodec opaque field stupidly supports only int64_t type
740 *(double *)&avctx->reordered_opaque = *reordered_pts;
741 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
742 *reordered_pts = *(double *)&pic->reordered_opaque;
744 dr1= ctx->do_dr1;
745 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
746 //printf("repeat: %d\n", pic->repeat_pict);
747 //-- vstats generation
748 while(lavc_param->vstats){ // always one time loop
749 static FILE *fvstats=NULL;
750 char filename[20];
751 static long long int all_len=0;
752 static int frame_number=0;
753 static double all_frametime=0.0;
754 AVFrame *pic= avctx->coded_frame;
755 double quality=0.0;
757 if(!fvstats) {
758 time_t today2;
759 struct tm *today;
760 today2 = time(NULL);
761 today = localtime(&today2);
762 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
763 today->tm_min, today->tm_sec);
764 fvstats = fopen(filename, "w");
765 if(!fvstats) {
766 perror("fopen");
767 lavc_param->vstats=0; // disable block
768 break;
769 /*exit(1);*/
773 // average MB quantizer
775 int x, y;
776 int w = ((avctx->width << ctx->lowres)+15) >> 4;
777 int h = ((avctx->height << ctx->lowres)+15) >> 4;
778 int8_t *q = pic->qscale_table;
779 for(y = 0; y < h; y++) {
780 for(x = 0; x < w; x++)
781 quality += (double)*(q+x);
782 q += pic->qstride;
784 quality /= w * h;
787 all_len+=len;
788 all_frametime+=sh->frametime;
789 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
790 ++frame_number, quality, len, (double)all_len/1024);
791 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
792 all_frametime, (double)(len*8)/sh->frametime/1000.0,
793 (double)(all_len*8)/all_frametime/1000.0);
794 switch(pic->pict_type){
795 case FF_I_TYPE:
796 fprintf(fvstats, "type= I\n");
797 break;
798 case FF_P_TYPE:
799 fprintf(fvstats, "type= P\n");
800 break;
801 case FF_S_TYPE:
802 fprintf(fvstats, "type= S\n");
803 break;
804 case FF_B_TYPE:
805 fprintf(fvstats, "type= B\n");
806 break;
807 default:
808 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
809 break;
812 ctx->qp_stat[(int)(quality+0.5)]++;
813 ctx->qp_sum += quality;
814 ctx->inv_qp_sum += 1.0/(double)quality;
816 break;
818 //--
820 if(!got_picture) return NULL; // skipped image
822 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
824 if(dr1 && pic->opaque){
825 mpi= (mp_image_t *)pic->opaque;
828 if(!mpi)
829 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
830 avctx->width, avctx->height);
831 if(!mpi){ // temporary!
832 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
833 return NULL;
836 if(!dr1){
837 mpi->planes[0]=pic->data[0];
838 mpi->planes[1]=pic->data[1];
839 mpi->planes[2]=pic->data[2];
840 mpi->stride[0]=pic->linesize[0];
841 mpi->stride[1]=pic->linesize[1];
842 mpi->stride[2]=pic->linesize[2];
845 if (!mpi->planes[0])
846 return NULL;
848 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
849 // we have 422p but user wants 420p
850 mpi->stride[1]*=2;
851 mpi->stride[2]*=2;
854 #if HAVE_BIGENDIAN
855 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
856 if (mpi->bpp == 8)
857 swap_palette(mpi->planes[1]);
858 #endif
859 /* to comfirm with newer lavc style */
860 mpi->qscale =pic->qscale_table;
861 mpi->qstride=pic->qstride;
862 mpi->pict_type=pic->pict_type;
863 mpi->qscale_type= pic->qscale_type;
864 mpi->fields = MP_IMGFIELD_ORDERED;
865 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
866 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
867 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
869 return mpi;
872 #if CONFIG_XVMC || CONFIG_VDPAU
873 static enum PixelFormat get_format(struct AVCodecContext *avctx,
874 const enum PixelFormat *fmt){
875 enum PixelFormat selected_format;
876 int imgfmt;
877 sh_video_t *sh = avctx->opaque;
878 int i;
880 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
881 imgfmt = pixfmt2imgfmt(fmt[i]);
882 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
883 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
884 if(init_vo(sh, fmt[i]) >= 0) {
885 break;
888 selected_format = fmt[i];
889 set_format_params(avctx, selected_format);
890 return selected_format;
892 #endif /* CONFIG_XVMC || CONFIG_VDPAU */
894 const struct vd_functions mpcodecs_vd_ffmpeg = {
895 .info = &info,
896 .init = init,
897 .uninit = uninit,
898 .control = control,
899 .decode2 = decode