Create a set_format_params function that sets all the special options needed
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
blob64ea79c569be818d590221573c27f420bab3b43f
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 "av_opts.h"
11 #include "libavutil/common.h"
12 #include "libavutil/intreadwrite.h"
13 #include "mpbswap.h"
14 #include "fmt-conversion.h"
16 #include "vd_internal.h"
18 static 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 "libavcodec/xvmc.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 } vd_ffmpeg_ctx;
54 #include "m_option.h"
56 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
57 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
58 static void draw_slice(struct AVCodecContext *s, AVFrame *src, int offset[4],
59 int y, int type, int height);
61 static enum PixelFormat get_format(struct AVCodecContext *avctx,
62 const enum PixelFormat *pix_fmt);
64 static int lavc_param_workaround_bugs= FF_BUG_AUTODETECT;
65 static int lavc_param_error_resilience=2;
66 static int lavc_param_error_concealment=3;
67 static int lavc_param_gray=0;
68 static int lavc_param_vstats=0;
69 static int lavc_param_idct_algo=0;
70 static int lavc_param_debug=0;
71 static int lavc_param_vismv=0;
72 static int lavc_param_skip_top=0;
73 static int lavc_param_skip_bottom=0;
74 static int lavc_param_fast=0;
75 static int lavc_param_lowres=0;
76 static char *lavc_param_lowres_str=NULL;
77 static char *lavc_param_skip_loop_filter_str = NULL;
78 static char *lavc_param_skip_idct_str = NULL;
79 static char *lavc_param_skip_frame_str = NULL;
80 static int lavc_param_threads=1;
81 static int lavc_param_bitexact=0;
82 static char *lavc_avopt = NULL;
84 const m_option_t lavc_decode_opts_conf[]={
85 {"bug", &lavc_param_workaround_bugs, CONF_TYPE_INT, CONF_RANGE, -1, 999999, NULL},
86 {"er", &lavc_param_error_resilience, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
87 {"gray", &lavc_param_gray, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_PART, NULL},
88 {"idct", &lavc_param_idct_algo, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
89 {"ec", &lavc_param_error_concealment, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
90 {"vstats", &lavc_param_vstats, CONF_TYPE_FLAG, 0, 0, 1, NULL},
91 {"debug", &lavc_param_debug, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
92 {"vismv", &lavc_param_vismv, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
93 {"st", &lavc_param_skip_top, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
94 {"sb", &lavc_param_skip_bottom, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
95 {"fast", &lavc_param_fast, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG2_FAST, NULL},
96 {"lowres", &lavc_param_lowres_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
97 {"skiploopfilter", &lavc_param_skip_loop_filter_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
98 {"skipidct", &lavc_param_skip_idct_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
99 {"skipframe", &lavc_param_skip_frame_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
100 {"threads", &lavc_param_threads, CONF_TYPE_INT, CONF_RANGE, 1, 8, NULL},
101 {"bitexact", &lavc_param_bitexact, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_BITEXACT, NULL},
102 {"o", &lavc_avopt, CONF_TYPE_STRING, 0, 0, 0, NULL},
103 {NULL, NULL, 0, 0, 0, 0, NULL}
106 static enum AVDiscard str2AVDiscard(char *str) {
107 if (!str) return AVDISCARD_DEFAULT;
108 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
109 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
110 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
111 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
112 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
113 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
114 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
115 return AVDISCARD_DEFAULT;
118 // to set/get/query special features/parameters
119 static int control(sh_video_t *sh, int cmd, void *arg, ...){
120 vd_ffmpeg_ctx *ctx = sh->context;
121 AVCodecContext *avctx = ctx->avctx;
122 switch(cmd){
123 case VDCTRL_QUERY_FORMAT:
125 int format =(*((int *)arg));
126 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
127 // possible conversions:
128 switch(format){
129 case IMGFMT_YV12:
130 case IMGFMT_IYUV:
131 case IMGFMT_I420:
132 // "converted" using pointer/stride modification
133 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
134 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
135 break;
136 #if CONFIG_XVMC
137 case IMGFMT_XVMC_IDCT_MPEG2:
138 case IMGFMT_XVMC_MOCO_MPEG2:
139 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
140 #endif
142 return CONTROL_FALSE;
144 case VDCTRL_RESYNC_STREAM:
145 avcodec_flush_buffers(avctx);
146 return CONTROL_TRUE;
147 case VDCTRL_QUERY_UNSEEN_FRAMES:
148 return avctx->has_b_frames + 10;
150 return CONTROL_UNKNOWN;
153 void mp_msp_av_log_callback(void *ptr, int level, const char *fmt, va_list vl)
155 static int print_prefix=1;
156 AVClass *avc= ptr ? *(AVClass **)ptr : NULL;
157 int type= MSGT_FIXME;
158 int mp_level;
159 char buf[256];
161 switch(level){
162 case AV_LOG_DEBUG: mp_level= MSGL_V ; break;
163 case AV_LOG_INFO : mp_level= MSGL_INFO; break;
164 case AV_LOG_ERROR: mp_level= MSGL_ERR ; break;
165 default : mp_level= MSGL_ERR ; break;
168 if (!mp_msg_test(type, mp_level)) return;
170 if(ptr){
171 if(!strcmp(avc->class_name, "AVCodecContext")){
172 AVCodecContext *s= ptr;
173 if(s->codec){
174 if(s->codec->type == CODEC_TYPE_AUDIO){
175 if(s->codec->decode)
176 type= MSGT_DECAUDIO;
177 }else if(s->codec->type == CODEC_TYPE_VIDEO){
178 if(s->codec->decode)
179 type= MSGT_DECVIDEO;
181 //FIXME subtitles, encoders (what msgt for them? there is no appropriate ...)
183 }else if(!strcmp(avc->class_name, "AVFormatContext")){
184 #if 0 //needs libavformat include FIXME iam too lazy to do this cleanly, probably the whole should be moved out of this file ...
185 AVFormatContext *s= ptr;
186 if(s->iformat)
187 type= MSGT_DEMUXER;
188 else if(s->oformat)
189 type= MSGT_MUXER;
190 #endif
194 if(print_prefix && avc) {
195 mp_msg(type, mp_level, "[%s @ %p]", avc->item_name(ptr), avc);
198 print_prefix= strchr(fmt, '\n') != NULL;
199 vsnprintf(buf, sizeof(buf), fmt, vl);
200 mp_msg(type, mp_level, buf);
203 static void set_format_params(struct AVCodecContext *avctx, enum PixelFormat fmt){
204 int imgfmt;
205 imgfmt = pixfmt2imgfmt(fmt);
206 if (IMGFMT_IS_XVMC(imgfmt) || IMGFMT_IS_VDPAU(imgfmt)) {
207 sh_video_t *sh = avctx->opaque;
208 vd_ffmpeg_ctx *ctx = sh->context;
209 ctx->do_dr1 = 1;
210 ctx->do_slices = 1;
211 avctx->thread_count = 1;
212 avctx->get_buffer = get_buffer;
213 avctx->release_buffer = release_buffer;
214 avctx->reget_buffer = get_buffer;
215 avctx->draw_horiz_band = draw_slice;
216 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedMPEG2);
217 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
221 // init driver
222 static int init(sh_video_t *sh){
223 AVCodecContext *avctx;
224 vd_ffmpeg_ctx *ctx;
225 AVCodec *lavc_codec;
226 int lowres_w=0;
227 int do_vis_debug= lavc_param_vismv || (lavc_param_debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
229 if(!avcodec_initialized){
230 avcodec_init();
231 avcodec_register_all();
232 avcodec_initialized=1;
233 av_log_set_callback(mp_msp_av_log_callback);
236 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
237 if (!ctx)
238 return 0;
239 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
241 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
242 if(!lavc_codec){
243 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MissingLAVCcodec, sh->codec->dll);
244 uninit(sh);
245 return 0;
248 if(vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
249 ctx->do_slices=1;
251 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)
252 ctx->do_dr1=1;
253 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
254 ctx->ip_count= ctx->b_count= 0;
256 ctx->pic = avcodec_alloc_frame();
257 ctx->avctx = avcodec_alloc_context();
258 avctx = ctx->avctx;
259 avctx->opaque = sh;
261 #if CONFIG_VDPAU
262 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU){
263 avctx->get_format = get_format;
265 #endif /* CONFIG_VDPAU */
266 #if CONFIG_XVMC
267 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
268 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedCodec);
269 avctx->get_format= get_format;//for now only this decoder will use it
270 // HACK around badly placed checks in mpeg_mc_decode_init
271 set_format_params(avctx, PIX_FMT_XVMC_MPEG2_IDCT);
273 #endif /* CONFIG_XVMC */
274 if(ctx->do_dr1){
275 avctx->flags|= CODEC_FLAG_EMU_EDGE;
276 avctx->get_buffer= get_buffer;
277 avctx->release_buffer= release_buffer;
278 avctx->reget_buffer= get_buffer;
281 avctx->flags|= lavc_param_bitexact;
283 avctx->width = sh->disp_w;
284 avctx->height= sh->disp_h;
285 avctx->workaround_bugs= lavc_param_workaround_bugs;
286 avctx->error_recognition= lavc_param_error_resilience;
287 if(lavc_param_gray) avctx->flags|= CODEC_FLAG_GRAY;
288 avctx->flags2|= lavc_param_fast;
289 avctx->codec_tag= sh->format;
290 avctx->stream_codec_tag= sh->video.fccHandler;
291 avctx->idct_algo= lavc_param_idct_algo;
292 avctx->error_concealment= lavc_param_error_concealment;
293 avctx->debug= lavc_param_debug;
294 if (lavc_param_debug)
295 av_log_set_level(AV_LOG_DEBUG);
296 avctx->debug_mv= lavc_param_vismv;
297 avctx->skip_top = lavc_param_skip_top;
298 avctx->skip_bottom= lavc_param_skip_bottom;
299 if(lavc_param_lowres_str != NULL)
301 sscanf(lavc_param_lowres_str, "%d,%d", &lavc_param_lowres, &lowres_w);
302 if(lavc_param_lowres < 1 || lavc_param_lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
303 lavc_param_lowres = 0;
304 avctx->lowres = lavc_param_lowres;
306 avctx->skip_loop_filter = str2AVDiscard(lavc_param_skip_loop_filter_str);
307 avctx->skip_idct = str2AVDiscard(lavc_param_skip_idct_str);
308 avctx->skip_frame = str2AVDiscard(lavc_param_skip_frame_str);
310 if(lavc_avopt){
311 if(parse_avopts(avctx, lavc_avopt) < 0){
312 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_avopt);
313 uninit(sh);
314 return 0;
318 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
319 switch (sh->format) {
320 case mmioFOURCC('S','V','Q','3'):
321 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
322 in the phony AVI header if demux_lavf is used. The first case is
323 handled here; the second case falls through to the next section. */
324 if (sh->ImageDesc) {
325 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
326 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
327 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
328 break;
330 /* fallthrough */
332 case mmioFOURCC('A','V','R','n'):
333 case mmioFOURCC('M','J','P','G'):
334 /* AVRn stores huffman table in AVI header */
335 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
336 MJPG fourcc :( */
337 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
338 break;
339 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
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 #if 0
346 int x;
347 uint8_t *p = avctx->extradata;
349 for (x=0; x<avctx->extradata_size; x++)
350 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
351 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
353 #endif
354 break;
356 case mmioFOURCC('R', 'V', '1', '0'):
357 case mmioFOURCC('R', 'V', '1', '3'):
358 case mmioFOURCC('R', 'V', '2', '0'):
359 case mmioFOURCC('R', 'V', '3', '0'):
360 case mmioFOURCC('R', 'V', '4', '0'):
361 if(sh->bih->biSize<sizeof(*sh->bih)+8){
362 /* only 1 packet per frame & sub_id from fourcc */
363 avctx->extradata_size= 8;
364 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
365 ((uint32_t *)avctx->extradata)[0] = 0;
366 ((uint32_t *)avctx->extradata)[1] =
367 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
368 } else {
369 /* has extra slice header (demux_rm or rm->avi streamcopy) */
370 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
371 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
372 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
374 avctx->sub_id= AV_RB32(avctx->extradata+4);
376 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
377 break;
379 default:
380 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
381 break;
382 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
383 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
384 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
385 break;
387 /* Pass palette to codec */
388 if (sh->bih && (sh->bih->biBitCount <= 8)) {
389 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
390 avctx->palctrl->palette_changed = 1;
391 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
392 /* Palette size in biSize */
393 memcpy(avctx->palctrl->palette, sh->bih+1,
394 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
395 else
396 /* Palette size in biClrUsed */
397 memcpy(avctx->palctrl->palette, sh->bih+1,
398 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
401 if(sh->bih)
402 avctx->bits_per_coded_sample= sh->bih->biBitCount;
404 if(lavc_param_threads > 1)
405 avcodec_thread_init(avctx, lavc_param_threads);
406 /* open it */
407 if (avcodec_open(avctx, lavc_codec) < 0) {
408 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_CantOpenCodec);
409 uninit(sh);
410 return 0;
412 // this is necessary in case get_format was never called
413 set_format_params(avctx, avctx->pix_fmt);
414 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
415 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
418 // uninit driver
419 static void uninit(sh_video_t *sh){
420 vd_ffmpeg_ctx *ctx = sh->context;
421 AVCodecContext *avctx = ctx->avctx;
423 if(lavc_param_vstats){
424 int i;
425 for(i=1; i<32; i++){
426 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
428 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_ArithmeticMeanOfQP,
429 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
430 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
434 if (avctx) {
435 if (avctx->codec && avcodec_close(avctx) < 0)
436 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_CantCloseCodec);
438 av_freep(&avctx->extradata);
439 av_freep(&avctx->palctrl);
440 av_freep(&avctx->slice_offset);
443 av_freep(&avctx);
444 av_freep(&ctx->pic);
445 if (ctx)
446 free(ctx);
449 static void draw_slice(struct AVCodecContext *s,
450 AVFrame *src, int offset[4],
451 int y, int type, int height){
452 sh_video_t *sh = s->opaque;
453 uint8_t *source[3]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
454 #if 0
455 int start=0, i;
456 int width= s->width;
457 int skip_stride= ((width<<lavc_param_lowres)+15)>>4;
458 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
459 int threshold= s->coded_frame->age;
460 if(s->pict_type!=B_TYPE){
461 for(i=0; i*16<width+16; i++){
462 if(i*16>=width || skip[i]>=threshold){
463 if(start==i) start++;
464 else{
465 uint8_t *src2[3]= {src[0] + start*16,
466 src[1] + start*8,
467 src[2] + start*8};
468 //printf("%2d-%2d x %d\n", start, i, y);
469 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
470 start= i+1;
474 }else
475 #endif
476 if (y < sh->disp_h) {
477 mpcodecs_draw_slice (sh, source, src->linesize, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
482 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
483 vd_ffmpeg_ctx *ctx = sh->context;
484 AVCodecContext *avctx = ctx->avctx;
485 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
486 int width, height;
488 width = avctx->width;
489 height = avctx->height;
491 // HACK!
492 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
493 // use dimensions from BIH to avoid black borders at the right and bottom.
494 if (sh->bih && sh->ImageDesc) {
495 width = sh->bih->biWidth>>lavc_param_lowres;
496 height = sh->bih->biHeight>>lavc_param_lowres;
499 // it is possible another vo buffers to be used after vo config()
500 // lavc reset its buffers on width/heigh change but not on aspect change!!!
501 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
502 width != sh->disp_w ||
503 height != sh->disp_h ||
504 pix_fmt != ctx->pix_fmt ||
505 !ctx->vo_initialized)
507 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
508 if (sh->aspect == 0 ||
509 av_cmp_q(avctx->sample_aspect_ratio,
510 ctx->last_sample_aspect_ratio))
511 sh->aspect = aspect;
512 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
513 sh->disp_w = width;
514 sh->disp_h = height;
515 ctx->pix_fmt = pix_fmt;
516 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
517 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
518 return -1;
519 ctx->vo_initialized = 1;
521 return 0;
524 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
525 sh_video_t *sh = avctx->opaque;
526 vd_ffmpeg_ctx *ctx = sh->context;
527 mp_image_t *mpi=NULL;
528 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
529 int type= MP_IMGTYPE_IPB;
530 int width= avctx->width;
531 int height= avctx->height;
532 int align=15;
533 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
534 if(avctx->pix_fmt == PIX_FMT_YUV410P)
535 align=63; //yes seriously, its really needed (16x16 chroma blocks in SVQ1 -> 64x64)
537 if (pic->buffer_hints) {
538 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
539 type = MP_IMGTYPE_TEMP;
540 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
541 flags |= MP_IMGFLAG_READABLE;
542 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
543 type = MP_IMGTYPE_STATIC;
544 flags |= MP_IMGFLAG_PRESERVE;
546 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
547 type = MP_IMGTYPE_STATIC;
548 flags |= MP_IMGFLAG_PRESERVE;
550 flags|=(!avctx->hurry_up && ctx->do_slices) ?
551 MP_IMGFLAG_DRAW_CALLBACK:0;
552 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
553 } else {
554 if(!pic->reference){
555 ctx->b_count++;
556 flags|=(!avctx->hurry_up && ctx->do_slices) ?
557 MP_IMGFLAG_DRAW_CALLBACK:0;
558 }else{
559 ctx->ip_count++;
560 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
561 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
565 if(init_vo(sh, avctx->pix_fmt) < 0){
566 avctx->release_buffer= avcodec_default_release_buffer;
567 avctx->get_buffer= avcodec_default_get_buffer;
568 return avctx->get_buffer(avctx, pic);
571 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
572 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
573 } else
574 if (!pic->buffer_hints) {
575 if(ctx->b_count>1 || ctx->ip_count>2){
576 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_DRIFailure);
578 ctx->do_dr1=0; //FIXME
579 avctx->get_buffer= avcodec_default_get_buffer;
580 return avctx->get_buffer(avctx, pic);
583 if(avctx->has_b_frames){
584 type= MP_IMGTYPE_IPB;
585 }else{
586 type= MP_IMGTYPE_IP;
588 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
591 mpi= mpcodecs_get_image(sh, type, flags,
592 (width+align)&(~align), (height+align)&(~align));
593 if (!mpi) return -1;
595 // ok, let's see what did we get:
596 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
597 !(mpi->flags&MP_IMGFLAG_DIRECT)){
598 // nice, filter/vo likes draw_callback :)
599 avctx->draw_horiz_band= draw_slice;
600 } else
601 avctx->draw_horiz_band= NULL;
602 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
603 avctx->draw_horiz_band= draw_slice;
605 #if CONFIG_XVMC
606 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
607 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
608 avctx->draw_horiz_band= draw_slice;
609 if(!avctx->xvmc_acceleration) {
610 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_McGetBufferShouldWorkOnlyWithXVMC);
611 assert(0);
612 exit(1);
613 // return -1;//!!fixme check error conditions in ffmpeg
615 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
616 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_OnlyBuffersAllocatedByVoXvmcAllowed);
617 assert(0);
618 exit(1);
619 // return -1;//!!fixme check error conditions in ffmpeg
621 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
622 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
623 assert(render != 0);
624 assert(render->xvmc_id == AV_XVMC_ID);
625 render->state |= AV_XVMC_STATE_PREDICTION;
627 #endif
629 // Palette support: libavcodec copies palette to *data[1]
630 if (mpi->bpp == 8)
631 mpi->planes[1] = av_malloc(AVPALETTE_SIZE);
633 pic->data[0]= mpi->planes[0];
634 pic->data[1]= mpi->planes[1];
635 pic->data[2]= mpi->planes[2];
637 #if 0
638 assert(mpi->width >= ((width +align)&(~align)));
639 assert(mpi->height >= ((height+align)&(~align)));
640 assert(mpi->stride[0] >= mpi->width);
641 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
642 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
643 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
645 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
646 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
647 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
648 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
649 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
650 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
652 #endif
654 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
655 * lavc will check that and die with an error message, if its not true
657 pic->linesize[0]= mpi->stride[0];
658 pic->linesize[1]= mpi->stride[1];
659 pic->linesize[2]= mpi->stride[2];
661 pic->opaque = mpi;
662 //printf("%X\n", (int)mpi->planes[0]);
663 #if 0
664 if(mpi->flags&MP_IMGFLAG_DIRECT)
665 printf("D");
666 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
667 printf("S");
668 else
669 printf(".");
670 #endif
671 if(pic->reference){
672 pic->age= ctx->ip_age[0];
674 ctx->ip_age[0]= ctx->ip_age[1]+1;
675 ctx->ip_age[1]= 1;
676 ctx->b_age++;
677 }else{
678 pic->age= ctx->b_age;
680 ctx->ip_age[0]++;
681 ctx->ip_age[1]++;
682 ctx->b_age=1;
684 pic->type= FF_BUFFER_TYPE_USER;
685 return 0;
688 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
689 mp_image_t *mpi= pic->opaque;
690 sh_video_t *sh = avctx->opaque;
691 vd_ffmpeg_ctx *ctx = sh->context;
692 int i;
694 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
696 if(ctx->ip_count <= 2 && ctx->b_count<=1){
697 if(mpi->flags&MP_IMGFLAG_PRESERVE)
698 ctx->ip_count--;
699 else
700 ctx->b_count--;
703 if (mpi) {
704 // Palette support: free palette buffer allocated in get_buffer
705 if (mpi->bpp == 8)
706 av_freep(&mpi->planes[1]);
707 #if CONFIG_XVMC
708 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
709 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
710 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
711 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
712 assert(render!=NULL);
713 assert(render->xvmc_id == AV_XVMC_ID);
714 render->state&=~AV_XVMC_STATE_PREDICTION;
716 #endif
717 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
718 mpi->flags &= ~MP_IMGFLAG_IN_USE;
721 if(pic->type!=FF_BUFFER_TYPE_USER){
722 avcodec_default_release_buffer(avctx, pic);
723 return;
726 for(i=0; i<4; i++){
727 pic->data[i]= NULL;
729 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
732 // copypaste from demux_real.c - it should match to get it working!
733 //FIXME put into some header
734 typedef struct dp_hdr_s {
735 uint32_t chunks; // number of chunks
736 uint32_t timestamp; // timestamp from packet header
737 uint32_t len; // length of actual data
738 uint32_t chunktab; // offset to chunk offset array
739 } dp_hdr_t;
741 void swap_palette(void *pal) {
742 int i;
743 uint32_t *p = pal;
744 for (i = 0; i < AVPALETTE_COUNT; i++)
745 p[i] = le2me_32(p[i]);
748 // decode a frame
749 static mp_image_t *decode(sh_video_t *sh, void *data, int len, int flags){
750 int got_picture=0;
751 int ret;
752 vd_ffmpeg_ctx *ctx = sh->context;
753 AVFrame *pic= ctx->pic;
754 AVCodecContext *avctx = ctx->avctx;
755 mp_image_t *mpi=NULL;
756 int dr1= ctx->do_dr1;
758 if(len<=0) return NULL; // skipped frame
760 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
761 if (!dr1)
762 avctx->draw_horiz_band=NULL;
763 if(ctx->vo_initialized && !(flags&3) && !dr1){
764 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
765 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
766 sh->disp_w, sh->disp_h);
767 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
768 // vd core likes slices!
769 avctx->draw_horiz_band=draw_slice;
773 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
775 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
776 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
777 ret = avcodec_decode_video(avctx, pic,
778 &got_picture, data, len);
780 dr1= ctx->do_dr1;
781 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
782 //printf("repeat: %d\n", pic->repeat_pict);
783 //-- vstats generation
784 while(lavc_param_vstats){ // always one time loop
785 static FILE *fvstats=NULL;
786 char filename[20];
787 static long long int all_len=0;
788 static int frame_number=0;
789 static double all_frametime=0.0;
790 AVFrame *pic= avctx->coded_frame;
791 double quality=0.0;
793 if(!fvstats) {
794 time_t today2;
795 struct tm *today;
796 today2 = time(NULL);
797 today = localtime(&today2);
798 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
799 today->tm_min, today->tm_sec);
800 fvstats = fopen(filename, "w");
801 if(!fvstats) {
802 perror("fopen");
803 lavc_param_vstats=0; // disable block
804 break;
805 /*exit(1);*/
809 // average MB quantizer
811 int x, y;
812 int w = ((avctx->width << lavc_param_lowres)+15) >> 4;
813 int h = ((avctx->height << lavc_param_lowres)+15) >> 4;
814 int8_t *q = pic->qscale_table;
815 for(y = 0; y < h; y++) {
816 for(x = 0; x < w; x++)
817 quality += (double)*(q+x);
818 q += pic->qstride;
820 quality /= w * h;
823 all_len+=len;
824 all_frametime+=sh->frametime;
825 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
826 ++frame_number, quality, len, (double)all_len/1024);
827 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
828 all_frametime, (double)(len*8)/sh->frametime/1000.0,
829 (double)(all_len*8)/all_frametime/1000.0);
830 switch(pic->pict_type){
831 case FF_I_TYPE:
832 fprintf(fvstats, "type= I\n");
833 break;
834 case FF_P_TYPE:
835 fprintf(fvstats, "type= P\n");
836 break;
837 case FF_S_TYPE:
838 fprintf(fvstats, "type= S\n");
839 break;
840 case FF_B_TYPE:
841 fprintf(fvstats, "type= B\n");
842 break;
843 default:
844 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
845 break;
848 ctx->qp_stat[(int)(quality+0.5)]++;
849 ctx->qp_sum += quality;
850 ctx->inv_qp_sum += 1.0/(double)quality;
852 break;
854 //--
856 if(!got_picture) return NULL; // skipped image
858 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
860 if(dr1 && pic->opaque){
861 mpi= (mp_image_t *)pic->opaque;
864 if(!mpi)
865 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
866 avctx->width, avctx->height);
867 if(!mpi){ // temporary!
868 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_CouldntAllocateImageForCodec);
869 return NULL;
872 if(!dr1){
873 mpi->planes[0]=pic->data[0];
874 mpi->planes[1]=pic->data[1];
875 mpi->planes[2]=pic->data[2];
876 mpi->stride[0]=pic->linesize[0];
877 mpi->stride[1]=pic->linesize[1];
878 mpi->stride[2]=pic->linesize[2];
881 if (!mpi->planes[0])
882 return NULL;
884 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
885 // we have 422p but user wants 420p
886 mpi->stride[1]*=2;
887 mpi->stride[2]*=2;
890 #ifdef WORDS_BIGENDIAN
891 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
892 if (mpi->bpp == 8)
893 swap_palette(mpi->planes[1]);
894 #endif
895 /* to comfirm with newer lavc style */
896 mpi->qscale =pic->qscale_table;
897 mpi->qstride=pic->qstride;
898 mpi->pict_type=pic->pict_type;
899 mpi->qscale_type= pic->qscale_type;
900 mpi->fields = MP_IMGFIELD_ORDERED;
901 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
902 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
903 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
905 return mpi;
908 #if CONFIG_XVMC || CONFIG_VDPAU
909 static enum PixelFormat get_format(struct AVCodecContext *avctx,
910 const enum PixelFormat *fmt){
911 enum PixelFormat selected_format;
912 int imgfmt;
913 sh_video_t *sh = avctx->opaque;
914 int i;
916 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
917 imgfmt = pixfmt2imgfmt(fmt[i]);
918 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
919 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_TryingPixfmt, i);
920 if(init_vo(sh, fmt[i]) >= 0) {
921 break;
924 selected_format = fmt[i];
925 set_format_params(avctx, selected_format);
926 return selected_format;
928 #endif /* CONFIG_XVMC || CONFIG_VDPAU */