cleanup: shut up more warnings
[mplayer/greg.git] / libmpcodecs / vd_ffmpeg.c
bloba5c21a2e623b5e3c6119b6faa04e7e6efcef0602
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 "osdep/numcores.h"
41 #include "vd_ffmpeg.h"
43 static const vd_info_t info = {
44 "FFmpeg's libavcodec codec family",
45 "ffmpeg",
46 "A'rpi",
47 "A'rpi, Michael, Alex",
48 "native codecs"
51 #include "libavcodec/avcodec.h"
53 #if AVPALETTE_SIZE > 1024
54 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
55 #endif
57 #if CONFIG_XVMC
58 #include "libavcodec/xvmc.h"
59 #endif
61 int avcodec_initialized=0;
63 typedef struct {
64 AVCodecContext *avctx;
65 AVFrame *pic;
66 enum PixelFormat pix_fmt;
67 int do_slices;
68 int do_dr1;
69 int vo_initialized;
70 int best_csp;
71 int b_age;
72 int ip_age[2];
73 int qp_stat[32];
74 double qp_sum;
75 double inv_qp_sum;
76 int ip_count;
77 int b_count;
78 AVRational last_sample_aspect_ratio;
79 int lowres;
80 } vd_ffmpeg_ctx;
82 #include "m_option.h"
84 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
85 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
86 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
87 int offset[4], int y, int type, int height);
89 static enum PixelFormat get_format(struct AVCodecContext *avctx,
90 const enum PixelFormat *pix_fmt);
91 static void uninit(struct sh_video *sh);
93 const m_option_t lavc_decode_opts_conf[]={
94 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
95 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
96 OPT_FLAG_ON("gray", lavc_param.gray, 0),
97 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
98 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
99 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
100 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
101 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
102 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
103 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
104 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
105 OPT_STRING("lowres", lavc_param.lowres_str, 0),
106 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
107 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
108 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
109 OPT_INTRANGE("threads", lavc_param.threads, 0, 0, 16),
110 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
111 OPT_STRING("o", lavc_param.avopt, 0),
112 {NULL, NULL, 0, 0, 0, 0, NULL}
115 static enum AVDiscard str2AVDiscard(char *str) {
116 if (!str) return AVDISCARD_DEFAULT;
117 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
118 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
119 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
120 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
121 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
122 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
123 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
124 return AVDISCARD_DEFAULT;
127 // to set/get/query special features/parameters
128 static int control(sh_video_t *sh, int cmd, void *arg, ...){
129 vd_ffmpeg_ctx *ctx = sh->context;
130 AVCodecContext *avctx = ctx->avctx;
131 switch(cmd){
132 case VDCTRL_QUERY_FORMAT:
134 int format =(*((int *)arg));
135 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
136 // possible conversions:
137 switch(format){
138 case IMGFMT_YV12:
139 case IMGFMT_IYUV:
140 case IMGFMT_I420:
141 // "converted" using pointer/stride modification
142 if(ctx->best_csp == IMGFMT_YV12) return CONTROL_TRUE;// u/v swap
143 if(ctx->best_csp == IMGFMT_422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
144 break;
145 #if CONFIG_XVMC
146 case IMGFMT_XVMC_IDCT_MPEG2:
147 case IMGFMT_XVMC_MOCO_MPEG2:
148 if(avctx->pix_fmt==PIX_FMT_XVMC_MPEG2_IDCT) return CONTROL_TRUE;
149 #endif
151 return CONTROL_FALSE;
153 case VDCTRL_RESYNC_STREAM:
154 avcodec_flush_buffers(avctx);
155 return CONTROL_TRUE;
156 case VDCTRL_QUERY_UNSEEN_FRAMES:;
157 int delay = avctx->has_b_frames;
158 return delay + 10;
160 return CONTROL_UNKNOWN;
163 void init_avcodec(void)
165 if (!avcodec_initialized) {
166 avcodec_init();
167 avcodec_register_all();
168 avcodec_initialized = 1;
172 // init driver
173 static int init(sh_video_t *sh){
174 struct lavc_param *lavc_param = &sh->opts->lavc_param;
175 AVCodecContext *avctx;
176 vd_ffmpeg_ctx *ctx;
177 AVCodec *lavc_codec;
178 int lowres_w=0;
179 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
181 init_avcodec();
183 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
185 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
186 if(!lavc_codec){
187 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
188 uninit(sh);
189 return 0;
192 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
193 ctx->do_slices=1;
195 if(lavc_codec->capabilities&CODEC_CAP_DR1 && !do_vis_debug
196 && lavc_codec->id != CODEC_ID_H264
197 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO
198 && lavc_codec->id != CODEC_ID_ROQ && lavc_codec->id != CODEC_ID_VP8
199 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 108, 0)
200 && lavc_codec->id != CODEC_ID_LAGARITH
201 #endif
203 ctx->do_dr1=1;
204 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
205 ctx->ip_count= ctx->b_count= 0;
207 ctx->pic = avcodec_alloc_frame();
208 ctx->avctx = avcodec_alloc_context();
209 avctx = ctx->avctx;
210 avctx->opaque = sh;
211 avctx->codec_type = AVMEDIA_TYPE_VIDEO;
212 avctx->codec_id = lavc_codec->id;
214 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
215 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
216 ctx->do_dr1 = true;
217 ctx->do_slices = true;
218 lavc_param->threads = 1;
219 avctx->get_format = get_format;
220 avctx->get_buffer = get_buffer;
221 avctx->release_buffer = release_buffer;
222 avctx->reget_buffer = get_buffer;
223 avctx->draw_horiz_band = draw_slice;
224 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
225 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
226 "MPEG-2.\n");
227 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
228 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
229 "decoding.\n");
230 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
233 if (lavc_param->threads == 0) {
234 int threads = default_thread_count();
235 if (threads < 1) {
236 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Could not determine "
237 "thread count to use, defaulting to 1.\n");
238 threads = 1;
240 threads = FFMIN(threads, 16);
241 lavc_param->threads = threads;
243 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
244 * from other threads. */
245 if (lavc_param->threads > 1) {
246 ctx->do_dr1 = false;
247 ctx->do_slices = false;
248 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "Asking decoder to use "
249 "%d threads if supported.\n", lavc_param->threads);
252 if(ctx->do_dr1){
253 avctx->flags|= CODEC_FLAG_EMU_EDGE;
254 avctx->get_buffer= get_buffer;
255 avctx->release_buffer= release_buffer;
256 avctx->reget_buffer= get_buffer;
259 avctx->flags|= lavc_param->bitexact;
261 avctx->coded_width = sh->disp_w;
262 avctx->coded_height= sh->disp_h;
263 avctx->workaround_bugs= lavc_param->workaround_bugs;
264 avctx->error_recognition= lavc_param->error_resilience;
265 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
266 avctx->flags2|= lavc_param->fast;
267 avctx->codec_tag= sh->format;
268 avctx->stream_codec_tag= sh->video.fccHandler;
269 avctx->idct_algo= lavc_param->idct_algo;
270 avctx->error_concealment= lavc_param->error_concealment;
271 avctx->debug= lavc_param->debug;
272 if (lavc_param->debug)
273 av_log_set_level(AV_LOG_DEBUG);
274 avctx->debug_mv= lavc_param->vismv;
275 avctx->skip_top = lavc_param->skip_top;
276 avctx->skip_bottom= lavc_param->skip_bottom;
277 if(lavc_param->lowres_str != NULL)
279 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
280 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
281 ctx->lowres = 0;
282 avctx->lowres = ctx->lowres;
284 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
285 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
286 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
288 if(lavc_param->avopt){
289 if(parse_avopts(avctx, lavc_param->avopt) < 0){
290 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
291 uninit(sh);
292 return 0;
296 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
297 switch (sh->format) {
298 case mmioFOURCC('S','V','Q','3'):
299 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
300 in the phony AVI header if demux_lavf is used. The first case is
301 handled here; the second case falls through to the next section. */
302 if (sh->ImageDesc) {
303 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
304 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
305 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
306 break;
308 /* fallthrough */
310 case mmioFOURCC('A','V','R','n'):
311 case mmioFOURCC('M','J','P','G'):
312 /* AVRn stores huffman table in AVI header */
313 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
314 MJPG fourcc :( */
315 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
316 break;
317 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
318 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
319 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
320 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
322 #if 0
324 int x;
325 uint8_t *p = avctx->extradata;
327 for (x=0; x<avctx->extradata_size; x++)
328 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
329 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
331 #endif
332 break;
334 case mmioFOURCC('R', 'V', '1', '0'):
335 case mmioFOURCC('R', 'V', '1', '3'):
336 case mmioFOURCC('R', 'V', '2', '0'):
337 case mmioFOURCC('R', 'V', '3', '0'):
338 case mmioFOURCC('R', 'V', '4', '0'):
339 if(sh->bih->biSize<sizeof(*sh->bih)+8){
340 /* only 1 packet per frame & sub_id from fourcc */
341 avctx->extradata_size= 8;
342 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
343 ((uint32_t *)avctx->extradata)[0] = 0;
344 ((uint32_t *)avctx->extradata)[1] =
345 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
346 } else {
347 /* has extra slice header (demux_rm or rm->avi streamcopy) */
348 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
349 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
350 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
352 avctx->sub_id= AV_RB32(avctx->extradata+4);
354 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
355 break;
357 default:
358 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
359 break;
360 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
361 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
362 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
363 break;
365 /* Pass palette to codec */
366 if (sh->bih && (sh->bih->biBitCount <= 8)) {
367 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
368 avctx->palctrl->palette_changed = 1;
369 if (sh->bih->biSize-sizeof(*sh->bih))
370 /* Palette size in biSize */
371 memcpy(avctx->palctrl->palette, sh->bih+1,
372 FFMIN(sh->bih->biSize-sizeof(*sh->bih), AVPALETTE_SIZE));
373 else
374 /* Palette size in biClrUsed */
375 memcpy(avctx->palctrl->palette, sh->bih+1,
376 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
379 if(sh->bih)
380 avctx->bits_per_coded_sample= sh->bih->biBitCount;
382 if(lavc_param->threads > 1) {
383 avctx->thread_count = lavc_param->threads;
384 avcodec_thread_init(avctx, lavc_param->threads);
386 /* open it */
387 if (avcodec_open(avctx, lavc_codec) < 0) {
388 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
389 uninit(sh);
390 return 0;
392 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
393 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
396 // uninit driver
397 static void uninit(sh_video_t *sh){
398 vd_ffmpeg_ctx *ctx = sh->context;
399 AVCodecContext *avctx = ctx->avctx;
401 if(sh->opts->lavc_param.vstats){
402 int i;
403 for(i=1; i<32; i++){
404 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
406 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
407 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
408 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
412 if (avctx) {
413 if (avctx->codec && avcodec_close(avctx) < 0)
414 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
416 av_freep(&avctx->extradata);
417 free(avctx->palctrl);
418 av_freep(&avctx->slice_offset);
421 av_freep(&avctx);
422 av_freep(&ctx->pic);
423 talloc_free(ctx);
426 static void draw_slice(struct AVCodecContext *s,
427 const AVFrame *src, int offset[4],
428 int y, int type, int height){
429 sh_video_t *sh = s->opaque;
430 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
431 int strides[MP_MAX_PLANES] = {src->linesize[0], src->linesize[1], src->linesize[2]};
432 #if 0
433 int start=0, i;
434 int width= s->width;
435 vd_ffmpeg_ctx *ctx = sh->context;
436 int skip_stride= ((width << ctx->lowres)+15)>>4;
437 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
438 int threshold= s->coded_frame->age;
439 if(s->pict_type!=B_TYPE){
440 for(i=0; i*16<width+16; i++){
441 if(i*16>=width || skip[i]>=threshold){
442 if(start==i) start++;
443 else{
444 uint8_t *src2[3]= {src[0] + start*16,
445 src[1] + start*8,
446 src[2] + start*8};
447 //printf("%2d-%2d x %d\n", start, i, y);
448 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
449 start= i+1;
453 }else
454 #endif
455 if (height < 0)
457 int i;
458 height = -height;
459 y -= height;
460 for (i = 0; i < MP_MAX_PLANES; i++)
462 strides[i] = -strides[i];
463 source[i] -= strides[i];
466 if (y < sh->disp_h) {
467 height = FFMIN(height, sh->disp_h-y);
468 mpcodecs_draw_slice (sh, source, strides, sh->disp_w, height, 0, y);
473 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
474 vd_ffmpeg_ctx *ctx = sh->context;
475 AVCodecContext *avctx = ctx->avctx;
476 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
477 int width, height;
479 width = avctx->width;
480 height = avctx->height;
482 // HACK!
483 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
484 // use dimensions from BIH to avoid black borders at the right and bottom.
485 if (sh->bih && sh->ImageDesc) {
486 width = sh->bih->biWidth >> ctx->lowres;
487 height = sh->bih->biHeight >> ctx->lowres;
490 // it is possible another vo buffers to be used after vo config()
491 // lavc reset its buffers on width/heigh change but not on aspect change!!!
492 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
493 width != sh->disp_w ||
494 height != sh->disp_h ||
495 pix_fmt != ctx->pix_fmt ||
496 !ctx->vo_initialized)
498 ctx->vo_initialized = 0;
499 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
501 // Do not overwrite s->aspect on the first call, so that a container
502 // aspect if available is preferred.
503 // But set it even if the sample aspect did not change, since a
504 // resolution change can cause an aspect change even if the
505 // _sample_ aspect is unchanged.
506 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
507 sh->aspect = aspect;
508 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
509 sh->disp_w = width;
510 sh->disp_h = height;
511 ctx->pix_fmt = pix_fmt;
512 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
513 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
514 return -1;
515 ctx->vo_initialized = 1;
517 return 0;
520 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
521 sh_video_t *sh = avctx->opaque;
522 vd_ffmpeg_ctx *ctx = sh->context;
523 mp_image_t *mpi=NULL;
524 int flags= MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
525 int type= MP_IMGTYPE_IPB;
526 int width= avctx->width;
527 int height= avctx->height;
528 // special case to handle reget_buffer without buffer hints
529 if (pic->opaque && pic->data[0] && !pic->buffer_hints)
530 return 0;
531 avcodec_align_dimensions(avctx, &width, &height);
532 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
534 if (pic->buffer_hints) {
535 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
536 type = MP_IMGTYPE_TEMP;
537 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
538 flags |= MP_IMGFLAG_READABLE;
539 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
540 type = MP_IMGTYPE_STATIC;
541 flags |= MP_IMGFLAG_PRESERVE;
543 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
544 type = MP_IMGTYPE_STATIC;
545 flags |= MP_IMGFLAG_PRESERVE;
547 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
548 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
549 } else {
550 if(!pic->reference){
551 ctx->b_count++;
552 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK:0;
553 }else{
554 ctx->ip_count++;
555 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
556 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
560 if(init_vo(sh, avctx->pix_fmt) < 0){
561 avctx->release_buffer= avcodec_default_release_buffer;
562 avctx->get_buffer= avcodec_default_get_buffer;
563 avctx->reget_buffer= avcodec_default_reget_buffer;
564 if (pic->data[0])
565 release_buffer(avctx, pic);
566 return avctx->get_buffer(avctx, pic);
569 if (IMGFMT_IS_HWACCEL(ctx->best_csp)) {
570 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
571 } else
572 if (!pic->buffer_hints) {
573 if(ctx->b_count>1 || ctx->ip_count>2){
574 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
576 ctx->do_dr1=0; //FIXME
577 avctx->get_buffer= avcodec_default_get_buffer;
578 avctx->reget_buffer= avcodec_default_reget_buffer;
579 if (pic->data[0])
580 release_buffer(avctx, pic);
581 return avctx->get_buffer(avctx, pic);
584 if(avctx->has_b_frames || ctx->b_count){
585 type= MP_IMGTYPE_IPB;
586 }else{
587 type= MP_IMGTYPE_IP;
589 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
592 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
593 flags |= MP_IMGFLAG_RGB_PALETTE;
594 mpi= mpcodecs_get_image(sh, type, flags, width, height);
595 if (!mpi) return -1;
597 // ok, let's see what did we get:
598 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
599 !(mpi->flags&MP_IMGFLAG_DIRECT)){
600 // nice, filter/vo likes draw_callback :)
601 avctx->draw_horiz_band= draw_slice;
602 } else
603 avctx->draw_horiz_band= NULL;
604 if(IMGFMT_IS_HWACCEL(mpi->imgfmt)) {
605 avctx->draw_horiz_band= draw_slice;
607 #if CONFIG_XVMC
608 if(IMGFMT_IS_XVMC(mpi->imgfmt)) {
609 struct xvmc_pix_fmt *render = mpi->priv; //same as data[2]
610 if(!avctx->xvmc_acceleration) {
611 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
612 assert(0);
613 exit(1);
614 // return -1;//!!fixme check error conditions in ffmpeg
616 if(!(mpi->flags & MP_IMGFLAG_DIRECT)) {
617 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
618 assert(0);
619 exit(1);
620 // return -1;//!!fixme check error conditions in ffmpeg
622 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
623 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render);
624 assert(render != 0);
625 assert(render->xvmc_id == AV_XVMC_ID);
626 render->state |= AV_XVMC_STATE_PREDICTION;
628 #endif
630 pic->data[0]= mpi->planes[0];
631 pic->data[1]= mpi->planes[1];
632 pic->data[2]= mpi->planes[2];
633 pic->data[3]= mpi->planes[3];
635 #if 0
636 assert(mpi->width >= ((width +align)&(~align)));
637 assert(mpi->height >= ((height+align)&(~align)));
638 assert(mpi->stride[0] >= mpi->width);
639 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
640 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
641 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
643 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
644 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
645 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
646 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
647 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
648 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
650 #endif
652 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
653 * lavc will check that and die with an error message, if its not true
655 pic->linesize[0]= mpi->stride[0];
656 pic->linesize[1]= mpi->stride[1];
657 pic->linesize[2]= mpi->stride[2];
658 pic->linesize[3]= mpi->stride[3];
660 pic->opaque = mpi;
661 //printf("%X\n", (int)mpi->planes[0]);
662 #if 0
663 if(mpi->flags&MP_IMGFLAG_DIRECT)
664 printf("D");
665 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
666 printf("S");
667 else
668 printf(".");
669 #endif
670 if(pic->reference){
671 pic->age= ctx->ip_age[0];
673 ctx->ip_age[0]= ctx->ip_age[1]+1;
674 ctx->ip_age[1]= 1;
675 ctx->b_age++;
676 }else{
677 pic->age= ctx->b_age;
679 ctx->ip_age[0]++;
680 ctx->ip_age[1]++;
681 ctx->b_age=1;
683 pic->type= FF_BUFFER_TYPE_USER;
685 /* The libavcodec reordered_opaque functionality is implemented by
686 * a similar copy in avcodec_default_get_buffer() and without a
687 * workaround like this it'd stop working when a custom buffer
688 * callback is used.
690 pic->reordered_opaque = avctx->reordered_opaque;
691 return 0;
694 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
695 mp_image_t *mpi= pic->opaque;
696 sh_video_t *sh = avctx->opaque;
697 vd_ffmpeg_ctx *ctx = sh->context;
698 int i;
700 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
702 if(ctx->ip_count <= 2 && ctx->b_count<=1){
703 if(mpi->flags&MP_IMGFLAG_PRESERVE)
704 ctx->ip_count--;
705 else
706 ctx->b_count--;
709 if (mpi) {
710 // Palette support: free palette buffer allocated in get_buffer
711 if (mpi->bpp == 8)
712 av_freep(&mpi->planes[1]);
713 #if CONFIG_XVMC
714 if (IMGFMT_IS_XVMC(mpi->imgfmt)) {
715 struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)pic->data[2]; //same as mpi->priv
716 if(mp_msg_test(MSGT_DECVIDEO, MSGL_DBG5))
717 mp_msg(MSGT_DECVIDEO, MSGL_DBG5, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render);
718 assert(render!=NULL);
719 assert(render->xvmc_id == AV_XVMC_ID);
720 render->state&=~AV_XVMC_STATE_PREDICTION;
722 #endif
723 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
724 mpi->usage_count--;
727 if(pic->type!=FF_BUFFER_TYPE_USER){
728 avcodec_default_release_buffer(avctx, pic);
729 return;
732 for(i=0; i<4; i++){
733 pic->data[i]= NULL;
735 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
738 // copypaste from demux_real.c - it should match to get it working!
739 //FIXME put into some header
740 typedef struct dp_hdr_s {
741 uint32_t chunks; // number of chunks
742 uint32_t timestamp; // timestamp from packet header
743 uint32_t len; // length of actual data
744 uint32_t chunktab; // offset to chunk offset array
745 } dp_hdr_t;
747 static av_unused void swap_palette(void *pal)
749 int i;
750 uint32_t *p = pal;
751 for (i = 0; i < AVPALETTE_COUNT; i++)
752 p[i] = le2me_32(p[i]);
755 // decode a frame
756 static struct mp_image *decode(struct sh_video *sh, void *data, int len,
757 int flags, double *reordered_pts)
759 int got_picture=0;
760 int ret;
761 vd_ffmpeg_ctx *ctx = sh->context;
762 AVFrame *pic= ctx->pic;
763 AVCodecContext *avctx = ctx->avctx;
764 struct lavc_param *lavc_param = &sh->opts->lavc_param;
765 mp_image_t *mpi=NULL;
766 int dr1= ctx->do_dr1;
767 AVPacket pkt;
769 if(len<=0) return NULL; // skipped frame
771 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
772 if (!dr1)
773 avctx->draw_horiz_band=NULL;
774 if(ctx->vo_initialized && !(flags&3) && !dr1){
775 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
776 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
777 sh->disp_w, sh->disp_h);
778 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
779 // vd core likes slices!
780 avctx->draw_horiz_band=draw_slice;
784 if (flags & 2)
785 avctx->skip_frame = AVDISCARD_ALL;
786 else if (flags & 1)
787 avctx->skip_frame = AVDISCARD_NONREF;
788 else
789 avctx->skip_frame = 0;
791 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
792 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
793 av_init_packet(&pkt);
794 pkt.data = data;
795 pkt.size = len;
796 // HACK: make PNGs decode normally instead of as CorePNG delta frames
797 pkt.flags = AV_PKT_FLAG_KEY;
798 // The avcodec opaque field stupidly supports only int64_t type
799 union pts { int64_t i; double d; };
800 avctx->reordered_opaque = (union pts){.d = *reordered_pts}.i;
801 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
802 *reordered_pts = (union pts){.i = pic->reordered_opaque}.d;
804 dr1= ctx->do_dr1;
805 if(ret<0) mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
806 //printf("repeat: %d\n", pic->repeat_pict);
807 //-- vstats generation
808 while(lavc_param->vstats){ // always one time loop
809 static FILE *fvstats=NULL;
810 char filename[20];
811 static long long int all_len=0;
812 static int frame_number=0;
813 static double all_frametime=0.0;
814 AVFrame *pic= avctx->coded_frame;
815 double quality=0.0;
817 if(!fvstats) {
818 time_t today2;
819 struct tm *today;
820 today2 = time(NULL);
821 today = localtime(&today2);
822 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
823 today->tm_min, today->tm_sec);
824 fvstats = fopen(filename, "w");
825 if(!fvstats) {
826 perror("fopen");
827 lavc_param->vstats=0; // disable block
828 break;
829 /*exit(1);*/
833 // average MB quantizer
835 int x, y;
836 int w = ((avctx->width << ctx->lowres)+15) >> 4;
837 int h = ((avctx->height << ctx->lowres)+15) >> 4;
838 int8_t *q = pic->qscale_table;
839 for(y = 0; y < h; y++) {
840 for(x = 0; x < w; x++)
841 quality += (double)*(q+x);
842 q += pic->qstride;
844 quality /= w * h;
847 all_len+=len;
848 all_frametime+=sh->frametime;
849 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
850 ++frame_number, quality, len, (double)all_len/1024);
851 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
852 all_frametime, (double)(len*8)/sh->frametime/1000.0,
853 (double)(all_len*8)/all_frametime/1000.0);
854 switch(pic->pict_type){
855 case FF_I_TYPE:
856 fprintf(fvstats, "type= I\n");
857 break;
858 case FF_P_TYPE:
859 fprintf(fvstats, "type= P\n");
860 break;
861 case FF_S_TYPE:
862 fprintf(fvstats, "type= S\n");
863 break;
864 case FF_B_TYPE:
865 fprintf(fvstats, "type= B\n");
866 break;
867 default:
868 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
869 break;
872 ctx->qp_stat[(int)(quality+0.5)]++;
873 ctx->qp_sum += quality;
874 ctx->inv_qp_sum += 1.0/(double)quality;
876 break;
878 //--
880 if(!got_picture) return NULL; // skipped image
882 if(init_vo(sh, avctx->pix_fmt) < 0) return NULL;
884 if(dr1 && pic->opaque){
885 mpi= (mp_image_t *)pic->opaque;
888 if(!mpi)
889 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
890 avctx->width, avctx->height);
891 if(!mpi){ // temporary!
892 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
893 return NULL;
896 if(!dr1){
897 mpi->planes[0]=pic->data[0];
898 mpi->planes[1]=pic->data[1];
899 mpi->planes[2]=pic->data[2];
900 mpi->planes[3]=pic->data[3];
901 mpi->stride[0]=pic->linesize[0];
902 mpi->stride[1]=pic->linesize[1];
903 mpi->stride[2]=pic->linesize[2];
904 mpi->stride[3]=pic->linesize[3];
907 if (!mpi->planes[0])
908 return NULL;
910 if(ctx->best_csp == IMGFMT_422P && mpi->chroma_y_shift==1){
911 // we have 422p but user wants 420p
912 mpi->stride[1]*=2;
913 mpi->stride[2]*=2;
916 #if HAVE_BIGENDIAN
917 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
918 if (mpi->bpp == 8)
919 swap_palette(mpi->planes[1]);
920 #endif
921 /* to comfirm with newer lavc style */
922 mpi->qscale =pic->qscale_table;
923 mpi->qstride=pic->qstride;
924 mpi->pict_type=pic->pict_type;
925 mpi->qscale_type= pic->qscale_type;
926 mpi->fields = MP_IMGFIELD_ORDERED;
927 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
928 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
929 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
931 return mpi;
934 static enum PixelFormat get_format(struct AVCodecContext *avctx,
935 const enum PixelFormat *fmt){
936 enum PixelFormat selected_format;
937 int imgfmt;
938 sh_video_t *sh = avctx->opaque;
939 int i;
941 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
942 imgfmt = pixfmt2imgfmt(fmt[i]);
943 if(!IMGFMT_IS_HWACCEL(imgfmt)) continue;
944 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
945 if(init_vo(sh, fmt[i]) >= 0) {
946 break;
949 selected_format = fmt[i];
950 return selected_format;
953 const struct vd_functions mpcodecs_vd_ffmpeg = {
954 .info = &info,
955 .init = init,
956 .uninit = uninit,
957 .control = control,
958 .decode2 = decode