options: move -name and -title to option struct
[mplayer/greg.git] / libmpcodecs / vd_ffmpeg.c
blob8105eb8f835b72a03a039b86190a27bdf96c6e22
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>
23 #include <stdbool.h>
25 #include "talloc.h"
26 #include "config.h"
27 #include "mp_msg.h"
28 #include "options.h"
29 #include "av_opts.h"
31 #include "libavutil/common.h"
32 #include "ffmpeg_files/intreadwrite.h"
33 #include "mpbswap.h"
34 #include "fmt-conversion.h"
36 #include "vd.h"
37 #include "img_format.h"
38 #include "libmpdemux/stheader.h"
39 #include "codec-cfg.h"
40 #include "vd_ffmpeg.h"
42 static const vd_info_t info = {
43 "FFmpeg's libavcodec codec family",
44 "ffmpeg",
45 "A'rpi",
46 "A'rpi, Michael, Alex",
47 "native codecs"
50 #include "libavcodec/avcodec.h"
52 #if AVPALETTE_SIZE > 1024
53 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
54 #endif
56 #if CONFIG_XVMC
57 #include "libavcodec/xvmc.h"
58 #endif
60 int avcodec_initialized=0;
62 typedef struct {
63 AVCodecContext *avctx;
64 AVFrame *pic;
65 enum PixelFormat pix_fmt;
66 int do_slices;
67 int do_dr1;
68 int vo_initialized;
69 int best_csp;
70 int b_age;
71 int ip_age[2];
72 int qp_stat[32];
73 double qp_sum;
74 double inv_qp_sum;
75 int ip_count;
76 int b_count;
77 AVRational last_sample_aspect_ratio;
78 int lowres;
79 } vd_ffmpeg_ctx;
81 #include "m_option.h"
83 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
84 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
85 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
86 int offset[4], int y, int type, int height);
88 static enum PixelFormat get_format(struct AVCodecContext *avctx,
89 const enum PixelFormat *pix_fmt);
90 static void uninit(struct sh_video *sh);
92 const m_option_t lavc_decode_opts_conf[]={
93 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
94 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
95 OPT_FLAG_ON("gray", lavc_param.gray, 0),
96 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
97 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
98 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
99 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
100 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
101 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
102 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
103 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
104 OPT_STRING("lowres", lavc_param.lowres_str, 0),
105 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
106 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
107 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
108 OPT_INTRANGE("threads", lavc_param.threads, 0, 1, 8),
109 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
110 OPT_STRING("o", lavc_param.avopt, 0),
111 {NULL, NULL, 0, 0, 0, 0, NULL}
114 static enum AVDiscard str2AVDiscard(char *str) {
115 if (!str) return AVDISCARD_DEFAULT;
116 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
117 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
118 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
119 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
120 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
121 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
122 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
123 return AVDISCARD_DEFAULT;
126 // to set/get/query special features/parameters
127 static int control(sh_video_t *sh, int cmd, void *arg, ...){
128 vd_ffmpeg_ctx *ctx = sh->context;
129 AVCodecContext *avctx = ctx->avctx;
130 switch(cmd){
131 case VDCTRL_QUERY_FORMAT:
133 int format =(*((int *)arg));
134 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
135 // possible conversions:
136 switch(format){
137 case IMGFMT_YV12:
138 case IMGFMT_IYUV:
139 case IMGFMT_I420:
140 // "converted" using pointer/stride modification
141 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
142 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
143 break;
144 #if CONFIG_XVMC
145 case IMGFMT_XVMC_IDCT_MPEG2:
146 case IMGFMT_XVMC_MOCO_MPEG2:
147 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
148 #endif
150 return CONTROL_FALSE;
152 case VDCTRL_RESYNC_STREAM:
153 avcodec_flush_buffers(avctx);
154 return CONTROL_TRUE;
155 case VDCTRL_QUERY_UNSEEN_FRAMES:;
156 int delay = avctx->has_b_frames;
157 return delay + 10;
159 return CONTROL_UNKNOWN;
162 void init_avcodec(void)
164 if (!avcodec_initialized) {
165 avcodec_init();
166 avcodec_register_all();
167 avcodec_initialized = 1;
171 // init driver
172 static int init(sh_video_t *sh){
173 struct lavc_param *lavc_param = &sh->opts->lavc_param;
174 AVCodecContext *avctx;
175 vd_ffmpeg_ctx *ctx;
176 AVCodec *lavc_codec;
177 int lowres_w=0;
178 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
180 init_avcodec();
182 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
184 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
185 if(!lavc_codec){
186 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
187 uninit(sh);
188 return 0;
191 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
192 ctx->do_slices=1;
194 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 && lavc_codec->id != CODEC_ID_VP8)
195 ctx->do_dr1=1;
196 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
197 ctx->ip_count= ctx->b_count= 0;
199 ctx->pic = avcodec_alloc_frame();
200 ctx->avctx = avcodec_alloc_context();
201 avctx = ctx->avctx;
202 avctx->opaque = sh;
203 avctx->codec_type = CODEC_TYPE_VIDEO;
204 avctx->codec_id = lavc_codec->id;
206 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
207 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
208 ctx->do_dr1 = true;
209 ctx->do_slices = true;
210 lavc_param->threads = 1;
211 avctx->get_format = get_format;
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 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
217 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
218 "MPEG-2.\n");
219 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
220 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
221 "decoding.\n");
222 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
225 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
226 * from other threads. */
227 if (lavc_param->threads > 1) {
228 ctx->do_dr1 = false;
229 ctx->do_slices = false;
232 if(ctx->do_dr1){
233 avctx->flags|= CODEC_FLAG_EMU_EDGE;
234 avctx->get_buffer= get_buffer;
235 avctx->release_buffer= release_buffer;
236 avctx->reget_buffer= get_buffer;
239 avctx->flags|= lavc_param->bitexact;
241 avctx->coded_width = sh->disp_w;
242 avctx->coded_height= sh->disp_h;
243 avctx->workaround_bugs= lavc_param->workaround_bugs;
244 avctx->error_recognition= lavc_param->error_resilience;
245 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
246 avctx->flags2|= lavc_param->fast;
247 avctx->codec_tag= sh->format;
248 avctx->stream_codec_tag= sh->video.fccHandler;
249 avctx->idct_algo= lavc_param->idct_algo;
250 avctx->error_concealment= lavc_param->error_concealment;
251 avctx->debug= lavc_param->debug;
252 if (lavc_param->debug)
253 av_log_set_level(AV_LOG_DEBUG);
254 avctx->debug_mv= lavc_param->vismv;
255 avctx->skip_top = lavc_param->skip_top;
256 avctx->skip_bottom= lavc_param->skip_bottom;
257 if(lavc_param->lowres_str != NULL)
259 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
260 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
261 ctx->lowres = 0;
262 avctx->lowres = ctx->lowres;
264 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
265 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
266 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
268 if(lavc_param->avopt){
269 if(parse_avopts(avctx, lavc_param->avopt) < 0){
270 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
271 uninit(sh);
272 return 0;
276 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
277 switch (sh->format) {
278 case mmioFOURCC('S','V','Q','3'):
279 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
280 in the phony AVI header if demux_lavf is used. The first case is
281 handled here; the second case falls through to the next section. */
282 if (sh->ImageDesc) {
283 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
284 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
285 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
286 break;
288 /* fallthrough */
290 case mmioFOURCC('A','V','R','n'):
291 case mmioFOURCC('M','J','P','G'):
292 /* AVRn stores huffman table in AVI header */
293 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
294 MJPG fourcc :( */
295 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
296 break;
297 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
298 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
299 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
300 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
302 #if 0
304 int x;
305 uint8_t *p = avctx->extradata;
307 for (x=0; x<avctx->extradata_size; x++)
308 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
309 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
311 #endif
312 break;
314 case mmioFOURCC('R', 'V', '1', '0'):
315 case mmioFOURCC('R', 'V', '1', '3'):
316 case mmioFOURCC('R', 'V', '2', '0'):
317 case mmioFOURCC('R', 'V', '3', '0'):
318 case mmioFOURCC('R', 'V', '4', '0'):
319 if(sh->bih->biSize<sizeof(*sh->bih)+8){
320 /* only 1 packet per frame & sub_id from fourcc */
321 avctx->extradata_size= 8;
322 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
323 ((uint32_t *)avctx->extradata)[0] = 0;
324 ((uint32_t *)avctx->extradata)[1] =
325 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
326 } else {
327 /* has extra slice header (demux_rm or rm->avi streamcopy) */
328 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
329 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
330 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
332 avctx->sub_id= AV_RB32(avctx->extradata+4);
334 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
335 break;
337 default:
338 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
339 break;
340 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
341 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
342 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
343 break;
345 /* Pass palette to codec */
346 if (sh->bih && (sh->bih->biBitCount <= 8)) {
347 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
348 avctx->palctrl->palette_changed = 1;
349 if (sh->bih->biSize-sizeof(*sh->bih))
350 /* Palette size in biSize */
351 memcpy(avctx->palctrl->palette, sh->bih+1,
352 FFMIN(sh->bih->biSize-sizeof(*sh->bih), AVPALETTE_SIZE));
353 else
354 /* Palette size in biClrUsed */
355 memcpy(avctx->palctrl->palette, sh->bih+1,
356 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
359 if(sh->bih)
360 avctx->bits_per_coded_sample= sh->bih->biBitCount;
362 if(lavc_param->threads > 1)
363 avcodec_thread_init(avctx, lavc_param->threads);
364 /* open it */
365 if (avcodec_open(avctx, lavc_codec) < 0) {
366 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
367 uninit(sh);
368 return 0;
370 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
371 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
374 // uninit driver
375 static void uninit(sh_video_t *sh){
376 vd_ffmpeg_ctx *ctx = sh->context;
377 AVCodecContext *avctx = ctx->avctx;
379 if(sh->opts->lavc_param.vstats){
380 int i;
381 for(i=1; i<32; i++){
382 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
384 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
385 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
386 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
390 if (avctx) {
391 if (avctx->codec && avcodec_close(avctx) < 0)
392 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
394 av_freep(&avctx->extradata);
395 free(avctx->palctrl);
396 av_freep(&avctx->slice_offset);
399 av_freep(&avctx);
400 av_freep(&ctx->pic);
401 talloc_free(ctx);
404 static void draw_slice(struct AVCodecContext *s,
405 const AVFrame *src, int offset[4],
406 int y, int type, int height){
407 sh_video_t *sh = s->opaque;
408 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
409 int strides[MP_MAX_PLANES] = {src->linesize[0], src->linesize[1], src->linesize[2]};
410 #if 0
411 int start=0, i;
412 int width= s->width;
413 vd_ffmpeg_ctx *ctx = sh->context;
414 int skip_stride= ((width << ctx->lowres)+15)>>4;
415 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
416 int threshold= s->coded_frame->age;
417 if(s->pict_type!=B_TYPE){
418 for(i=0; i*16<width+16; i++){
419 if(i*16>=width || skip[i]>=threshold){
420 if(start==i) start++;
421 else{
422 uint8_t *src2[3]= {src[0] + start*16,
423 src[1] + start*8,
424 src[2] + start*8};
425 //printf("%2d-%2d x %d\n", start, i, y);
426 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
427 start= i+1;
431 }else
432 #endif
433 if (height < 0)
435 int i;
436 height = -height;
437 y -= height;
438 for (i = 0; i < MP_MAX_PLANES; i++)
440 strides[i] = -strides[i];
441 source[i] -= strides[i];
444 if (y < sh->disp_h) {
445 height = FFMIN(height, sh->disp_h-y);
446 mpcodecs_draw_slice (sh, source, strides, sh->disp_w, height, 0, y);
451 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
452 vd_ffmpeg_ctx *ctx = sh->context;
453 AVCodecContext *avctx = ctx->avctx;
454 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
455 int width, height;
457 width = avctx->width;
458 height = avctx->height;
460 // HACK!
461 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
462 // use dimensions from BIH to avoid black borders at the right and bottom.
463 if (sh->bih && sh->ImageDesc) {
464 width = sh->bih->biWidth >> ctx->lowres;
465 height = sh->bih->biHeight >> ctx->lowres;
468 // it is possible another vo buffers to be used after vo config()
469 // lavc reset its buffers on width/heigh change but not on aspect change!!!
470 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
471 width != sh->disp_w ||
472 height != sh->disp_h ||
473 pix_fmt != ctx->pix_fmt ||
474 !ctx->vo_initialized)
476 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
478 // Do not overwrite s->aspect on the first call, so that a container
479 // aspect if available is preferred.
480 // But set it even if the sample aspect did not change, since a
481 // resolution change can cause an aspect change even if the
482 // _sample_ aspect is unchanged.
483 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
484 sh->aspect = aspect;
485 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
486 sh->disp_w = width;
487 sh->disp_h = height;
488 ctx->pix_fmt = pix_fmt;
489 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
490 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
491 return -1;
492 ctx->vo_initialized = 1;
494 return 0;
497 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
498 sh_video_t *sh = avctx->opaque;
499 vd_ffmpeg_ctx *ctx = sh->context;
500 mp_image_t *mpi=NULL;
501 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
502 int type= MP_IMGTYPE_IPB;
503 int width= avctx->width;
504 int height= avctx->height;
505 avcodec_align_dimensions(avctx, &width, &height);
506 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
508 if (pic->buffer_hints) {
509 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
510 type = MP_IMGTYPE_TEMP;
511 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
512 flags |= MP_IMGFLAG_READABLE;
513 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
514 type = MP_IMGTYPE_STATIC;
515 flags |= MP_IMGFLAG_PRESERVE;
517 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
518 type = MP_IMGTYPE_STATIC;
519 flags |= MP_IMGFLAG_PRESERVE;
521 flags|=(!avctx->hurry_up && ctx->do_slices) ?
522 MP_IMGFLAG_DRAW_CALLBACK:0;
523 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
524 } else {
525 if(!pic->reference){
526 ctx->b_count++;
527 flags|=(!avctx->hurry_up && ctx->do_slices) ?
528 MP_IMGFLAG_DRAW_CALLBACK:0;
529 }else{
530 ctx->ip_count++;
531 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
532 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
536 if(init_vo(sh, avctx->pix_fmt) < 0){
537 avctx->release_buffer= avcodec_default_release_buffer;
538 avctx->get_buffer= avcodec_default_get_buffer;
539 return avctx->get_buffer(avctx, pic);
542 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
543 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
544 } else
545 if (!pic->buffer_hints) {
546 if(ctx->b_count>1 || ctx->ip_count>2){
547 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
549 ctx->do_dr1=0; //FIXME
550 avctx->get_buffer= avcodec_default_get_buffer;
551 return avctx->get_buffer(avctx, pic);
554 if(avctx->has_b_frames){
555 type= MP_IMGTYPE_IPB;
556 }else{
557 type= MP_IMGTYPE_IP;
559 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
562 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
563 flags |= MP_IMGFLAG_RGB_PALETTE;
564 mpi= mpcodecs_get_image(sh, type, flags, width, height);
565 if (!mpi) return -1;
567 // ok, let's see what did we get:
568 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
569 !(mpi->flags&MP_IMGFLAG_DIRECT)){
570 // nice, filter/vo likes draw_callback :)
571 avctx->draw_horiz_band= draw_slice;
572 } else
573 avctx->draw_horiz_band= NULL;
574 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
575 avctx->draw_horiz_band= draw_slice;
577 #if CONFIG_XVMC
578 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
579 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
580 avctx->draw_horiz_band= draw_slice;
581 if(!avctx->xvmc_acceleration) {
582 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
583 assert(0);
584 exit(1);
585 // return -1;//!!fixme check error conditions in ffmpeg
587 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
588 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
589 assert(0);
590 exit(1);
591 // return -1;//!!fixme check error conditions in ffmpeg
593 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
594 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
595 assert(render != 0);
596 assert(render->xvmc_id == AV_XVMC_ID);
597 render->state |= AV_XVMC_STATE_PREDICTION;
599 #endif
601 pic->data[0]= mpi->planes[0];
602 pic->data[1]= mpi->planes[1];
603 pic->data[2]= mpi->planes[2];
604 pic->data[3]= mpi->planes[3];
606 #if 0
607 assert(mpi->width >= ((width +align)&(~align)));
608 assert(mpi->height >= ((height+align)&(~align)));
609 assert(mpi->stride[0] >= mpi->width);
610 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
611 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
612 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
614 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
615 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
616 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
617 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
618 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
619 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
621 #endif
623 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
624 * lavc will check that and die with an error message, if its not true
626 pic->linesize[0]= mpi->stride[0];
627 pic->linesize[1]= mpi->stride[1];
628 pic->linesize[2]= mpi->stride[2];
629 pic->linesize[3]= mpi->stride[3];
631 pic->opaque = mpi;
632 //printf("%X\n", (int)mpi->planes[0]);
633 #if 0
634 if(mpi->flags&MP_IMGFLAG_DIRECT)
635 printf("D");
636 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
637 printf("S");
638 else
639 printf(".");
640 #endif
641 if(pic->reference){
642 pic->age= ctx->ip_age[0];
644 ctx->ip_age[0]= ctx->ip_age[1]+1;
645 ctx->ip_age[1]= 1;
646 ctx->b_age++;
647 }else{
648 pic->age= ctx->b_age;
650 ctx->ip_age[0]++;
651 ctx->ip_age[1]++;
652 ctx->b_age=1;
654 pic->type= FF_BUFFER_TYPE_USER;
656 /* The libavcodec reordered_opaque functionality is implemented by
657 * a similar copy in avcodec_default_get_buffer() and without a
658 * workaround like this it'd stop working when a custom buffer
659 * callback is used.
661 pic->reordered_opaque = avctx->reordered_opaque;
662 return 0;
665 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
666 mp_image_t *mpi= pic->opaque;
667 sh_video_t *sh = avctx->opaque;
668 vd_ffmpeg_ctx *ctx = sh->context;
669 int i;
671 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
673 if(ctx->ip_count <= 2 && ctx->b_count<=1){
674 if(mpi->flags&MP_IMGFLAG_PRESERVE)
675 ctx->ip_count--;
676 else
677 ctx->b_count--;
680 if (mpi) {
681 // Palette support: free palette buffer allocated in get_buffer
682 if (mpi->bpp == 8)
683 av_freep(&mpi->planes[1]);
684 #if CONFIG_XVMC
685 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
686 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
687 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
688 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
689 assert(render!=NULL);
690 assert(render->xvmc_id == AV_XVMC_ID);
691 render->state&=~AV_XVMC_STATE_PREDICTION;
693 #endif
694 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
695 mpi->usage_count--;
698 if(pic->type!=FF_BUFFER_TYPE_USER){
699 avcodec_default_release_buffer(avctx, pic);
700 return;
703 for(i=0; i<4; i++){
704 pic->data[i]= NULL;
706 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
709 // copypaste from demux_real.c - it should match to get it working!
710 //FIXME put into some header
711 typedef struct dp_hdr_s {
712 uint32_t chunks; // number of chunks
713 uint32_t timestamp; // timestamp from packet header
714 uint32_t len; // length of actual data
715 uint32_t chunktab; // offset to chunk offset array
716 } dp_hdr_t;
718 static av_unused void swap_palette(void *pal)
720 int i;
721 uint32_t *p = pal;
722 for (i = 0; i < AVPALETTE_COUNT; i++)
723 p[i] = le2me_32(p[i]);
726 // decode a frame
727 static struct mp_image *decode(struct sh_video *sh, void *data, int len,
728 int flags, double *reordered_pts)
730 int got_picture=0;
731 int ret;
732 vd_ffmpeg_ctx *ctx = sh->context;
733 AVFrame *pic= ctx->pic;
734 AVCodecContext *avctx = ctx->avctx;
735 struct lavc_param *lavc_param = &sh->opts->lavc_param;
736 mp_image_t *mpi=NULL;
737 int dr1= ctx->do_dr1;
738 AVPacket pkt;
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 if(ctx->vo_initialized && !(flags&3) && !dr1){
746 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
747 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
748 sh->disp_w, sh->disp_h);
749 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
750 // vd core likes slices!
751 avctx->draw_horiz_band=draw_slice;
755 if (flags & 2)
756 avctx->skip_frame = AVDISCARD_ALL;
757 else if (flags & 1)
758 avctx->skip_frame = AVDISCARD_NONREF;
759 else
760 avctx->skip_frame = 0;
762 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
763 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
764 av_init_packet(&pkt);
765 pkt.data = data;
766 pkt.size = len;
767 // HACK: make PNGs decode normally instead of as CorePNG delta frames
768 pkt.flags = PKT_FLAG_KEY;
769 // The avcodec opaque field stupidly supports only int64_t type
770 *(double *)&avctx->reordered_opaque = *reordered_pts;
771 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
772 *reordered_pts = *(double *)&pic->reordered_opaque;
774 dr1= ctx->do_dr1;
775 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
776 //printf("repeat: %d\n", pic->repeat_pict);
777 //-- vstats generation
778 while(lavc_param->vstats){ // always one time loop
779 static FILE *fvstats=NULL;
780 char filename[20];
781 static long long int all_len=0;
782 static int frame_number=0;
783 static double all_frametime=0.0;
784 AVFrame *pic= avctx->coded_frame;
785 double quality=0.0;
787 if(!fvstats) {
788 time_t today2;
789 struct tm *today;
790 today2 = time(NULL);
791 today = localtime(&today2);
792 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
793 today->tm_min, today->tm_sec);
794 fvstats = fopen(filename, "w");
795 if(!fvstats) {
796 perror("fopen");
797 lavc_param->vstats=0; // disable block
798 break;
799 /*exit(1);*/
803 // average MB quantizer
805 int x, y;
806 int w = ((avctx->width << ctx->lowres)+15) >> 4;
807 int h = ((avctx->height << ctx->lowres)+15) >> 4;
808 int8_t *q = pic->qscale_table;
809 for(y = 0; y < h; y++) {
810 for(x = 0; x < w; x++)
811 quality += (double)*(q+x);
812 q += pic->qstride;
814 quality /= w * h;
817 all_len+=len;
818 all_frametime+=sh->frametime;
819 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
820 ++frame_number, quality, len, (double)all_len/1024);
821 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
822 all_frametime, (double)(len*8)/sh->frametime/1000.0,
823 (double)(all_len*8)/all_frametime/1000.0);
824 switch(pic->pict_type){
825 case FF_I_TYPE:
826 fprintf(fvstats, "type= I\n");
827 break;
828 case FF_P_TYPE:
829 fprintf(fvstats, "type= P\n");
830 break;
831 case FF_S_TYPE:
832 fprintf(fvstats, "type= S\n");
833 break;
834 case FF_B_TYPE:
835 fprintf(fvstats, "type= B\n");
836 break;
837 default:
838 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
839 break;
842 ctx->qp_stat[(int)(quality+0.5)]++;
843 ctx->qp_sum += quality;
844 ctx->inv_qp_sum += 1.0/(double)quality;
846 break;
848 //--
850 if(!got_picture) return NULL; // skipped image
852 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
854 if(dr1 && pic->opaque){
855 mpi= (mp_image_t *)pic->opaque;
858 if(!mpi)
859 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
860 avctx->width, avctx->height);
861 if(!mpi){ // temporary!
862 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
863 return NULL;
866 if(!dr1){
867 mpi->planes[0]=pic->data[0];
868 mpi->planes[1]=pic->data[1];
869 mpi->planes[2]=pic->data[2];
870 mpi->planes[3]=pic->data[3];
871 mpi->stride[0]=pic->linesize[0];
872 mpi->stride[1]=pic->linesize[1];
873 mpi->stride[2]=pic->linesize[2];
874 mpi->stride[3]=pic->linesize[3];
877 if (!mpi->planes[0])
878 return NULL;
880 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
881 // we have 422p but user wants 420p
882 mpi->stride[1]*=2;
883 mpi->stride[2]*=2;
886 #if HAVE_BIGENDIAN
887 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
888 if (mpi->bpp == 8)
889 swap_palette(mpi->planes[1]);
890 #endif
891 /* to comfirm with newer lavc style */
892 mpi->qscale =pic->qscale_table;
893 mpi->qstride=pic->qstride;
894 mpi->pict_type=pic->pict_type;
895 mpi->qscale_type= pic->qscale_type;
896 mpi->fields = MP_IMGFIELD_ORDERED;
897 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
898 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
899 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
901 return mpi;
904 static enum PixelFormat get_format(struct AVCodecContext *avctx,
905 const enum PixelFormat *fmt){
906 enum PixelFormat selected_format;
907 int imgfmt;
908 sh_video_t *sh = avctx->opaque;
909 int i;
911 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
912 imgfmt = pixfmt2imgfmt(fmt[i]);
913 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
914 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
915 if(init_vo(sh, fmt[i]) >= 0) {
916 break;
919 selected_format = fmt[i];
920 return selected_format;
923 const struct vd_functions mpcodecs_vd_ffmpeg = {
924 .info = &info,
925 .init = init,
926 .uninit = uninit,
927 .control = control,
928 .decode2 = decode