20% faster hqdn3d on x86_64
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
blob244e6495b39e14ec2c5187b823b86ede88a476a0
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 and init_vo is
413 // too late e.g. for H.264 VDPAU
414 set_format_params(avctx, avctx->pix_fmt);
415 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
416 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
419 // uninit driver
420 static void uninit(sh_video_t *sh){
421 vd_ffmpeg_ctx *ctx = sh->context;
422 AVCodecContext *avctx = ctx->avctx;
424 if(lavc_param_vstats){
425 int i;
426 for(i=1; i<32; i++){
427 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
429 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_ArithmeticMeanOfQP,
430 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
431 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
435 if (avctx) {
436 if (avctx->codec && avcodec_close(avctx) < 0)
437 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_CantCloseCodec);
439 av_freep(&avctx->extradata);
440 av_freep(&avctx->palctrl);
441 av_freep(&avctx->slice_offset);
444 av_freep(&avctx);
445 av_freep(&ctx->pic);
446 if (ctx)
447 free(ctx);
450 static void draw_slice(struct AVCodecContext *s,
451 AVFrame *src, int offset[4],
452 int y, int type, int height){
453 sh_video_t *sh = s->opaque;
454 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
455 #if 0
456 int start=0, i;
457 int width= s->width;
458 int skip_stride= ((width<<lavc_param_lowres)+15)>>4;
459 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
460 int threshold= s->coded_frame->age;
461 if(s->pict_type!=B_TYPE){
462 for(i=0; i*16<width+16; i++){
463 if(i*16>=width || skip[i]>=threshold){
464 if(start==i) start++;
465 else{
466 uint8_t *src2[3]= {src[0] + start*16,
467 src[1] + start*8,
468 src[2] + start*8};
469 //printf("%2d-%2d x %d\n", start, i, y);
470 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
471 start= i+1;
475 }else
476 #endif
477 if (y < sh->disp_h) {
478 mpcodecs_draw_slice (sh, source, src->linesize, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
483 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
484 vd_ffmpeg_ctx *ctx = sh->context;
485 AVCodecContext *avctx = ctx->avctx;
486 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
487 int width, height;
489 width = avctx->width;
490 height = avctx->height;
492 // HACK!
493 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
494 // use dimensions from BIH to avoid black borders at the right and bottom.
495 if (sh->bih && sh->ImageDesc) {
496 width = sh->bih->biWidth>>lavc_param_lowres;
497 height = sh->bih->biHeight>>lavc_param_lowres;
500 // it is possible another vo buffers to be used after vo config()
501 // lavc reset its buffers on width/heigh change but not on aspect change!!!
502 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
503 width != sh->disp_w ||
504 height != sh->disp_h ||
505 pix_fmt != ctx->pix_fmt ||
506 !ctx->vo_initialized)
508 // this is a special-case HACK for MPEG-1/2 VDPAU that uses neither get_format nor
509 // sets the value correctly in avcodec_open.
510 set_format_params(avctx, avctx->pix_fmt);
511 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
512 if (sh->aspect == 0 ||
513 av_cmp_q(avctx->sample_aspect_ratio,
514 ctx->last_sample_aspect_ratio))
515 sh->aspect = aspect;
516 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
517 sh->disp_w = width;
518 sh->disp_h = height;
519 ctx->pix_fmt = pix_fmt;
520 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
521 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
522 return -1;
523 ctx->vo_initialized = 1;
525 return 0;
528 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
529 sh_video_t *sh = avctx->opaque;
530 vd_ffmpeg_ctx *ctx = sh->context;
531 mp_image_t *mpi=NULL;
532 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
533 int type= MP_IMGTYPE_IPB;
534 int width= avctx->width;
535 int height= avctx->height;
536 int align=15;
537 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
538 if(avctx->pix_fmt == PIX_FMT_YUV410P)
539 align=63; //yes seriously, its really needed (16x16 chroma blocks in SVQ1 -> 64x64)
541 if (pic->buffer_hints) {
542 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
543 type = MP_IMGTYPE_TEMP;
544 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
545 flags |= MP_IMGFLAG_READABLE;
546 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
547 type = MP_IMGTYPE_STATIC;
548 flags |= MP_IMGFLAG_PRESERVE;
550 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
551 type = MP_IMGTYPE_STATIC;
552 flags |= MP_IMGFLAG_PRESERVE;
554 flags|=(!avctx->hurry_up && ctx->do_slices) ?
555 MP_IMGFLAG_DRAW_CALLBACK:0;
556 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
557 } else {
558 if(!pic->reference){
559 ctx->b_count++;
560 flags|=(!avctx->hurry_up && ctx->do_slices) ?
561 MP_IMGFLAG_DRAW_CALLBACK:0;
562 }else{
563 ctx->ip_count++;
564 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
565 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
569 if(init_vo(sh, avctx->pix_fmt) < 0){
570 avctx->release_buffer= avcodec_default_release_buffer;
571 avctx->get_buffer= avcodec_default_get_buffer;
572 return avctx->get_buffer(avctx, pic);
575 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
576 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
577 } else
578 if (!pic->buffer_hints) {
579 if(ctx->b_count>1 || ctx->ip_count>2){
580 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_DRIFailure);
582 ctx->do_dr1=0; //FIXME
583 avctx->get_buffer= avcodec_default_get_buffer;
584 return avctx->get_buffer(avctx, pic);
587 if(avctx->has_b_frames){
588 type= MP_IMGTYPE_IPB;
589 }else{
590 type= MP_IMGTYPE_IP;
592 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
595 mpi= mpcodecs_get_image(sh, type, flags,
596 (width+align)&(~align), (height+align)&(~align));
597 if (!mpi) return -1;
599 // ok, let's see what did we get:
600 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
601 !(mpi->flags&MP_IMGFLAG_DIRECT)){
602 // nice, filter/vo likes draw_callback :)
603 avctx->draw_horiz_band= draw_slice;
604 } else
605 avctx->draw_horiz_band= NULL;
606 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
607 avctx->draw_horiz_band= draw_slice;
609 #if CONFIG_XVMC
610 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
611 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
612 avctx->draw_horiz_band= draw_slice;
613 if(!avctx->xvmc_acceleration) {
614 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_McGetBufferShouldWorkOnlyWithXVMC);
615 assert(0);
616 exit(1);
617 // return -1;//!!fixme check error conditions in ffmpeg
619 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
620 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_OnlyBuffersAllocatedByVoXvmcAllowed);
621 assert(0);
622 exit(1);
623 // return -1;//!!fixme check error conditions in ffmpeg
625 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
626 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
627 assert(render != 0);
628 assert(render->xvmc_id == AV_XVMC_ID);
629 render->state |= AV_XVMC_STATE_PREDICTION;
631 #endif
633 // Palette support: libavcodec copies palette to *data[1]
634 if (mpi->bpp == 8)
635 mpi->planes[1] = av_malloc(AVPALETTE_SIZE);
637 pic->data[0]= mpi->planes[0];
638 pic->data[1]= mpi->planes[1];
639 pic->data[2]= mpi->planes[2];
641 #if 0
642 assert(mpi->width >= ((width +align)&(~align)));
643 assert(mpi->height >= ((height+align)&(~align)));
644 assert(mpi->stride[0] >= mpi->width);
645 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
646 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
647 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
649 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
650 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
651 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
652 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
653 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
654 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
656 #endif
658 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
659 * lavc will check that and die with an error message, if its not true
661 pic->linesize[0]= mpi->stride[0];
662 pic->linesize[1]= mpi->stride[1];
663 pic->linesize[2]= mpi->stride[2];
665 pic->opaque = mpi;
666 //printf("%X\n", (int)mpi->planes[0]);
667 #if 0
668 if(mpi->flags&MP_IMGFLAG_DIRECT)
669 printf("D");
670 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
671 printf("S");
672 else
673 printf(".");
674 #endif
675 if(pic->reference){
676 pic->age= ctx->ip_age[0];
678 ctx->ip_age[0]= ctx->ip_age[1]+1;
679 ctx->ip_age[1]= 1;
680 ctx->b_age++;
681 }else{
682 pic->age= ctx->b_age;
684 ctx->ip_age[0]++;
685 ctx->ip_age[1]++;
686 ctx->b_age=1;
688 pic->type= FF_BUFFER_TYPE_USER;
689 return 0;
692 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
693 mp_image_t *mpi= pic->opaque;
694 sh_video_t *sh = avctx->opaque;
695 vd_ffmpeg_ctx *ctx = sh->context;
696 int i;
698 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
700 if(ctx->ip_count <= 2 && ctx->b_count<=1){
701 if(mpi->flags&MP_IMGFLAG_PRESERVE)
702 ctx->ip_count--;
703 else
704 ctx->b_count--;
707 if (mpi) {
708 // Palette support: free palette buffer allocated in get_buffer
709 if (mpi->bpp == 8)
710 av_freep(&mpi->planes[1]);
711 #if CONFIG_XVMC
712 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
713 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
714 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
715 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
716 assert(render!=NULL);
717 assert(render->xvmc_id == AV_XVMC_ID);
718 render->state&=~AV_XVMC_STATE_PREDICTION;
720 #endif
721 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
722 mpi->usage_count--;
725 if(pic->type!=FF_BUFFER_TYPE_USER){
726 avcodec_default_release_buffer(avctx, pic);
727 return;
730 for(i=0; i<4; i++){
731 pic->data[i]= NULL;
733 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
736 // copypaste from demux_real.c - it should match to get it working!
737 //FIXME put into some header
738 typedef struct dp_hdr_s {
739 uint32_t chunks; // number of chunks
740 uint32_t timestamp; // timestamp from packet header
741 uint32_t len; // length of actual data
742 uint32_t chunktab; // offset to chunk offset array
743 } dp_hdr_t;
745 void swap_palette(void *pal) {
746 int i;
747 uint32_t *p = pal;
748 for (i = 0; i < AVPALETTE_COUNT; i++)
749 p[i] = le2me_32(p[i]);
752 // decode a frame
753 static mp_image_t *decode(sh_video_t *sh, void *data, int len, int flags){
754 int got_picture=0;
755 int ret;
756 vd_ffmpeg_ctx *ctx = sh->context;
757 AVFrame *pic= ctx->pic;
758 AVCodecContext *avctx = ctx->avctx;
759 mp_image_t *mpi=NULL;
760 int dr1= ctx->do_dr1;
761 AVPacket pkt;
763 if(len<=0) return NULL; // skipped frame
765 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
766 if (!dr1)
767 avctx->draw_horiz_band=NULL;
768 if(ctx->vo_initialized && !(flags&3) && !dr1){
769 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
770 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
771 sh->disp_w, sh->disp_h);
772 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
773 // vd core likes slices!
774 avctx->draw_horiz_band=draw_slice;
778 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
780 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
781 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
782 av_init_packet(&pkt);
783 pkt.data = data;
784 pkt.size = len;
785 // HACK: make PNGs decode normally instead of as CorePNG delta frames
786 pkt.flags = PKT_FLAG_KEY;
787 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
789 dr1= ctx->do_dr1;
790 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
791 //printf("repeat: %d\n", pic->repeat_pict);
792 //-- vstats generation
793 while(lavc_param_vstats){ // always one time loop
794 static FILE *fvstats=NULL;
795 char filename[20];
796 static long long int all_len=0;
797 static int frame_number=0;
798 static double all_frametime=0.0;
799 AVFrame *pic= avctx->coded_frame;
800 double quality=0.0;
802 if(!fvstats) {
803 time_t today2;
804 struct tm *today;
805 today2 = time(NULL);
806 today = localtime(&today2);
807 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
808 today->tm_min, today->tm_sec);
809 fvstats = fopen(filename, "w");
810 if(!fvstats) {
811 perror("fopen");
812 lavc_param_vstats=0; // disable block
813 break;
814 /*exit(1);*/
818 // average MB quantizer
820 int x, y;
821 int w = ((avctx->width << lavc_param_lowres)+15) >> 4;
822 int h = ((avctx->height << lavc_param_lowres)+15) >> 4;
823 int8_t *q = pic->qscale_table;
824 for(y = 0; y < h; y++) {
825 for(x = 0; x < w; x++)
826 quality += (double)*(q+x);
827 q += pic->qstride;
829 quality /= w * h;
832 all_len+=len;
833 all_frametime+=sh->frametime;
834 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
835 ++frame_number, quality, len, (double)all_len/1024);
836 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
837 all_frametime, (double)(len*8)/sh->frametime/1000.0,
838 (double)(all_len*8)/all_frametime/1000.0);
839 switch(pic->pict_type){
840 case FF_I_TYPE:
841 fprintf(fvstats, "type= I\n");
842 break;
843 case FF_P_TYPE:
844 fprintf(fvstats, "type= P\n");
845 break;
846 case FF_S_TYPE:
847 fprintf(fvstats, "type= S\n");
848 break;
849 case FF_B_TYPE:
850 fprintf(fvstats, "type= B\n");
851 break;
852 default:
853 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
854 break;
857 ctx->qp_stat[(int)(quality+0.5)]++;
858 ctx->qp_sum += quality;
859 ctx->inv_qp_sum += 1.0/(double)quality;
861 break;
863 //--
865 if(!got_picture) return NULL; // skipped image
867 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
869 if(dr1 && pic->opaque){
870 mpi= (mp_image_t *)pic->opaque;
873 if(!mpi)
874 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
875 avctx->width, avctx->height);
876 if(!mpi){ // temporary!
877 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_CouldntAllocateImageForCodec);
878 return NULL;
881 if(!dr1){
882 mpi->planes[0]=pic->data[0];
883 mpi->planes[1]=pic->data[1];
884 mpi->planes[2]=pic->data[2];
885 mpi->stride[0]=pic->linesize[0];
886 mpi->stride[1]=pic->linesize[1];
887 mpi->stride[2]=pic->linesize[2];
890 if (!mpi->planes[0])
891 return NULL;
893 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
894 // we have 422p but user wants 420p
895 mpi->stride[1]*=2;
896 mpi->stride[2]*=2;
899 #ifdef WORDS_BIGENDIAN
900 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
901 if (mpi->bpp == 8)
902 swap_palette(mpi->planes[1]);
903 #endif
904 /* to comfirm with newer lavc style */
905 mpi->qscale =pic->qscale_table;
906 mpi->qstride=pic->qstride;
907 mpi->pict_type=pic->pict_type;
908 mpi->qscale_type= pic->qscale_type;
909 mpi->fields = MP_IMGFIELD_ORDERED;
910 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
911 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
912 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
914 return mpi;
917 #if CONFIG_XVMC || CONFIG_VDPAU
918 static enum PixelFormat get_format(struct AVCodecContext *avctx,
919 const enum PixelFormat *fmt){
920 enum PixelFormat selected_format;
921 int imgfmt;
922 sh_video_t *sh = avctx->opaque;
923 int i;
925 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
926 imgfmt = pixfmt2imgfmt(fmt[i]);
927 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
928 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_TryingPixfmt, i);
929 if(init_vo(sh, fmt[i]) >= 0) {
930 break;
933 selected_format = fmt[i];
934 set_format_params(avctx, selected_format);
935 return selected_format;
937 #endif /* CONFIG_XVMC || CONFIG_VDPAU */