sync with en/mplayer.1 rev. 30936
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
bloba54254b80b26227503a90ef4b971147c71449c4a
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <assert.h>
22 #include <time.h>
24 #include "config.h"
25 #include "mp_msg.h"
26 #include "help_mp.h"
27 #include "av_opts.h"
29 #include "libavutil/common.h"
30 #include "libavutil/intreadwrite.h"
31 #include "mpbswap.h"
32 #include "fmt-conversion.h"
34 #include "vd_internal.h"
36 static const vd_info_t info = {
37 "FFmpeg's libavcodec codec family",
38 "ffmpeg",
39 "A'rpi",
40 "A'rpi, Michael, Alex",
41 "native codecs"
44 LIBVD_EXTERN(ffmpeg)
46 #include "libavcodec/avcodec.h"
48 #if AVPALETTE_SIZE > 1024
49 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
50 #endif
52 #if CONFIG_XVMC
53 #include "libavcodec/xvmc.h"
54 #endif
56 int avcodec_initialized=0;
58 typedef struct {
59 AVCodecContext *avctx;
60 AVFrame *pic;
61 enum PixelFormat pix_fmt;
62 int do_slices;
63 int do_dr1;
64 int vo_initialized;
65 int best_csp;
66 int b_age;
67 int ip_age[2];
68 int qp_stat[32];
69 double qp_sum;
70 double inv_qp_sum;
71 int ip_count;
72 int b_count;
73 AVRational last_sample_aspect_ratio;
74 } vd_ffmpeg_ctx;
76 #include "m_option.h"
78 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
79 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
80 static void draw_slice(struct AVCodecContext *s, const AVFrame *src, int offset[4],
81 int y, int type, int height);
83 static enum PixelFormat get_format(struct AVCodecContext *avctx,
84 const enum PixelFormat *pix_fmt);
86 static int lavc_param_workaround_bugs= FF_BUG_AUTODETECT;
87 static int lavc_param_error_resilience=2;
88 static int lavc_param_error_concealment=3;
89 static int lavc_param_gray=0;
90 static int lavc_param_vstats=0;
91 static int lavc_param_idct_algo=0;
92 static int lavc_param_debug=0;
93 static int lavc_param_vismv=0;
94 static int lavc_param_skip_top=0;
95 static int lavc_param_skip_bottom=0;
96 static int lavc_param_fast=0;
97 static int lavc_param_lowres=0;
98 static char *lavc_param_lowres_str=NULL;
99 static char *lavc_param_skip_loop_filter_str = NULL;
100 static char *lavc_param_skip_idct_str = NULL;
101 static char *lavc_param_skip_frame_str = NULL;
102 static int lavc_param_threads=1;
103 static int lavc_param_bitexact=0;
104 static char *lavc_avopt = NULL;
106 const m_option_t lavc_decode_opts_conf[]={
107 {"bug", &lavc_param_workaround_bugs, CONF_TYPE_INT, CONF_RANGE, -1, 999999, NULL},
108 {"er", &lavc_param_error_resilience, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
109 {"gray", &lavc_param_gray, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_PART, NULL},
110 {"idct", &lavc_param_idct_algo, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
111 {"ec", &lavc_param_error_concealment, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
112 {"vstats", &lavc_param_vstats, CONF_TYPE_FLAG, 0, 0, 1, NULL},
113 {"debug", &lavc_param_debug, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
114 {"vismv", &lavc_param_vismv, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
115 {"st", &lavc_param_skip_top, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
116 {"sb", &lavc_param_skip_bottom, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
117 {"fast", &lavc_param_fast, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG2_FAST, NULL},
118 {"lowres", &lavc_param_lowres_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
119 {"skiploopfilter", &lavc_param_skip_loop_filter_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
120 {"skipidct", &lavc_param_skip_idct_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
121 {"skipframe", &lavc_param_skip_frame_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
122 {"threads", &lavc_param_threads, CONF_TYPE_INT, CONF_RANGE, 1, 8, NULL},
123 {"bitexact", &lavc_param_bitexact, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_BITEXACT, NULL},
124 {"o", &lavc_avopt, CONF_TYPE_STRING, 0, 0, 0, NULL},
125 {NULL, NULL, 0, 0, 0, 0, NULL}
128 static enum AVDiscard str2AVDiscard(char *str) {
129 if (!str) return AVDISCARD_DEFAULT;
130 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
131 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
132 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
133 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
134 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
135 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
136 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
137 return AVDISCARD_DEFAULT;
140 // to set/get/query special features/parameters
141 static int control(sh_video_t *sh, int cmd, void *arg, ...){
142 vd_ffmpeg_ctx *ctx = sh->context;
143 AVCodecContext *avctx = ctx->avctx;
144 switch(cmd){
145 case VDCTRL_QUERY_FORMAT:
147 int format =(*((int *)arg));
148 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
149 // possible conversions:
150 switch(format){
151 case IMGFMT_YV12:
152 case IMGFMT_IYUV:
153 case IMGFMT_I420:
154 // "converted" using pointer/stride modification
155 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
156 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
157 break;
158 #if CONFIG_XVMC
159 case IMGFMT_XVMC_IDCT_MPEG2:
160 case IMGFMT_XVMC_MOCO_MPEG2:
161 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
162 #endif
164 return CONTROL_FALSE;
166 case VDCTRL_RESYNC_STREAM:
167 avcodec_flush_buffers(avctx);
168 return CONTROL_TRUE;
169 case VDCTRL_QUERY_UNSEEN_FRAMES:
170 return avctx->has_b_frames + 10;
172 return CONTROL_UNKNOWN;
175 static void mp_msp_av_log_callback(void *ptr, int level, const char *fmt,
176 va_list vl)
178 static int print_prefix=1;
179 AVClass *avc= ptr ? *(AVClass **)ptr : NULL;
180 int type= MSGT_FIXME;
181 int mp_level;
182 char buf[256];
184 switch(level){
185 case AV_LOG_VERBOSE: mp_level = MSGL_V ; break;
186 case AV_LOG_DEBUG: mp_level= MSGL_V ; break;
187 case AV_LOG_INFO : mp_level= MSGL_INFO; break;
188 case AV_LOG_ERROR: mp_level= MSGL_ERR ; break;
189 default : mp_level= MSGL_ERR ; break;
192 if (!mp_msg_test(type, mp_level)) return;
194 if(ptr){
195 if(!strcmp(avc->class_name, "AVCodecContext")){
196 AVCodecContext *s= ptr;
197 if(s->codec){
198 if(s->codec->type == CODEC_TYPE_AUDIO){
199 if(s->codec->decode)
200 type= MSGT_DECAUDIO;
201 }else if(s->codec->type == CODEC_TYPE_VIDEO){
202 if(s->codec->decode)
203 type= MSGT_DECVIDEO;
205 //FIXME subtitles, encoders (what msgt for them? there is no appropriate ...)
207 }else if(!strcmp(avc->class_name, "AVFormatContext")){
208 #if 0 //needs libavformat include FIXME iam too lazy to do this cleanly, probably the whole should be moved out of this file ...
209 AVFormatContext *s= ptr;
210 if(s->iformat)
211 type= MSGT_DEMUXER;
212 else if(s->oformat)
213 type= MSGT_MUXER;
214 #endif
218 if(print_prefix && avc) {
219 mp_msg(type, mp_level, "[%s @ %p]", avc->item_name(ptr), avc);
222 print_prefix= strchr(fmt, '\n') != NULL;
223 vsnprintf(buf, sizeof(buf), fmt, vl);
224 mp_msg(type, mp_level, buf);
227 static void set_format_params(struct AVCodecContext *avctx, enum PixelFormat fmt){
228 int imgfmt;
229 if (fmt == PIX_FMT_NONE)
230 return;
231 imgfmt = pixfmt2imgfmt(fmt);
232 if (IMGFMT_IS_XVMC(imgfmt) || IMGFMT_IS_VDPAU(imgfmt)) {
233 sh_video_t *sh = avctx->opaque;
234 vd_ffmpeg_ctx *ctx = sh->context;
235 ctx->do_dr1 = 1;
236 ctx->do_slices = 1;
237 avctx->thread_count = 1;
238 avctx->get_buffer = get_buffer;
239 avctx->release_buffer = release_buffer;
240 avctx->reget_buffer = get_buffer;
241 avctx->draw_horiz_band = draw_slice;
242 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedMPEG2);
243 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
247 // init driver
248 static int init(sh_video_t *sh){
249 AVCodecContext *avctx;
250 vd_ffmpeg_ctx *ctx;
251 AVCodec *lavc_codec;
252 int lowres_w=0;
253 int do_vis_debug= lavc_param_vismv || (lavc_param_debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
255 if(!avcodec_initialized){
256 avcodec_init();
257 avcodec_register_all();
258 avcodec_initialized=1;
259 av_log_set_callback(mp_msp_av_log_callback);
262 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
263 if (!ctx)
264 return 0;
265 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
267 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
268 if(!lavc_codec){
269 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MissingLAVCcodec, sh->codec->dll);
270 uninit(sh);
271 return 0;
274 if(vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
275 ctx->do_slices=1;
277 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)
278 ctx->do_dr1=1;
279 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
280 ctx->ip_count= ctx->b_count= 0;
282 ctx->pic = avcodec_alloc_frame();
283 ctx->avctx = avcodec_alloc_context();
284 avctx = ctx->avctx;
285 avctx->opaque = sh;
286 avctx->codec_type = CODEC_TYPE_VIDEO;
287 avctx->codec_id = lavc_codec->id;
289 #if CONFIG_VDPAU
290 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU){
291 avctx->get_format = get_format;
293 #endif /* CONFIG_VDPAU */
294 #if CONFIG_XVMC
295 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
296 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedCodec);
297 avctx->get_format= get_format;//for now only this decoder will use it
298 // HACK around badly placed checks in mpeg_mc_decode_init
299 set_format_params(avctx, PIX_FMT_XVMC_MPEG2_IDCT);
301 #endif /* CONFIG_XVMC */
302 if(ctx->do_dr1){
303 avctx->flags|= CODEC_FLAG_EMU_EDGE;
304 avctx->get_buffer= get_buffer;
305 avctx->release_buffer= release_buffer;
306 avctx->reget_buffer= get_buffer;
309 avctx->flags|= lavc_param_bitexact;
311 avctx->width = sh->disp_w;
312 avctx->height= sh->disp_h;
313 avctx->workaround_bugs= lavc_param_workaround_bugs;
314 avctx->error_recognition= lavc_param_error_resilience;
315 if(lavc_param_gray) avctx->flags|= CODEC_FLAG_GRAY;
316 avctx->flags2|= lavc_param_fast;
317 avctx->codec_tag= sh->format;
318 avctx->stream_codec_tag= sh->video.fccHandler;
319 avctx->idct_algo= lavc_param_idct_algo;
320 avctx->error_concealment= lavc_param_error_concealment;
321 avctx->debug= lavc_param_debug;
322 if (lavc_param_debug)
323 av_log_set_level(AV_LOG_DEBUG);
324 avctx->debug_mv= lavc_param_vismv;
325 avctx->skip_top = lavc_param_skip_top;
326 avctx->skip_bottom= lavc_param_skip_bottom;
327 if(lavc_param_lowres_str != NULL)
329 sscanf(lavc_param_lowres_str, "%d,%d", &lavc_param_lowres, &lowres_w);
330 if(lavc_param_lowres < 1 || lavc_param_lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
331 lavc_param_lowres = 0;
332 avctx->lowres = lavc_param_lowres;
334 avctx->skip_loop_filter = str2AVDiscard(lavc_param_skip_loop_filter_str);
335 avctx->skip_idct = str2AVDiscard(lavc_param_skip_idct_str);
336 avctx->skip_frame = str2AVDiscard(lavc_param_skip_frame_str);
338 if(lavc_avopt){
339 if(parse_avopts(avctx, lavc_avopt) < 0){
340 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_avopt);
341 uninit(sh);
342 return 0;
346 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
347 switch (sh->format) {
348 case mmioFOURCC('S','V','Q','3'):
349 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
350 in the phony AVI header if demux_lavf is used. The first case is
351 handled here; the second case falls through to the next section. */
352 if (sh->ImageDesc) {
353 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
354 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
355 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
356 break;
358 /* fallthrough */
360 case mmioFOURCC('A','V','R','n'):
361 case mmioFOURCC('M','J','P','G'):
362 /* AVRn stores huffman table in AVI header */
363 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
364 MJPG fourcc :( */
365 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
366 break;
367 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
368 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
369 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
370 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
372 #if 0
374 int x;
375 uint8_t *p = avctx->extradata;
377 for (x=0; x<avctx->extradata_size; x++)
378 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
379 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
381 #endif
382 break;
384 case mmioFOURCC('R', 'V', '1', '0'):
385 case mmioFOURCC('R', 'V', '1', '3'):
386 case mmioFOURCC('R', 'V', '2', '0'):
387 case mmioFOURCC('R', 'V', '3', '0'):
388 case mmioFOURCC('R', 'V', '4', '0'):
389 if(sh->bih->biSize<sizeof(*sh->bih)+8){
390 /* only 1 packet per frame & sub_id from fourcc */
391 avctx->extradata_size= 8;
392 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
393 ((uint32_t *)avctx->extradata)[0] = 0;
394 ((uint32_t *)avctx->extradata)[1] =
395 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
396 } else {
397 /* has extra slice header (demux_rm or rm->avi streamcopy) */
398 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
399 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
400 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
402 avctx->sub_id= AV_RB32(avctx->extradata+4);
404 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
405 break;
407 default:
408 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
409 break;
410 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
411 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
412 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
413 break;
415 /* Pass palette to codec */
416 if (sh->bih && (sh->bih->biBitCount <= 8)) {
417 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
418 avctx->palctrl->palette_changed = 1;
419 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
420 /* Palette size in biSize */
421 memcpy(avctx->palctrl->palette, sh->bih+1,
422 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
423 else
424 /* Palette size in biClrUsed */
425 memcpy(avctx->palctrl->palette, sh->bih+1,
426 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
429 if(sh->bih)
430 avctx->bits_per_coded_sample= sh->bih->biBitCount;
432 if(lavc_param_threads > 1)
433 avcodec_thread_init(avctx, lavc_param_threads);
434 /* open it */
435 if (avcodec_open(avctx, lavc_codec) < 0) {
436 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_CantOpenCodec);
437 uninit(sh);
438 return 0;
440 // this is necessary in case get_format was never called and init_vo is
441 // too late e.g. for H.264 VDPAU
442 set_format_params(avctx, avctx->pix_fmt);
443 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
444 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
447 // uninit driver
448 static void uninit(sh_video_t *sh){
449 vd_ffmpeg_ctx *ctx = sh->context;
450 AVCodecContext *avctx = ctx->avctx;
452 if(lavc_param_vstats){
453 int i;
454 for(i=1; i<32; i++){
455 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
457 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_ArithmeticMeanOfQP,
458 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
459 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
463 if (avctx) {
464 if (avctx->codec && avcodec_close(avctx) < 0)
465 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_CantCloseCodec);
467 av_freep(&avctx->extradata);
468 av_freep(&avctx->palctrl);
469 av_freep(&avctx->slice_offset);
472 av_freep(&avctx);
473 av_freep(&ctx->pic);
474 if (ctx)
475 free(ctx);
478 static void draw_slice(struct AVCodecContext *s,
479 const AVFrame *src, int offset[4],
480 int y, int type, int height){
481 sh_video_t *sh = s->opaque;
482 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
483 int strides[MP_MAX_PLANES] = {src->linesize[0], src->linesize[1], src->linesize[2]};
484 #if 0
485 int start=0, i;
486 int width= s->width;
487 int skip_stride= ((width<<lavc_param_lowres)+15)>>4;
488 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
489 int threshold= s->coded_frame->age;
490 if(s->pict_type!=B_TYPE){
491 for(i=0; i*16<width+16; i++){
492 if(i*16>=width || skip[i]>=threshold){
493 if(start==i) start++;
494 else{
495 uint8_t *src2[3]= {src[0] + start*16,
496 src[1] + start*8,
497 src[2] + start*8};
498 //printf("%2d-%2d x %d\n", start, i, y);
499 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
500 start= i+1;
504 }else
505 #endif
506 if (height < 0)
508 int i;
509 height = -height;
510 y -= height;
511 for (i = 0; i < MP_MAX_PLANES; i++)
513 strides[i] = -strides[i];
514 source[i] -= strides[i];
517 if (y < sh->disp_h) {
518 mpcodecs_draw_slice (sh, source, strides, sh->disp_w, (y+height)<=sh->disp_h?height:sh->disp_h-y, 0, y);
523 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
524 vd_ffmpeg_ctx *ctx = sh->context;
525 AVCodecContext *avctx = ctx->avctx;
526 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
527 int width, height;
529 width = avctx->width;
530 height = avctx->height;
532 // HACK!
533 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
534 // use dimensions from BIH to avoid black borders at the right and bottom.
535 if (sh->bih && sh->ImageDesc) {
536 width = sh->bih->biWidth>>lavc_param_lowres;
537 height = sh->bih->biHeight>>lavc_param_lowres;
540 // it is possible another vo buffers to be used after vo config()
541 // lavc reset its buffers on width/heigh change but not on aspect change!!!
542 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
543 width != sh->disp_w ||
544 height != sh->disp_h ||
545 pix_fmt != ctx->pix_fmt ||
546 !ctx->vo_initialized)
548 // this is a special-case HACK for MPEG-1/2 VDPAU that uses neither get_format nor
549 // sets the value correctly in avcodec_open.
550 set_format_params(avctx, avctx->pix_fmt);
551 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
552 if (sh->aspect == 0 ||
553 av_cmp_q(avctx->sample_aspect_ratio,
554 ctx->last_sample_aspect_ratio))
555 sh->aspect = aspect;
556 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
557 sh->disp_w = width;
558 sh->disp_h = height;
559 ctx->pix_fmt = pix_fmt;
560 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
561 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
562 return -1;
563 ctx->vo_initialized = 1;
565 return 0;
568 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
569 sh_video_t *sh = avctx->opaque;
570 vd_ffmpeg_ctx *ctx = sh->context;
571 mp_image_t *mpi=NULL;
572 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
573 int type= MP_IMGTYPE_IPB;
574 int width= avctx->width;
575 int height= avctx->height;
576 avcodec_align_dimensions(avctx, &width, &height);
577 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
579 if (pic->buffer_hints) {
580 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
581 type = MP_IMGTYPE_TEMP;
582 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
583 flags |= MP_IMGFLAG_READABLE;
584 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
585 type = MP_IMGTYPE_STATIC;
586 flags |= MP_IMGFLAG_PRESERVE;
588 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
589 type = MP_IMGTYPE_STATIC;
590 flags |= MP_IMGFLAG_PRESERVE;
592 flags|=(!avctx->hurry_up && ctx->do_slices) ?
593 MP_IMGFLAG_DRAW_CALLBACK:0;
594 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
595 } else {
596 if(!pic->reference){
597 ctx->b_count++;
598 flags|=(!avctx->hurry_up && ctx->do_slices) ?
599 MP_IMGFLAG_DRAW_CALLBACK:0;
600 }else{
601 ctx->ip_count++;
602 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
603 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
607 if(init_vo(sh, avctx->pix_fmt) < 0){
608 avctx->release_buffer= avcodec_default_release_buffer;
609 avctx->get_buffer= avcodec_default_get_buffer;
610 return avctx->get_buffer(avctx, pic);
613 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
614 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
615 } else
616 if (!pic->buffer_hints) {
617 if(ctx->b_count>1 || ctx->ip_count>2){
618 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_DRIFailure);
620 ctx->do_dr1=0; //FIXME
621 avctx->get_buffer= avcodec_default_get_buffer;
622 return avctx->get_buffer(avctx, pic);
625 if(avctx->has_b_frames){
626 type= MP_IMGTYPE_IPB;
627 }else{
628 type= MP_IMGTYPE_IP;
630 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
633 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
634 flags |= MP_IMGFLAG_RGB_PALETTE;
635 mpi= mpcodecs_get_image(sh, type, flags, width, height);
636 if (!mpi) return -1;
638 // ok, let's see what did we get:
639 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
640 !(mpi->flags&MP_IMGFLAG_DIRECT)){
641 // nice, filter/vo likes draw_callback :)
642 avctx->draw_horiz_band= draw_slice;
643 } else
644 avctx->draw_horiz_band= NULL;
645 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
646 avctx->draw_horiz_band= draw_slice;
648 #if CONFIG_XVMC
649 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
650 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
651 avctx->draw_horiz_band= draw_slice;
652 if(!avctx->xvmc_acceleration) {
653 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_McGetBufferShouldWorkOnlyWithXVMC);
654 assert(0);
655 exit(1);
656 // return -1;//!!fixme check error conditions in ffmpeg
658 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
659 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_OnlyBuffersAllocatedByVoXvmcAllowed);
660 assert(0);
661 exit(1);
662 // return -1;//!!fixme check error conditions in ffmpeg
664 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
665 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
666 assert(render != 0);
667 assert(render->xvmc_id == AV_XVMC_ID);
668 render->state |= AV_XVMC_STATE_PREDICTION;
670 #endif
672 pic->data[0]= mpi->planes[0];
673 pic->data[1]= mpi->planes[1];
674 pic->data[2]= mpi->planes[2];
675 pic->data[3]= mpi->planes[3];
677 #if 0
678 assert(mpi->width >= ((width +align)&(~align)));
679 assert(mpi->height >= ((height+align)&(~align)));
680 assert(mpi->stride[0] >= mpi->width);
681 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
682 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
683 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
685 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
686 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
687 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
688 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
689 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
690 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
692 #endif
694 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
695 * lavc will check that and die with an error message, if its not true
697 pic->linesize[0]= mpi->stride[0];
698 pic->linesize[1]= mpi->stride[1];
699 pic->linesize[2]= mpi->stride[2];
700 pic->linesize[3]= mpi->stride[3];
702 pic->opaque = mpi;
703 //printf("%X\n", (int)mpi->planes[0]);
704 #if 0
705 if(mpi->flags&MP_IMGFLAG_DIRECT)
706 printf("D");
707 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
708 printf("S");
709 else
710 printf(".");
711 #endif
712 if(pic->reference){
713 pic->age= ctx->ip_age[0];
715 ctx->ip_age[0]= ctx->ip_age[1]+1;
716 ctx->ip_age[1]= 1;
717 ctx->b_age++;
718 }else{
719 pic->age= ctx->b_age;
721 ctx->ip_age[0]++;
722 ctx->ip_age[1]++;
723 ctx->b_age=1;
725 pic->type= FF_BUFFER_TYPE_USER;
726 return 0;
729 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
730 mp_image_t *mpi= pic->opaque;
731 sh_video_t *sh = avctx->opaque;
732 vd_ffmpeg_ctx *ctx = sh->context;
733 int i;
735 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
737 if(ctx->ip_count <= 2 && ctx->b_count<=1){
738 if(mpi->flags&MP_IMGFLAG_PRESERVE)
739 ctx->ip_count--;
740 else
741 ctx->b_count--;
744 if (mpi) {
745 // Palette support: free palette buffer allocated in get_buffer
746 if (mpi->bpp == 8)
747 av_freep(&mpi->planes[1]);
748 #if CONFIG_XVMC
749 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
750 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
751 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
752 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
753 assert(render!=NULL);
754 assert(render->xvmc_id == AV_XVMC_ID);
755 render->state&=~AV_XVMC_STATE_PREDICTION;
757 #endif
758 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
759 mpi->usage_count--;
762 if(pic->type!=FF_BUFFER_TYPE_USER){
763 avcodec_default_release_buffer(avctx, pic);
764 return;
767 for(i=0; i<4; i++){
768 pic->data[i]= NULL;
770 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
773 // copypaste from demux_real.c - it should match to get it working!
774 //FIXME put into some header
775 typedef struct dp_hdr_s {
776 uint32_t chunks; // number of chunks
777 uint32_t timestamp; // timestamp from packet header
778 uint32_t len; // length of actual data
779 uint32_t chunktab; // offset to chunk offset array
780 } dp_hdr_t;
782 static void swap_palette(void *pal)
784 int i;
785 uint32_t *p = pal;
786 for (i = 0; i < AVPALETTE_COUNT; i++)
787 p[i] = le2me_32(p[i]);
790 // decode a frame
791 static mp_image_t *decode(sh_video_t *sh, void *data, int len, int flags){
792 int got_picture=0;
793 int ret;
794 vd_ffmpeg_ctx *ctx = sh->context;
795 AVFrame *pic= ctx->pic;
796 AVCodecContext *avctx = ctx->avctx;
797 mp_image_t *mpi=NULL;
798 int dr1= ctx->do_dr1;
799 AVPacket pkt;
801 if(len<=0) return NULL; // skipped frame
803 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
804 if (!dr1)
805 avctx->draw_horiz_band=NULL;
806 if(ctx->vo_initialized && !(flags&3) && !dr1){
807 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
808 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
809 sh->disp_w, sh->disp_h);
810 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
811 // vd core likes slices!
812 avctx->draw_horiz_band=draw_slice;
816 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
818 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
819 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
820 av_init_packet(&pkt);
821 pkt.data = data;
822 pkt.size = len;
823 // HACK: make PNGs decode normally instead of as CorePNG delta frames
824 pkt.flags = PKT_FLAG_KEY;
825 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
827 dr1= ctx->do_dr1;
828 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
829 //printf("repeat: %d\n", pic->repeat_pict);
830 //-- vstats generation
831 while(lavc_param_vstats){ // always one time loop
832 static FILE *fvstats=NULL;
833 char filename[20];
834 static long long int all_len=0;
835 static int frame_number=0;
836 static double all_frametime=0.0;
837 AVFrame *pic= avctx->coded_frame;
838 double quality=0.0;
840 if(!fvstats) {
841 time_t today2;
842 struct tm *today;
843 today2 = time(NULL);
844 today = localtime(&today2);
845 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
846 today->tm_min, today->tm_sec);
847 fvstats = fopen(filename, "w");
848 if(!fvstats) {
849 perror("fopen");
850 lavc_param_vstats=0; // disable block
851 break;
852 /*exit(1);*/
856 // average MB quantizer
858 int x, y;
859 int w = ((avctx->width << lavc_param_lowres)+15) >> 4;
860 int h = ((avctx->height << lavc_param_lowres)+15) >> 4;
861 int8_t *q = pic->qscale_table;
862 for(y = 0; y < h; y++) {
863 for(x = 0; x < w; x++)
864 quality += (double)*(q+x);
865 q += pic->qstride;
867 quality /= w * h;
870 all_len+=len;
871 all_frametime+=sh->frametime;
872 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
873 ++frame_number, quality, len, (double)all_len/1024);
874 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
875 all_frametime, (double)(len*8)/sh->frametime/1000.0,
876 (double)(all_len*8)/all_frametime/1000.0);
877 switch(pic->pict_type){
878 case FF_I_TYPE:
879 fprintf(fvstats, "type= I\n");
880 break;
881 case FF_P_TYPE:
882 fprintf(fvstats, "type= P\n");
883 break;
884 case FF_S_TYPE:
885 fprintf(fvstats, "type= S\n");
886 break;
887 case FF_B_TYPE:
888 fprintf(fvstats, "type= B\n");
889 break;
890 default:
891 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
892 break;
895 ctx->qp_stat[(int)(quality+0.5)]++;
896 ctx->qp_sum += quality;
897 ctx->inv_qp_sum += 1.0/(double)quality;
899 break;
901 //--
903 if(!got_picture) return NULL; // skipped image
905 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
907 if(dr1 && pic->opaque){
908 mpi= (mp_image_t *)pic->opaque;
911 if(!mpi)
912 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
913 avctx->width, avctx->height);
914 if(!mpi){ // temporary!
915 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_CouldntAllocateImageForCodec);
916 return NULL;
919 if(!dr1){
920 mpi->planes[0]=pic->data[0];
921 mpi->planes[1]=pic->data[1];
922 mpi->planes[2]=pic->data[2];
923 mpi->planes[3]=pic->data[3];
924 mpi->stride[0]=pic->linesize[0];
925 mpi->stride[1]=pic->linesize[1];
926 mpi->stride[2]=pic->linesize[2];
927 mpi->stride[3]=pic->linesize[3];
930 if (!mpi->planes[0])
931 return NULL;
933 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
934 // we have 422p but user wants 420p
935 mpi->stride[1]*=2;
936 mpi->stride[2]*=2;
939 #if HAVE_BIGENDIAN
940 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
941 if (mpi->bpp == 8)
942 swap_palette(mpi->planes[1]);
943 #endif
944 /* to comfirm with newer lavc style */
945 mpi->qscale =pic->qscale_table;
946 mpi->qstride=pic->qstride;
947 mpi->pict_type=pic->pict_type;
948 mpi->qscale_type= pic->qscale_type;
949 mpi->fields = MP_IMGFIELD_ORDERED;
950 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
951 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
952 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
954 return mpi;
957 #if CONFIG_XVMC || CONFIG_VDPAU
958 static enum PixelFormat get_format(struct AVCodecContext *avctx,
959 const enum PixelFormat *fmt){
960 enum PixelFormat selected_format;
961 int imgfmt;
962 sh_video_t *sh = avctx->opaque;
963 int i;
965 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
966 imgfmt = pixfmt2imgfmt(fmt[i]);
967 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
968 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_TryingPixfmt, i);
969 if(init_vo(sh, fmt[i]) >= 0) {
970 break;
973 selected_format = fmt[i];
974 set_format_params(avctx, selected_format);
975 return selected_format;
977 #endif /* CONFIG_XVMC || CONFIG_VDPAU */