partial sync with obsolete section removal
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
bloba3055ccc1a47b35dc0baa982aa5241d4c98cf08f
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"
15 #include "vd_internal.h"
17 static vd_info_t info = {
18 "FFmpeg's libavcodec codec family",
19 "ffmpeg",
20 "A'rpi",
21 "A'rpi, Michael, Alex",
22 "native codecs"
25 LIBVD_EXTERN(ffmpeg)
27 #include "libavcodec/avcodec.h"
29 #if CONFIG_XVMC
30 #include "xvmc_render.h"
31 #endif
33 int avcodec_initialized=0;
35 typedef struct {
36 AVCodecContext *avctx;
37 AVFrame *pic;
38 enum PixelFormat pix_fmt;
39 int do_slices;
40 int do_dr1;
41 int vo_initialized;
42 int best_csp;
43 int b_age;
44 int ip_age[2];
45 int qp_stat[32];
46 double qp_sum;
47 double inv_qp_sum;
48 int ip_count;
49 int b_count;
50 AVRational last_sample_aspect_ratio;
51 } vd_ffmpeg_ctx;
53 //#ifdef CONFIG_LIBPOSTPROC
54 //unsigned int lavc_pp=0;
55 //#endif
57 #include "m_option.h"
59 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
60 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
62 #if CONFIG_XVMC
63 static enum PixelFormat get_format(struct AVCodecContext * avctx,
64 const enum PixelFormat * pix_fmt);
65 static int mc_get_buffer(AVCodecContext *avctx, AVFrame *pic);
66 static void mc_release_buffer(AVCodecContext *avctx, AVFrame *pic);
67 static void mc_render_slice(struct AVCodecContext *s,
68 AVFrame *src, int offset[4],
69 int y, int type, int height);
70 #endif
72 static int lavc_param_workaround_bugs= FF_BUG_AUTODETECT;
73 static int lavc_param_error_resilience=2;
74 static int lavc_param_error_concealment=3;
75 static int lavc_param_gray=0;
76 static int lavc_param_vstats=0;
77 static int lavc_param_idct_algo=0;
78 static int lavc_param_debug=0;
79 static int lavc_param_vismv=0;
80 static int lavc_param_skip_top=0;
81 static int lavc_param_skip_bottom=0;
82 static int lavc_param_fast=0;
83 static int lavc_param_lowres=0;
84 static char *lavc_param_lowres_str=NULL;
85 static char *lavc_param_skip_loop_filter_str = NULL;
86 static char *lavc_param_skip_idct_str = NULL;
87 static char *lavc_param_skip_frame_str = NULL;
88 static int lavc_param_threads=1;
89 static int lavc_param_bitexact=0;
90 static char *lavc_avopt = NULL;
92 const m_option_t lavc_decode_opts_conf[]={
93 {"bug", &lavc_param_workaround_bugs, CONF_TYPE_INT, CONF_RANGE, -1, 999999, NULL},
94 {"er", &lavc_param_error_resilience, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
95 {"gray", &lavc_param_gray, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_PART, NULL},
96 {"idct", &lavc_param_idct_algo, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
97 {"ec", &lavc_param_error_concealment, CONF_TYPE_INT, CONF_RANGE, 0, 99, NULL},
98 {"vstats", &lavc_param_vstats, CONF_TYPE_FLAG, 0, 0, 1, NULL},
99 {"debug", &lavc_param_debug, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
100 {"vismv", &lavc_param_vismv, CONF_TYPE_INT, CONF_RANGE, 0, 9999999, NULL},
101 {"st", &lavc_param_skip_top, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
102 {"sb", &lavc_param_skip_bottom, CONF_TYPE_INT, CONF_RANGE, 0, 999, NULL},
103 #ifdef CODEC_FLAG2_FAST
104 {"fast", &lavc_param_fast, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG2_FAST, NULL},
105 #endif
106 {"lowres", &lavc_param_lowres_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
107 {"skiploopfilter", &lavc_param_skip_loop_filter_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
108 {"skipidct", &lavc_param_skip_idct_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
109 {"skipframe", &lavc_param_skip_frame_str, CONF_TYPE_STRING, 0, 0, 0, NULL},
110 {"threads", &lavc_param_threads, CONF_TYPE_INT, CONF_RANGE, 1, 8, NULL},
111 {"bitexact", &lavc_param_bitexact, CONF_TYPE_FLAG, 0, 0, CODEC_FLAG_BITEXACT, NULL},
112 {"o", &lavc_avopt, CONF_TYPE_STRING, 0, 0, 0, NULL},
113 {NULL, NULL, 0, 0, 0, 0, NULL}
116 static enum AVDiscard str2AVDiscard(char *str) {
117 if (!str) return AVDISCARD_DEFAULT;
118 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
119 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
120 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
121 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
122 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
123 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
124 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
125 return AVDISCARD_DEFAULT;
128 // to set/get/query special features/parameters
129 static int control(sh_video_t *sh,int cmd,void* arg,...){
130 vd_ffmpeg_ctx *ctx = sh->context;
131 AVCodecContext *avctx = ctx->avctx;
132 switch(cmd){
133 case VDCTRL_QUERY_FORMAT:
135 int format =(*((int*)arg));
136 if( format == ctx->best_csp ) return CONTROL_TRUE;//supported
137 // possible conversions:
138 switch( format ){
139 case IMGFMT_YV12:
140 case IMGFMT_IYUV:
141 case IMGFMT_I420:
142 // "converted" using pointer/stride modification
143 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
144 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
145 break;
146 #if CONFIG_XVMC
147 case IMGFMT_XVMC_IDCT_MPEG2:
148 case IMGFMT_XVMC_MOCO_MPEG2:
149 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
150 #endif
152 return CONTROL_FALSE;
154 break;
155 case VDCTRL_RESYNC_STREAM:
156 avcodec_flush_buffers(avctx);
157 return CONTROL_TRUE;
158 case VDCTRL_QUERY_UNSEEN_FRAMES:
159 return avctx->has_b_frames + 10;
161 return CONTROL_UNKNOWN;
164 void mp_msp_av_log_callback(void* ptr, int level, const char* fmt, va_list vl)
166 static int print_prefix=1;
167 AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
168 int type= MSGT_FIXME;
169 int mp_level;
170 char buf[256];
172 switch(level){
173 case AV_LOG_DEBUG: mp_level= MSGL_V ; break;
174 case AV_LOG_INFO : mp_level= MSGL_INFO; break;
175 case AV_LOG_ERROR: mp_level= MSGL_ERR ; break;
176 default : mp_level= MSGL_ERR ; break;
179 if (!mp_msg_test(type, mp_level)) return;
181 if(ptr){
182 if(!strcmp(avc->class_name, "AVCodecContext")){
183 AVCodecContext * s= ptr;
184 if(s->codec){
185 if(s->codec->type == CODEC_TYPE_AUDIO){
186 if(s->codec->decode)
187 type= MSGT_DECAUDIO;
188 }else if(s->codec->type == CODEC_TYPE_VIDEO){
189 if(s->codec->decode)
190 type= MSGT_DECVIDEO;
192 //FIXME subtitles, encoders (what msgt for them? there is no appropriate ...)
194 }else if(!strcmp(avc->class_name, "AVFormatContext")){
195 #if 0 //needs libavformat include FIXME iam too lazy to do this cleanly,probably the whole should be moved out of this file ...
196 AVFormatContext * s= ptr;
197 if(s->iformat)
198 type= MSGT_DEMUXER;
199 else if(s->oformat)
200 type= MSGT_MUXER;
201 #endif
205 if(print_prefix && avc) {
206 mp_msg(type, mp_level, "[%s @ %p]", avc->item_name(ptr), avc);
209 print_prefix= strchr(fmt, '\n') != NULL;
210 vsnprintf(buf, sizeof(buf), fmt, vl);
211 mp_msg(type, mp_level, buf);
214 // init driver
215 static int init(sh_video_t *sh){
216 AVCodecContext *avctx;
217 vd_ffmpeg_ctx *ctx;
218 AVCodec *lavc_codec;
219 int lowres_w=0;
220 int do_vis_debug= lavc_param_vismv || (lavc_param_debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
222 if(!avcodec_initialized){
223 avcodec_init();
224 avcodec_register_all();
225 avcodec_initialized=1;
226 av_log_set_callback(mp_msp_av_log_callback);
229 ctx = sh->context = malloc(sizeof(vd_ffmpeg_ctx));
230 if (!ctx)
231 return 0;
232 memset(ctx, 0, sizeof(vd_ffmpeg_ctx));
234 lavc_codec = (AVCodec *)avcodec_find_decoder_by_name(sh->codec->dll);
235 if(!lavc_codec){
236 mp_msg(MSGT_DECVIDEO,MSGL_ERR,MSGTR_MissingLAVCcodec,sh->codec->dll);
237 uninit(sh);
238 return 0;
241 if(vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
242 ctx->do_slices=1;
244 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)
245 ctx->do_dr1=1;
246 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
247 ctx->ip_count= ctx->b_count= 0;
249 ctx->pic = avcodec_alloc_frame();
250 ctx->avctx = avcodec_alloc_context();
251 avctx = ctx->avctx;
253 #if CONFIG_XVMC
255 #ifdef CODEC_CAP_HWACCEL
256 if(lavc_codec->capabilities & CODEC_CAP_HWACCEL){
257 #else
258 if(lavc_codec->id == CODEC_ID_MPEG2VIDEO_XVMC){
259 #endif /* CODEC_CAP_HWACCEL */
260 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedCodec);
261 assert(ctx->do_dr1);//these are must to!
262 assert(ctx->do_slices); //it is (vo_)ffmpeg bug if this fails
263 avctx->flags|= CODEC_FLAG_EMU_EDGE;//do i need that??!!
264 avctx->get_format= get_format;//for now only this decoder will use it
265 avctx->get_buffer= mc_get_buffer;
266 avctx->release_buffer= mc_release_buffer;
267 avctx->draw_horiz_band = mc_render_slice;
268 avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
269 }else
270 #endif /* CONFIG_XVMC */
271 if(ctx->do_dr1){
272 avctx->flags|= CODEC_FLAG_EMU_EDGE;
273 avctx->get_buffer= get_buffer;
274 avctx->release_buffer= release_buffer;
275 avctx->reget_buffer= get_buffer;
278 #ifdef CODEC_FLAG_NOT_TRUNCATED
279 avctx->flags|= CODEC_FLAG_NOT_TRUNCATED;
280 #endif
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 #ifdef CODEC_FLAG2_FAST
289 avctx->flags2|= lavc_param_fast;
290 #endif
291 avctx->codec_tag= sh->format;
292 avctx->stream_codec_tag= sh->video.fccHandler;
293 avctx->idct_algo= lavc_param_idct_algo;
294 avctx->error_concealment= lavc_param_error_concealment;
295 avctx->debug= lavc_param_debug;
296 if (lavc_param_debug)
297 av_log_set_level(AV_LOG_DEBUG);
298 avctx->debug_mv= lavc_param_vismv;
299 avctx->skip_top = lavc_param_skip_top;
300 avctx->skip_bottom= lavc_param_skip_bottom;
301 if(lavc_param_lowres_str != NULL)
303 sscanf(lavc_param_lowres_str, "%d,%d", &lavc_param_lowres, &lowres_w);
304 if(lavc_param_lowres < 1 || lavc_param_lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
305 lavc_param_lowres = 0;
306 avctx->lowres = lavc_param_lowres;
308 avctx->skip_loop_filter = str2AVDiscard(lavc_param_skip_loop_filter_str);
309 avctx->skip_idct = str2AVDiscard(lavc_param_skip_idct_str);
310 avctx->skip_frame = str2AVDiscard(lavc_param_skip_frame_str);
312 if(lavc_avopt){
313 if(parse_avopts(avctx, lavc_avopt) < 0){
314 mp_msg(MSGT_DECVIDEO,MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_avopt);
315 uninit(sh);
316 return 0;
320 mp_dbg(MSGT_DECVIDEO,MSGL_DBG2,"libavcodec.size: %d x %d\n",avctx->width,avctx->height);
321 switch (sh->format) {
322 case mmioFOURCC('S','V','Q','3'):
323 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
324 in the phony AVI header if demux_lavf is used. The first case is
325 handled here; the second case falls through to the next section. */
326 if (sh->ImageDesc) {
327 avctx->extradata_size = (*(int*)sh->ImageDesc) - sizeof(int);
328 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
329 memcpy(avctx->extradata, ((int*)sh->ImageDesc)+1, avctx->extradata_size);
330 break;
332 /* fallthrough */
334 case mmioFOURCC('A','V','R','n'):
335 case mmioFOURCC('M','J','P','G'):
336 /* AVRn stores huffman table in AVI header */
337 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
338 MJPG fourcc :( */
339 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
340 break;
341 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
342 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
343 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
344 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
346 #if 0
348 int x;
349 uint8_t *p = avctx->extradata;
351 for (x=0; x<avctx->extradata_size; x++)
352 mp_msg(MSGT_DECVIDEO, MSGL_INFO,"[%x] ", p[x]);
353 mp_msg(MSGT_DECVIDEO, MSGL_INFO,"\n");
355 #endif
356 break;
358 case mmioFOURCC('R', 'V', '1', '0'):
359 case mmioFOURCC('R', 'V', '1', '3'):
360 case mmioFOURCC('R', 'V', '2', '0'):
361 case mmioFOURCC('R', 'V', '3', '0'):
362 case mmioFOURCC('R', 'V', '4', '0'):
363 if(sh->bih->biSize<sizeof(*sh->bih)+8){
364 /* only 1 packet per frame & sub_id from fourcc */
365 avctx->extradata_size= 8;
366 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
367 ((uint32_t*)avctx->extradata)[0] = 0;
368 ((uint32_t*)avctx->extradata)[1] =
369 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
370 } else {
371 /* has extra slice header (demux_rm or rm->avi streamcopy) */
372 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
373 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
374 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
376 avctx->sub_id= AV_RB32(avctx->extradata+4);
378 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
379 break;
381 default:
382 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
383 break;
384 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
385 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
386 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
387 break;
389 /* Pass palette to codec */
390 if (sh->bih && (sh->bih->biBitCount <= 8)) {
391 avctx->palctrl = calloc(1,sizeof(AVPaletteControl));
392 avctx->palctrl->palette_changed = 1;
393 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
394 /* Palette size in biSize */
395 memcpy(avctx->palctrl->palette, sh->bih+1,
396 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
397 else
398 /* Palette size in biClrUsed */
399 memcpy(avctx->palctrl->palette, sh->bih+1,
400 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
403 if(sh->bih)
404 avctx->bits_per_coded_sample= sh->bih->biBitCount;
406 if(lavc_param_threads > 1)
407 avcodec_thread_init(avctx, lavc_param_threads);
408 /* open it */
409 if (avcodec_open(avctx, lavc_codec) < 0) {
410 mp_msg(MSGT_DECVIDEO,MSGL_ERR, MSGTR_CantOpenCodec);
411 uninit(sh);
412 return 0;
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 switch(pix_fmt){
517 // YUVJ are YUV formats that use the full Y range and not just
518 // 16 - 235 (see colorspaces.txt).
519 // Currently they are all treated the same way.
520 case PIX_FMT_YUV410P: ctx->best_csp=IMGFMT_YVU9;break; //svq1
521 case PIX_FMT_YUVJ420P:
522 case PIX_FMT_YUV420P: ctx->best_csp=IMGFMT_YV12;break; //mpegs
523 case PIX_FMT_YUVJ422P:
524 case PIX_FMT_YUV422P: ctx->best_csp=IMGFMT_422P;break; //mjpeg / huffyuv
525 case PIX_FMT_YUVJ444P:
526 case PIX_FMT_YUV444P: ctx->best_csp=IMGFMT_444P;break; //photo jpeg
527 case PIX_FMT_YUV411P: ctx->best_csp=IMGFMT_411P;break; //dv ntsc
528 case PIX_FMT_YUYV422: ctx->best_csp=IMGFMT_YUY2;break; //huffyuv perhaps in the future
529 case PIX_FMT_RGB24 : ctx->best_csp=IMGFMT_RGB24;break; //qtrle
530 case PIX_FMT_RGB32: ctx->best_csp=IMGFMT_BGR32;break; //huffyuv / mjpeg
531 case PIX_FMT_BGR24 : ctx->best_csp=IMGFMT_BGR24;break; //8bps
532 case PIX_FMT_RGB555: ctx->best_csp=IMGFMT_BGR15;break; //rpza,cram
533 case PIX_FMT_RGB565: ctx->best_csp=IMGFMT_BGR16;break; //4xm
534 case PIX_FMT_GRAY8: ctx->best_csp=IMGFMT_Y800;break; // gray jpeg
535 case PIX_FMT_PAL8: ctx->best_csp=IMGFMT_BGR8;break; //8bps,mrle,cram
536 #if CONFIG_XVMC
537 case PIX_FMT_XVMC_MPEG2_MC:ctx->best_csp=IMGFMT_XVMC_MOCO_MPEG2;break;
538 case PIX_FMT_XVMC_MPEG2_IDCT:ctx->best_csp=IMGFMT_XVMC_IDCT_MPEG2;break;
539 #endif
540 default:
541 ctx->best_csp=0;
543 if (!mpcodecs_config_vo(sh,sh->disp_w,sh->disp_h, ctx->best_csp))
544 return -1;
545 ctx->vo_initialized = 1;
547 return 0;
550 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
551 sh_video_t * sh = avctx->opaque;
552 vd_ffmpeg_ctx *ctx = sh->context;
553 mp_image_t* mpi=NULL;
554 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
555 int type= MP_IMGTYPE_IPB;
556 int width= avctx->width;
557 int height= avctx->height;
558 int align=15;
559 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
560 if(avctx->pix_fmt == PIX_FMT_YUV410P)
561 align=63; //yes seriously, its really needed (16x16 chroma blocks in SVQ1 -> 64x64)
563 if (pic->buffer_hints) {
564 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
565 type = MP_IMGTYPE_TEMP;
566 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
567 flags |= MP_IMGFLAG_READABLE;
568 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
569 type = MP_IMGTYPE_STATIC;
570 flags |= MP_IMGFLAG_PRESERVE;
572 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
573 type = MP_IMGTYPE_STATIC;
574 flags |= MP_IMGFLAG_PRESERVE;
576 flags|=(!avctx->hurry_up && ctx->do_slices) ?
577 MP_IMGFLAG_DRAW_CALLBACK:0;
578 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
579 } else {
580 if(!pic->reference){
581 ctx->b_count++;
582 flags|=(!avctx->hurry_up && ctx->do_slices) ?
583 MP_IMGFLAG_DRAW_CALLBACK:0;
584 }else{
585 ctx->ip_count++;
586 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
587 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
591 if(init_vo(sh,avctx->pix_fmt) < 0){
592 avctx->release_buffer= avcodec_default_release_buffer;
593 avctx->get_buffer= avcodec_default_get_buffer;
594 return avctx->get_buffer(avctx, pic);
597 if (!pic->buffer_hints) {
598 if(ctx->b_count>1 || ctx->ip_count>2){
599 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_DRIFailure);
601 ctx->do_dr1=0; //FIXME
602 avctx->get_buffer= avcodec_default_get_buffer;
603 return avctx->get_buffer(avctx, pic);
606 if(avctx->has_b_frames){
607 type= MP_IMGTYPE_IPB;
608 }else{
609 type= MP_IMGTYPE_IP;
611 mp_msg(MSGT_DECVIDEO,MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
614 mpi= mpcodecs_get_image(sh,type, flags,
615 (width+align)&(~align), (height+align)&(~align));
617 // ok, let's see what did we get:
618 if( mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
619 !(mpi->flags&MP_IMGFLAG_DIRECT)){
620 // nice, filter/vo likes draw_callback :)
621 avctx->draw_horiz_band= draw_slice;
622 } else
623 avctx->draw_horiz_band= NULL;
625 // Palette support: libavcodec copies palette to *data[1]
626 if (mpi->bpp == 8)
627 mpi->planes[1] = av_malloc(AVPALETTE_SIZE);
629 pic->data[0]= mpi->planes[0];
630 pic->data[1]= mpi->planes[1];
631 pic->data[2]= mpi->planes[2];
633 #if 0
634 assert(mpi->width >= ((width +align)&(~align)));
635 assert(mpi->height >= ((height+align)&(~align)));
636 assert(mpi->stride[0] >= mpi->width);
637 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
638 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
639 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
641 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
642 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
643 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
644 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
645 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
646 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
648 #endif
650 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
651 * lavc will check that and die with an error message, if its not true
653 pic->linesize[0]= mpi->stride[0];
654 pic->linesize[1]= mpi->stride[1];
655 pic->linesize[2]= mpi->stride[2];
657 pic->opaque = mpi;
658 //printf("%X\n", (int)mpi->planes[0]);
659 #if 0
660 if(mpi->flags&MP_IMGFLAG_DIRECT)
661 printf("D");
662 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
663 printf("S");
664 else
665 printf(".");
666 #endif
667 if(pic->reference){
668 pic->age= ctx->ip_age[0];
670 ctx->ip_age[0]= ctx->ip_age[1]+1;
671 ctx->ip_age[1]= 1;
672 ctx->b_age++;
673 }else{
674 pic->age= ctx->b_age;
676 ctx->ip_age[0]++;
677 ctx->ip_age[1]++;
678 ctx->b_age=1;
680 pic->type= FF_BUFFER_TYPE_USER;
681 return 0;
684 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
685 mp_image_t* mpi= pic->opaque;
686 sh_video_t * sh = avctx->opaque;
687 vd_ffmpeg_ctx *ctx = sh->context;
688 int i;
690 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
692 if(ctx->ip_count <= 2 && ctx->b_count<=1){
693 if(mpi->flags&MP_IMGFLAG_PRESERVE)
694 ctx->ip_count--;
695 else
696 ctx->b_count--;
699 // Palette support: free palette buffer allocated in get_buffer
700 if ( mpi && (mpi->bpp == 8))
701 av_freep(&mpi->planes[1]);
703 if(pic->type!=FF_BUFFER_TYPE_USER){
704 avcodec_default_release_buffer(avctx, pic);
705 return;
708 for(i=0; i<4; i++){
709 pic->data[i]= NULL;
711 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
714 // copypaste from demux_real.c - it should match to get it working!
715 //FIXME put into some header
716 typedef struct dp_hdr_s {
717 uint32_t chunks; // number of chunks
718 uint32_t timestamp; // timestamp from packet header
719 uint32_t len; // length of actual data
720 uint32_t chunktab; // offset to chunk offset array
721 } dp_hdr_t;
723 void swap_palette(void *pal) {
724 int i;
725 uint32_t *p = pal;
726 for (i = 0; i < AVPALETTE_COUNT; i++)
727 p[i] = le2me_32(p[i]);
730 // decode a frame
731 static mp_image_t* decode(sh_video_t *sh,void* data,int len,int flags){
732 int got_picture=0;
733 int ret;
734 vd_ffmpeg_ctx *ctx = sh->context;
735 AVFrame *pic= ctx->pic;
736 AVCodecContext *avctx = ctx->avctx;
737 mp_image_t* mpi=NULL;
738 int dr1= ctx->do_dr1;
740 if(len<=0) return NULL; // skipped frame
742 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
743 if (!dr1)
744 avctx->draw_horiz_band=NULL;
745 avctx->opaque=sh;
746 if(ctx->vo_initialized && !(flags&3) && !dr1){
747 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
748 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
749 sh->disp_w, sh->disp_h);
750 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
751 // vd core likes slices!
752 avctx->draw_horiz_band=draw_slice;
756 avctx->hurry_up=(flags&3)?((flags&2)?2:1):0;
758 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
759 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
760 ret = avcodec_decode_video(avctx, pic,
761 &got_picture, data, len);
763 dr1= ctx->do_dr1;
764 if(ret<0) mp_msg(MSGT_DECVIDEO,MSGL_WARN, "Error while decoding frame!\n");
765 //printf("repeat: %d\n", pic->repeat_pict);
766 //-- vstats generation
767 while(lavc_param_vstats){ // always one time loop
768 static FILE *fvstats=NULL;
769 char filename[20];
770 static long long int all_len=0;
771 static int frame_number=0;
772 static double all_frametime=0.0;
773 AVFrame *pic= avctx->coded_frame;
774 double quality=0.0;
776 if(!fvstats) {
777 time_t today2;
778 struct tm *today;
779 today2 = time(NULL);
780 today = localtime(&today2);
781 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
782 today->tm_min, today->tm_sec);
783 fvstats = fopen(filename,"w");
784 if(!fvstats) {
785 perror("fopen");
786 lavc_param_vstats=0; // disable block
787 break;
788 /*exit(1);*/
792 // average MB quantizer
794 int x, y;
795 int w = ((avctx->width << lavc_param_lowres)+15) >> 4;
796 int h = ((avctx->height << lavc_param_lowres)+15) >> 4;
797 int8_t *q = pic->qscale_table;
798 for( y = 0; y < h; y++ ) {
799 for( x = 0; x < w; x++ )
800 quality += (double)*(q+x);
801 q += pic->qstride;
803 quality /= w * h;
806 all_len+=len;
807 all_frametime+=sh->frametime;
808 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
809 ++frame_number, quality, len, (double)all_len/1024);
810 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
811 all_frametime, (double)(len*8)/sh->frametime/1000.0,
812 (double)(all_len*8)/all_frametime/1000.0);
813 switch(pic->pict_type){
814 case FF_I_TYPE:
815 fprintf(fvstats, "type= I\n");
816 break;
817 case FF_P_TYPE:
818 fprintf(fvstats, "type= P\n");
819 break;
820 case FF_S_TYPE:
821 fprintf(fvstats, "type= S\n");
822 break;
823 case FF_B_TYPE:
824 fprintf(fvstats, "type= B\n");
825 break;
826 default:
827 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
828 break;
831 ctx->qp_stat[(int)(quality+0.5)]++;
832 ctx->qp_sum += quality;
833 ctx->inv_qp_sum += 1.0/(double)quality;
835 break;
837 //--
839 if(!got_picture) return NULL; // skipped image
841 if(init_vo(sh,avctx->pix_fmt) < 0) return NULL;
843 if(dr1 && pic->opaque){
844 mpi= (mp_image_t*)pic->opaque;
847 if(!mpi)
848 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
849 avctx->width, avctx->height);
850 if(!mpi){ // temporary!
851 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_CouldntAllocateImageForCodec);
852 return NULL;
855 if(!dr1){
856 mpi->planes[0]=pic->data[0];
857 mpi->planes[1]=pic->data[1];
858 mpi->planes[2]=pic->data[2];
859 mpi->stride[0]=pic->linesize[0];
860 mpi->stride[1]=pic->linesize[1];
861 mpi->stride[2]=pic->linesize[2];
864 if (!mpi->planes[0])
865 return NULL;
867 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
868 // we have 422p but user wants 420p
869 mpi->stride[1]*=2;
870 mpi->stride[2]*=2;
873 #ifdef WORDS_BIGENDIAN
874 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
875 if (mpi->bpp == 8)
876 swap_palette(mpi->planes[1]);
877 #endif
878 /* to comfirm with newer lavc style */
879 mpi->qscale =pic->qscale_table;
880 mpi->qstride=pic->qstride;
881 mpi->pict_type=pic->pict_type;
882 mpi->qscale_type= pic->qscale_type;
883 mpi->fields = MP_IMGFIELD_ORDERED;
884 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
885 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
886 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
888 return mpi;
891 #if CONFIG_XVMC
892 static enum PixelFormat get_format(struct AVCodecContext * avctx,
893 const enum PixelFormat * fmt){
894 sh_video_t * sh = avctx->opaque;
895 int i;
897 if(avctx->xvmc_acceleration){
898 vd_ffmpeg_ctx *ctx = sh->context;
899 avctx->get_buffer= mc_get_buffer;
900 avctx->release_buffer= mc_release_buffer;
901 avctx->draw_horiz_band = mc_render_slice;
902 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_XVMCAcceleratedMPEG2);
903 assert(ctx->do_dr1);//these are must to!
904 assert(ctx->do_slices); //it is (vo_)ffmpeg bug if this fails
905 avctx->flags|= CODEC_FLAG_EMU_EDGE;//do i need that??!!
906 avctx->slice_flags=SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
908 for(i=0;fmt[i]!=-1;i++){
909 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_TryingPixfmt,i);
910 if( init_vo(sh,fmt[i]) >= 0)
911 return fmt[i];
913 return fmt[0];
916 static int mc_get_buffer(AVCodecContext *avctx, AVFrame *pic){
917 sh_video_t * sh = avctx->opaque;
918 vd_ffmpeg_ctx *ctx = sh->context;
919 mp_image_t* mpi=NULL;
920 struct xvmc_render_state * render;
921 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE|
922 MP_IMGFLAG_DRAW_CALLBACK;
924 // printf("vd_ffmpeg::mc_get_buffer (xvmc) %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
925 if(!avctx->xvmc_acceleration){
926 mp_msg(MSGT_DECVIDEO, MSGL_INFO, MSGTR_MPCODECS_McGetBufferShouldWorkOnlyWithXVMC);
927 assert(0);
928 exit(1);
929 // return -1;//!!fixme check error conditions
931 assert(avctx->draw_horiz_band == mc_render_slice);
932 assert(avctx->release_buffer == mc_release_buffer);
933 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
934 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_get_buffer\n");
936 if(init_vo(sh,avctx->pix_fmt) < 0){
937 mp_msg(MSGT_DECVIDEO, MSGL_WARN, MSGTR_MPCODECS_UnexpectedInitVoError);
938 exit(1);
939 // return -1;//!!fixme check error conditions
944 if(!pic->reference){
945 ctx->b_count++;
946 }else{
947 ctx->ip_count++;
948 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE;
951 mpi= mpcodecs_get_image(sh, MP_IMGTYPE_IPB,flags ,
952 avctx->width, avctx->height);
953 if(mpi==NULL){
954 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_UnrecoverableErrorRenderBuffersNotTaken);
955 assert(0);
956 exit(1);
957 // return -1;//!!fixme check error conditions in ffmpeg
960 if( (mpi->flags & MP_IMGFLAG_DIRECT) == 0){
961 mp_msg(MSGT_DECVIDEO, MSGL_ERR, MSGTR_MPCODECS_OnlyBuffersAllocatedByVoXvmcAllowed);
962 assert(0);
963 exit(1);
964 // return -1;//!!fixme check error conditions in ffmpeg
967 pic->data[0]= mpi->planes[0];
968 pic->data[1]= mpi->planes[1];
969 pic->data[2]= mpi->planes[2];
972 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
973 * lavc will check that and die with an error message, if its not true
975 pic->linesize[0]= mpi->stride[0];
976 pic->linesize[1]= mpi->stride[1];
977 pic->linesize[2]= mpi->stride[2];
979 pic->opaque = mpi;
981 if(pic->reference){
982 //I or P frame
983 pic->age= ctx->ip_age[0];
985 ctx->ip_age[0]= ctx->ip_age[1]+1;
986 ctx->ip_age[1]= 1;
987 ctx->b_age++;
988 }else{
989 //B frame
990 pic->age= ctx->b_age;
992 ctx->ip_age[0]++;
993 ctx->ip_age[1]++;
994 ctx->b_age=1;
997 pic->type= FF_BUFFER_TYPE_USER;
999 render=(struct xvmc_render_state*)mpi->priv;//same as data[2]
1000 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
1001 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_get_buffer (render=%p)\n",render);
1002 assert(render != 0);
1003 assert(render->magic == MP_XVMC_RENDER_MAGIC);
1004 render->state |= MP_XVMC_STATE_PREDICTION;
1005 return 0;
1009 static void mc_release_buffer(AVCodecContext *avctx, AVFrame *pic){
1010 mp_image_t* mpi= pic->opaque;
1011 sh_video_t * sh = avctx->opaque;
1012 vd_ffmpeg_ctx *ctx = sh->context;
1013 struct xvmc_render_state * render;
1014 int i;
1017 if(ctx->ip_count <= 2 && ctx->b_count<=1){
1018 if(mpi->flags&MP_IMGFLAG_PRESERVE)
1019 ctx->ip_count--;
1020 else
1021 ctx->b_count--;
1024 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
1025 //mark the surface as not requared for prediction
1026 render=(struct xvmc_render_state*)pic->data[2];//same as mpi->priv
1027 if( mp_msg_test(MSGT_DECVIDEO,MSGL_DBG5) )
1028 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::mc_release_buffer (render=%p)\n",render);
1029 assert(render!=NULL);
1030 assert(render->magic==MP_XVMC_RENDER_MAGIC);
1031 render->state&=~MP_XVMC_STATE_PREDICTION;
1032 for(i=0; i<4; i++){
1033 pic->data[i]= NULL;
1037 static void mc_render_slice(struct AVCodecContext *s,
1038 AVFrame *src, int offset[4],
1039 int y, int type, int height){
1040 int width= s->width;
1041 sh_video_t * sh = s->opaque;
1042 uint8_t *source[3]= {src->data[0], src->data[1], src->data[2]};
1044 assert(src->linesize[0]==0 && src->linesize[1]==0 && src->linesize[2]==0);
1045 assert(offset[0]==0 && offset[1]==0 && offset[2]==0);
1047 mpcodecs_draw_slice (sh, source, src->linesize, width, height, 0, y);
1051 #endif /* CONFIG_XVMC */