vd_ffmpeg: Set avctx->coded_width/coded_height instead of width/height
[mplayer/glamo.git] / libmpcodecs / vd_ffmpeg.c
blob0101c5d39df1900162ae7c7ce14d108773c7290b
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"
41 static const vd_info_t info = {
42 "FFmpeg's libavcodec codec family",
43 "ffmpeg",
44 "A'rpi",
45 "A'rpi, Michael, Alex",
46 "native codecs"
49 #include "libavcodec/avcodec.h"
51 #if AVPALETTE_SIZE > 1024
52 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
53 #endif
55 #if CONFIG_XVMC
56 #include "libavcodec/xvmc.h"
57 #endif
59 int avcodec_initialized=0;
61 typedef struct {
62 AVCodecContext *avctx;
63 AVFrame *pic;
64 enum PixelFormat pix_fmt;
65 int do_slices;
66 int do_dr1;
67 int vo_initialized;
68 int best_csp;
69 int b_age;
70 int ip_age[2];
71 int qp_stat[32];
72 double qp_sum;
73 double inv_qp_sum;
74 int ip_count;
75 int b_count;
76 AVRational last_sample_aspect_ratio;
77 int lowres;
78 } vd_ffmpeg_ctx;
80 #include "m_option.h"
82 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
83 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
84 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
85 int offset[4], int y, int type, int height);
87 static enum PixelFormat get_format(struct AVCodecContext *avctx,
88 const enum PixelFormat *pix_fmt);
89 static void uninit(struct sh_video *sh);
91 const m_option_t lavc_decode_opts_conf[]={
92 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
93 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
94 OPT_FLAG_ON("gray", lavc_param.gray, 0),
95 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
96 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
97 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
98 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
99 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
100 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
101 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
102 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
103 OPT_STRING("lowres", lavc_param.lowres_str, 0),
104 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
105 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
106 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
107 OPT_INTRANGE("threads", lavc_param.threads, 0, 1, 8),
108 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
109 OPT_STRING("o", lavc_param.avopt, 0),
110 {NULL, NULL, 0, 0, 0, 0, NULL}
113 static enum AVDiscard str2AVDiscard(char *str) {
114 if (!str) return AVDISCARD_DEFAULT;
115 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
116 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
117 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
118 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
119 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
120 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
121 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
122 return AVDISCARD_DEFAULT;
125 // to set/get/query special features/parameters
126 static int control(sh_video_t *sh, int cmd, void *arg, ...){
127 vd_ffmpeg_ctx *ctx = sh->context;
128 AVCodecContext *avctx = ctx->avctx;
129 switch(cmd){
130 case VDCTRL_QUERY_FORMAT:
132 int format =(*((int *)arg));
133 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
134 // possible conversions:
135 switch(format){
136 case IMGFMT_YV12:
137 case IMGFMT_IYUV:
138 case IMGFMT_I420:
139 // "converted" using pointer/stride modification
140 if(avctx->pix_fmt==PIX_FMT_YUV420P) return CONTROL_TRUE;// u/v swap
141 if(avctx->pix_fmt==PIX_FMT_YUV422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
142 break;
143 #if CONFIG_XVMC
144 case IMGFMT_XVMC_IDCT_MPEG2:
145 case IMGFMT_XVMC_MOCO_MPEG2:
146 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
147 #endif
149 return CONTROL_FALSE;
151 case VDCTRL_RESYNC_STREAM:
152 avcodec_flush_buffers(avctx);
153 return CONTROL_TRUE;
154 case VDCTRL_QUERY_UNSEEN_FRAMES:;
155 int delay = avctx->has_b_frames;
156 return delay + 10;
158 return CONTROL_UNKNOWN;
161 // init driver
162 static int init(sh_video_t *sh){
163 struct lavc_param *lavc_param = &sh->opts->lavc_param;
164 AVCodecContext *avctx;
165 vd_ffmpeg_ctx *ctx;
166 AVCodec *lavc_codec;
167 int lowres_w=0;
168 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
170 if(!avcodec_initialized){
171 avcodec_init();
172 avcodec_register_all();
173 avcodec_initialized=1;
176 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
178 ctx->last_sample_aspect_ratio = (AVRational){0, 1};
180 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
181 if(!lavc_codec){
182 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
183 uninit(sh);
184 return 0;
187 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
188 ctx->do_slices=1;
190 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)
191 ctx->do_dr1=1;
192 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
193 ctx->ip_count= ctx->b_count= 0;
195 ctx->pic = avcodec_alloc_frame();
196 ctx->avctx = avcodec_alloc_context();
197 avctx = ctx->avctx;
198 avctx->opaque = sh;
199 avctx->codec_type = CODEC_TYPE_VIDEO;
200 avctx->codec_id = lavc_codec->id;
202 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
203 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
204 ctx->do_dr1 = true;
205 ctx->do_slices = true;
206 lavc_param->threads = 1;
207 avctx->get_format = get_format;
208 avctx->get_buffer = get_buffer;
209 avctx->release_buffer = release_buffer;
210 avctx->reget_buffer = get_buffer;
211 avctx->draw_horiz_band = draw_slice;
212 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
213 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
214 "MPEG-2.\n");
215 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
216 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
217 "decoding.\n");
218 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
221 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
222 * from other threads. */
223 if (lavc_param->threads > 1) {
224 ctx->do_dr1 = false;
225 ctx->do_slices = false;
228 if(ctx->do_dr1){
229 avctx->flags|= CODEC_FLAG_EMU_EDGE;
230 avctx->get_buffer= get_buffer;
231 avctx->release_buffer= release_buffer;
232 avctx->reget_buffer= get_buffer;
235 avctx->flags|= lavc_param->bitexact;
237 avctx->coded_width = sh->disp_w;
238 avctx->coded_height= sh->disp_h;
239 avctx->workaround_bugs= lavc_param->workaround_bugs;
240 avctx->error_recognition= lavc_param->error_resilience;
241 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
242 avctx->flags2|= lavc_param->fast;
243 avctx->codec_tag= sh->format;
244 avctx->stream_codec_tag= sh->video.fccHandler;
245 avctx->idct_algo= lavc_param->idct_algo;
246 avctx->error_concealment= lavc_param->error_concealment;
247 avctx->debug= lavc_param->debug;
248 if (lavc_param->debug)
249 av_log_set_level(AV_LOG_DEBUG);
250 avctx->debug_mv= lavc_param->vismv;
251 avctx->skip_top = lavc_param->skip_top;
252 avctx->skip_bottom= lavc_param->skip_bottom;
253 if(lavc_param->lowres_str != NULL)
255 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
256 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
257 ctx->lowres = 0;
258 avctx->lowres = ctx->lowres;
260 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
261 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
262 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
264 if(lavc_param->avopt){
265 if(parse_avopts(avctx, lavc_param->avopt) < 0){
266 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
267 uninit(sh);
268 return 0;
272 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
273 switch (sh->format) {
274 case mmioFOURCC('S','V','Q','3'):
275 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
276 in the phony AVI header if demux_lavf is used. The first case is
277 handled here; the second case falls through to the next section. */
278 if (sh->ImageDesc) {
279 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
280 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
281 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
282 break;
284 /* fallthrough */
286 case mmioFOURCC('A','V','R','n'):
287 case mmioFOURCC('M','J','P','G'):
288 /* AVRn stores huffman table in AVI header */
289 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
290 MJPG fourcc :( */
291 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
292 break;
293 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
294 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
295 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
296 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
298 #if 0
300 int x;
301 uint8_t *p = avctx->extradata;
303 for (x=0; x<avctx->extradata_size; x++)
304 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
305 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
307 #endif
308 break;
310 case mmioFOURCC('R', 'V', '1', '0'):
311 case mmioFOURCC('R', 'V', '1', '3'):
312 case mmioFOURCC('R', 'V', '2', '0'):
313 case mmioFOURCC('R', 'V', '3', '0'):
314 case mmioFOURCC('R', 'V', '4', '0'):
315 if(sh->bih->biSize<sizeof(*sh->bih)+8){
316 /* only 1 packet per frame & sub_id from fourcc */
317 avctx->extradata_size= 8;
318 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
319 ((uint32_t *)avctx->extradata)[0] = 0;
320 ((uint32_t *)avctx->extradata)[1] =
321 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
322 } else {
323 /* has extra slice header (demux_rm or rm->avi streamcopy) */
324 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
325 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
326 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
328 avctx->sub_id= AV_RB32(avctx->extradata+4);
330 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
331 break;
333 default:
334 if (!sh->bih || sh->bih->biSize <= sizeof(BITMAPINFOHEADER))
335 break;
336 avctx->extradata_size = sh->bih->biSize-sizeof(BITMAPINFOHEADER);
337 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
338 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
339 break;
341 /* Pass palette to codec */
342 if (sh->bih && (sh->bih->biBitCount <= 8)) {
343 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
344 avctx->palctrl->palette_changed = 1;
345 if (sh->bih->biSize-sizeof(BITMAPINFOHEADER))
346 /* Palette size in biSize */
347 memcpy(avctx->palctrl->palette, sh->bih+1,
348 FFMIN(sh->bih->biSize-sizeof(BITMAPINFOHEADER), AVPALETTE_SIZE));
349 else
350 /* Palette size in biClrUsed */
351 memcpy(avctx->palctrl->palette, sh->bih+1,
352 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
355 if(sh->bih)
356 avctx->bits_per_coded_sample= sh->bih->biBitCount;
358 if(lavc_param->threads > 1)
359 avcodec_thread_init(avctx, lavc_param->threads);
360 /* open it */
361 if (avcodec_open(avctx, lavc_codec) < 0) {
362 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
363 uninit(sh);
364 return 0;
366 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
367 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
370 // uninit driver
371 static void uninit(sh_video_t *sh){
372 vd_ffmpeg_ctx *ctx = sh->context;
373 AVCodecContext *avctx = ctx->avctx;
375 if(sh->opts->lavc_param.vstats){
376 int i;
377 for(i=1; i<32; i++){
378 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
380 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
381 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
382 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
386 if (avctx) {
387 if (avctx->codec && avcodec_close(avctx) < 0)
388 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
390 av_freep(&avctx->extradata);
391 free(avctx->palctrl);
392 av_freep(&avctx->slice_offset);
395 av_freep(&avctx);
396 av_freep(&ctx->pic);
397 talloc_free(ctx);
400 static void draw_slice(struct AVCodecContext *s,
401 const AVFrame *src, int offset[4],
402 int y, int type, int height){
403 sh_video_t *sh = s->opaque;
404 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
405 int strides[MP_MAX_PLANES] = {src->linesize[0], src->linesize[1], src->linesize[2]};
406 #if 0
407 int start=0, i;
408 int width= s->width;
409 vd_ffmpeg_ctx *ctx = sh->context;
410 int skip_stride= ((width << ctx->lowres)+15)>>4;
411 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
412 int threshold= s->coded_frame->age;
413 if(s->pict_type!=B_TYPE){
414 for(i=0; i*16<width+16; i++){
415 if(i*16>=width || skip[i]>=threshold){
416 if(start==i) start++;
417 else{
418 uint8_t *src2[3]= {src[0] + start*16,
419 src[1] + start*8,
420 src[2] + start*8};
421 //printf("%2d-%2d x %d\n", start, i, y);
422 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
423 start= i+1;
427 }else
428 #endif
429 if (height < 0)
431 int i;
432 height = -height;
433 y -= height;
434 for (i = 0; i < MP_MAX_PLANES; i++)
436 strides[i] = -strides[i];
437 source[i] -= strides[i];
440 if (y < sh->disp_h) {
441 height = FFMIN(height, sh->disp_h-y);
442 mpcodecs_draw_slice (sh, source, strides, sh->disp_w, height, 0, y);
447 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
448 vd_ffmpeg_ctx *ctx = sh->context;
449 AVCodecContext *avctx = ctx->avctx;
450 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
451 int width, height;
453 width = avctx->width;
454 height = avctx->height;
456 // HACK!
457 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
458 // use dimensions from BIH to avoid black borders at the right and bottom.
459 if (sh->bih && sh->ImageDesc) {
460 width = sh->bih->biWidth >> ctx->lowres;
461 height = sh->bih->biHeight >> ctx->lowres;
464 // it is possible another vo buffers to be used after vo config()
465 // lavc reset its buffers on width/heigh change but not on aspect change!!!
466 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
467 width != sh->disp_w ||
468 height != sh->disp_h ||
469 pix_fmt != ctx->pix_fmt ||
470 !ctx->vo_initialized)
472 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
473 if (sh->aspect == 0 ||
474 av_cmp_q(avctx->sample_aspect_ratio,
475 ctx->last_sample_aspect_ratio))
476 sh->aspect = aspect;
477 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
478 sh->disp_w = width;
479 sh->disp_h = height;
480 ctx->pix_fmt = pix_fmt;
481 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
482 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
483 return -1;
484 ctx->vo_initialized = 1;
486 return 0;
489 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
490 sh_video_t *sh = avctx->opaque;
491 vd_ffmpeg_ctx *ctx = sh->context;
492 mp_image_t *mpi=NULL;
493 int flags= MP_IMGFLAG_ACCEPT_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
494 int type= MP_IMGTYPE_IPB;
495 int width= avctx->width;
496 int height= avctx->height;
497 avcodec_align_dimensions(avctx, &width, &height);
498 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
500 if (pic->buffer_hints) {
501 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
502 type = MP_IMGTYPE_TEMP;
503 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
504 flags |= MP_IMGFLAG_READABLE;
505 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
506 type = MP_IMGTYPE_STATIC;
507 flags |= MP_IMGFLAG_PRESERVE;
509 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
510 type = MP_IMGTYPE_STATIC;
511 flags |= MP_IMGFLAG_PRESERVE;
513 flags|=(!avctx->hurry_up && ctx->do_slices) ?
514 MP_IMGFLAG_DRAW_CALLBACK:0;
515 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
516 } else {
517 if(!pic->reference){
518 ctx->b_count++;
519 flags|=(!avctx->hurry_up && ctx->do_slices) ?
520 MP_IMGFLAG_DRAW_CALLBACK:0;
521 }else{
522 ctx->ip_count++;
523 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
524 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
528 if(init_vo(sh, avctx->pix_fmt) < 0){
529 avctx->release_buffer= avcodec_default_release_buffer;
530 avctx->get_buffer= avcodec_default_get_buffer;
531 return avctx->get_buffer(avctx, pic);
534 if (IMGFMT_IS_XVMC(ctx->best_csp) || IMGFMT_IS_VDPAU(ctx->best_csp)) {
535 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
536 } else
537 if (!pic->buffer_hints) {
538 if(ctx->b_count>1 || ctx->ip_count>2){
539 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
541 ctx->do_dr1=0; //FIXME
542 avctx->get_buffer= avcodec_default_get_buffer;
543 return avctx->get_buffer(avctx, pic);
546 if(avctx->has_b_frames){
547 type= MP_IMGTYPE_IPB;
548 }else{
549 type= MP_IMGTYPE_IP;
551 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
554 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
555 flags |= MP_IMGFLAG_RGB_PALETTE;
556 mpi= mpcodecs_get_image(sh, type, flags, width, height);
557 if (!mpi) return -1;
559 // ok, let's see what did we get:
560 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
561 !(mpi->flags&MP_IMGFLAG_DIRECT)){
562 // nice, filter/vo likes draw_callback :)
563 avctx->draw_horiz_band= draw_slice;
564 } else
565 avctx->draw_horiz_band= NULL;
566 if(IMGFMT_IS_VDPAU(mpi->imgfmt)) {
567 avctx->draw_horiz_band= draw_slice;
569 #if CONFIG_XVMC
570 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
571 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
572 avctx->draw_horiz_band= draw_slice;
573 if(!avctx->xvmc_acceleration) {
574 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
575 assert(0);
576 exit(1);
577 // return -1;//!!fixme check error conditions in ffmpeg
579 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
580 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
581 assert(0);
582 exit(1);
583 // return -1;//!!fixme check error conditions in ffmpeg
585 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
586 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
587 assert(render != 0);
588 assert(render->xvmc_id == AV_XVMC_ID);
589 render->state |= AV_XVMC_STATE_PREDICTION;
591 #endif
593 pic->data[0]= mpi->planes[0];
594 pic->data[1]= mpi->planes[1];
595 pic->data[2]= mpi->planes[2];
596 pic->data[3]= mpi->planes[3];
598 #if 0
599 assert(mpi->width >= ((width +align)&(~align)));
600 assert(mpi->height >= ((height+align)&(~align)));
601 assert(mpi->stride[0] >= mpi->width);
602 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
603 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
604 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
606 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
607 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
608 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
609 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
610 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
611 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
613 #endif
615 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
616 * lavc will check that and die with an error message, if its not true
618 pic->linesize[0]= mpi->stride[0];
619 pic->linesize[1]= mpi->stride[1];
620 pic->linesize[2]= mpi->stride[2];
621 pic->linesize[3]= mpi->stride[3];
623 pic->opaque = mpi;
624 //printf("%X\n", (int)mpi->planes[0]);
625 #if 0
626 if(mpi->flags&MP_IMGFLAG_DIRECT)
627 printf("D");
628 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
629 printf("S");
630 else
631 printf(".");
632 #endif
633 if(pic->reference){
634 pic->age= ctx->ip_age[0];
636 ctx->ip_age[0]= ctx->ip_age[1]+1;
637 ctx->ip_age[1]= 1;
638 ctx->b_age++;
639 }else{
640 pic->age= ctx->b_age;
642 ctx->ip_age[0]++;
643 ctx->ip_age[1]++;
644 ctx->b_age=1;
646 pic->type= FF_BUFFER_TYPE_USER;
648 /* The libavcodec reordered_opaque functionality is implemented by
649 * a similar copy in avcodec_default_get_buffer() and without a
650 * workaround like this it'd stop working when a custom buffer
651 * callback is used.
653 pic->reordered_opaque = avctx->reordered_opaque;
654 return 0;
657 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
658 mp_image_t *mpi= pic->opaque;
659 sh_video_t *sh = avctx->opaque;
660 vd_ffmpeg_ctx *ctx = sh->context;
661 int i;
663 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
665 if(ctx->ip_count <= 2 && ctx->b_count<=1){
666 if(mpi->flags&MP_IMGFLAG_PRESERVE)
667 ctx->ip_count--;
668 else
669 ctx->b_count--;
672 if (mpi) {
673 // Palette support: free palette buffer allocated in get_buffer
674 if (mpi->bpp == 8)
675 av_freep(&mpi->planes[1]);
676 #if CONFIG_XVMC
677 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
678 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
679 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
680 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
681 assert(render!=NULL);
682 assert(render->xvmc_id == AV_XVMC_ID);
683 render->state&=~AV_XVMC_STATE_PREDICTION;
685 #endif
686 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
687 mpi->usage_count--;
690 if(pic->type!=FF_BUFFER_TYPE_USER){
691 avcodec_default_release_buffer(avctx, pic);
692 return;
695 for(i=0; i<4; i++){
696 pic->data[i]= NULL;
698 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
701 // copypaste from demux_real.c - it should match to get it working!
702 //FIXME put into some header
703 typedef struct dp_hdr_s {
704 uint32_t chunks; // number of chunks
705 uint32_t timestamp; // timestamp from packet header
706 uint32_t len; // length of actual data
707 uint32_t chunktab; // offset to chunk offset array
708 } dp_hdr_t;
710 static av_unused void swap_palette(void *pal)
712 int i;
713 uint32_t *p = pal;
714 for (i = 0; i < AVPALETTE_COUNT; i++)
715 p[i] = le2me_32(p[i]);
718 // decode a frame
719 static struct mp_image *decode(struct sh_video *sh, void *data, int len,
720 int flags, double *reordered_pts)
722 int got_picture=0;
723 int ret;
724 vd_ffmpeg_ctx *ctx = sh->context;
725 AVFrame *pic= ctx->pic;
726 AVCodecContext *avctx = ctx->avctx;
727 struct lavc_param *lavc_param = &sh->opts->lavc_param;
728 mp_image_t *mpi=NULL;
729 int dr1= ctx->do_dr1;
730 AVPacket pkt;
732 if(len<=0) return NULL; // skipped frame
734 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
735 if (!dr1)
736 avctx->draw_horiz_band=NULL;
737 if(ctx->vo_initialized && !(flags&3) && !dr1){
738 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
739 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
740 sh->disp_w, sh->disp_h);
741 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
742 // vd core likes slices!
743 avctx->draw_horiz_band=draw_slice;
747 if (flags & 2)
748 avctx->skip_frame = AVDISCARD_ALL;
749 else if (flags & 1)
750 avctx->skip_frame = AVDISCARD_NONREF;
751 else
752 avctx->skip_frame = 0;
754 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
755 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
756 av_init_packet(&pkt);
757 pkt.data = data;
758 pkt.size = len;
759 // HACK: make PNGs decode normally instead of as CorePNG delta frames
760 pkt.flags = PKT_FLAG_KEY;
761 // The avcodec opaque field stupidly supports only int64_t type
762 *(double *)&avctx->reordered_opaque = *reordered_pts;
763 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
764 *reordered_pts = *(double *)&pic->reordered_opaque;
766 dr1= ctx->do_dr1;
767 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
768 //printf("repeat: %d\n", pic->repeat_pict);
769 //-- vstats generation
770 while(lavc_param->vstats){ // always one time loop
771 static FILE *fvstats=NULL;
772 char filename[20];
773 static long long int all_len=0;
774 static int frame_number=0;
775 static double all_frametime=0.0;
776 AVFrame *pic= avctx->coded_frame;
777 double quality=0.0;
779 if(!fvstats) {
780 time_t today2;
781 struct tm *today;
782 today2 = time(NULL);
783 today = localtime(&today2);
784 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
785 today->tm_min, today->tm_sec);
786 fvstats = fopen(filename, "w");
787 if(!fvstats) {
788 perror("fopen");
789 lavc_param->vstats=0; // disable block
790 break;
791 /*exit(1);*/
795 // average MB quantizer
797 int x, y;
798 int w = ((avctx->width << ctx->lowres)+15) >> 4;
799 int h = ((avctx->height << ctx->lowres)+15) >> 4;
800 int8_t *q = pic->qscale_table;
801 for(y = 0; y < h; y++) {
802 for(x = 0; x < w; x++)
803 quality += (double)*(q+x);
804 q += pic->qstride;
806 quality /= w * h;
809 all_len+=len;
810 all_frametime+=sh->frametime;
811 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
812 ++frame_number, quality, len, (double)all_len/1024);
813 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
814 all_frametime, (double)(len*8)/sh->frametime/1000.0,
815 (double)(all_len*8)/all_frametime/1000.0);
816 switch(pic->pict_type){
817 case FF_I_TYPE:
818 fprintf(fvstats, "type= I\n");
819 break;
820 case FF_P_TYPE:
821 fprintf(fvstats, "type= P\n");
822 break;
823 case FF_S_TYPE:
824 fprintf(fvstats, "type= S\n");
825 break;
826 case FF_B_TYPE:
827 fprintf(fvstats, "type= B\n");
828 break;
829 default:
830 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
831 break;
834 ctx->qp_stat[(int)(quality+0.5)]++;
835 ctx->qp_sum += quality;
836 ctx->inv_qp_sum += 1.0/(double)quality;
838 break;
840 //--
842 if(!got_picture) return NULL; // skipped image
844 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
846 if(dr1 && pic->opaque){
847 mpi= (mp_image_t *)pic->opaque;
850 if(!mpi)
851 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
852 avctx->width, avctx->height);
853 if(!mpi){ // temporary!
854 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
855 return NULL;
858 if(!dr1){
859 mpi->planes[0]=pic->data[0];
860 mpi->planes[1]=pic->data[1];
861 mpi->planes[2]=pic->data[2];
862 mpi->planes[3]=pic->data[3];
863 mpi->stride[0]=pic->linesize[0];
864 mpi->stride[1]=pic->linesize[1];
865 mpi->stride[2]=pic->linesize[2];
866 mpi->stride[3]=pic->linesize[3];
869 if (!mpi->planes[0])
870 return NULL;
872 if(avctx->pix_fmt==PIX_FMT_YUV422P && mpi->chroma_y_shift==1){
873 // we have 422p but user wants 420p
874 mpi->stride[1]*=2;
875 mpi->stride[2]*=2;
878 #if HAVE_BIGENDIAN
879 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
880 if (mpi->bpp == 8)
881 swap_palette(mpi->planes[1]);
882 #endif
883 /* to comfirm with newer lavc style */
884 mpi->qscale =pic->qscale_table;
885 mpi->qstride=pic->qstride;
886 mpi->pict_type=pic->pict_type;
887 mpi->qscale_type= pic->qscale_type;
888 mpi->fields = MP_IMGFIELD_ORDERED;
889 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
890 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
891 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
893 return mpi;
896 static enum PixelFormat get_format(struct AVCodecContext *avctx,
897 const enum PixelFormat *fmt){
898 enum PixelFormat selected_format;
899 int imgfmt;
900 sh_video_t *sh = avctx->opaque;
901 int i;
903 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
904 imgfmt = pixfmt2imgfmt(fmt[i]);
905 if(!IMGFMT_IS_XVMC(imgfmt) && !IMGFMT_IS_VDPAU(imgfmt)) continue;
906 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
907 if(init_vo(sh, fmt[i]) >= 0) {
908 break;
911 selected_format = fmt[i];
912 return selected_format;
915 const struct vd_functions mpcodecs_vd_ffmpeg = {
916 .info = &info,
917 .init = init,
918 .uninit = uninit,
919 .control = control,
920 .decode2 = decode