ao: fix crash after ao init failure (from recent 3a5fd15fa2)
[mplayer/greg.git] / libmpcodecs / vd_ffmpeg.c
blob5a17bc243ea89626cb642ea4b357ee5354d24af3
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 int avcodec_initialized=0;
59 typedef struct {
60 AVCodecContext *avctx;
61 AVFrame *pic;
62 enum PixelFormat pix_fmt;
63 int do_slices;
64 int do_dr1;
65 int vo_initialized;
66 int best_csp;
67 int b_age;
68 int ip_age[2];
69 int qp_stat[32];
70 double qp_sum;
71 double inv_qp_sum;
72 int ip_count;
73 int b_count;
74 AVRational last_sample_aspect_ratio;
75 int lowres;
76 } vd_ffmpeg_ctx;
78 #include "m_option.h"
80 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
81 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
82 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
83 int offset[4], int y, int type, int height);
85 static enum PixelFormat get_format(struct AVCodecContext *avctx,
86 const enum PixelFormat *pix_fmt);
87 static void uninit(struct sh_video *sh);
89 const m_option_t lavc_decode_opts_conf[]={
90 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
91 OPT_INTRANGE("er", lavc_param.error_resilience, 0, 0, 99),
92 OPT_FLAG_ON("gray", lavc_param.gray, 0),
93 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
94 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
95 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
96 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
97 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
98 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
99 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
100 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
101 OPT_STRING("lowres", lavc_param.lowres_str, 0),
102 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
103 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
104 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
105 OPT_INTRANGE("threads", lavc_param.threads, 0, 0, 16),
106 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
107 OPT_STRING("o", lavc_param.avopt, 0),
108 {NULL, NULL, 0, 0, 0, 0, NULL}
111 static enum AVDiscard str2AVDiscard(char *str) {
112 if (!str) return AVDISCARD_DEFAULT;
113 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
114 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
115 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
116 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
117 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
118 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
119 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
120 return AVDISCARD_DEFAULT;
123 // to set/get/query special features/parameters
124 static int control(sh_video_t *sh, int cmd, void *arg, ...){
125 vd_ffmpeg_ctx *ctx = sh->context;
126 AVCodecContext *avctx = ctx->avctx;
127 switch(cmd){
128 case VDCTRL_QUERY_FORMAT:
130 int format =(*((int *)arg));
131 if(format == ctx->best_csp) return CONTROL_TRUE;//supported
132 // possible conversions:
133 switch(format){
134 case IMGFMT_YV12:
135 case IMGFMT_IYUV:
136 case IMGFMT_I420:
137 // "converted" using pointer/stride modification
138 if(ctx->best_csp == IMGFMT_YV12) return CONTROL_TRUE;// u/v swap
139 if(ctx->best_csp == IMGFMT_422P && !ctx->do_dr1) return CONTROL_TRUE;// half stride
140 break;
142 return CONTROL_FALSE;
144 case VDCTRL_RESYNC_STREAM:
145 avcodec_flush_buffers(avctx);
146 return CONTROL_TRUE;
147 case VDCTRL_QUERY_UNSEEN_FRAMES:;
148 int delay = avctx->has_b_frames;
149 return delay + 10;
151 return CONTROL_UNKNOWN;
154 void init_avcodec(void)
156 if (!avcodec_initialized) {
157 avcodec_init();
158 avcodec_register_all();
159 avcodec_initialized = 1;
163 // init driver
164 static int init(sh_video_t *sh){
165 struct lavc_param *lavc_param = &sh->opts->lavc_param;
166 AVCodecContext *avctx;
167 vd_ffmpeg_ctx *ctx;
168 AVCodec *lavc_codec;
169 int lowres_w=0;
170 int do_vis_debug= lavc_param->vismv || (lavc_param->debug&(FF_DEBUG_VIS_MB_TYPE|FF_DEBUG_VIS_QP));
172 init_avcodec();
174 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
176 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
177 if(!lavc_codec){
178 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
179 uninit(sh);
180 return 0;
183 if(sh->opts->vd_use_slices && (lavc_codec->capabilities&CODEC_CAP_DRAW_HORIZ_BAND) && !do_vis_debug)
184 ctx->do_slices=1;
186 if(lavc_codec->capabilities&CODEC_CAP_DR1 && !do_vis_debug
187 && lavc_codec->id != CODEC_ID_H264
188 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO
189 && lavc_codec->id != CODEC_ID_ROQ && lavc_codec->id != CODEC_ID_VP8
190 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(52, 108, 0)
191 && lavc_codec->id != CODEC_ID_LAGARITH
192 #endif
194 ctx->do_dr1=1;
195 ctx->b_age= ctx->ip_age[0]= ctx->ip_age[1]= 256*256*256*64;
196 ctx->ip_count= ctx->b_count= 0;
198 ctx->pic = avcodec_alloc_frame();
199 ctx->avctx = avcodec_alloc_context();
200 avctx = ctx->avctx;
201 avctx->opaque = sh;
202 avctx->codec_type = AVMEDIA_TYPE_VIDEO;
203 avctx->codec_id = lavc_codec->id;
205 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
206 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
207 ctx->do_dr1 = true;
208 ctx->do_slices = true;
209 lavc_param->threads = 1;
210 avctx->get_format = get_format;
211 avctx->get_buffer = get_buffer;
212 avctx->release_buffer = release_buffer;
213 avctx->reget_buffer = get_buffer;
214 avctx->draw_horiz_band = draw_slice;
215 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
216 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
217 "MPEG-2.\n");
218 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
219 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
220 "decoding.\n");
221 avctx->slice_flags = SLICE_FLAG_CODED_ORDER|SLICE_FLAG_ALLOW_FIELD;
224 if (lavc_param->threads == 0) {
225 int threads = default_thread_count();
226 if (threads < 1) {
227 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Could not determine "
228 "thread count to use, defaulting to 1.\n");
229 threads = 1;
231 threads = FFMIN(threads, 16);
232 lavc_param->threads = threads;
234 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
235 * from other threads. */
236 if (lavc_param->threads > 1) {
237 ctx->do_dr1 = false;
238 ctx->do_slices = false;
239 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "Asking decoder to use "
240 "%d threads if supported.\n", lavc_param->threads);
243 if(ctx->do_dr1){
244 avctx->flags|= CODEC_FLAG_EMU_EDGE;
245 avctx->get_buffer= get_buffer;
246 avctx->release_buffer= release_buffer;
247 avctx->reget_buffer= get_buffer;
250 avctx->flags|= lavc_param->bitexact;
252 avctx->coded_width = sh->disp_w;
253 avctx->coded_height= sh->disp_h;
254 avctx->workaround_bugs= lavc_param->workaround_bugs;
255 avctx->error_recognition= lavc_param->error_resilience;
256 if(lavc_param->gray) avctx->flags|= CODEC_FLAG_GRAY;
257 avctx->flags2|= lavc_param->fast;
258 avctx->codec_tag= sh->format;
259 avctx->stream_codec_tag= sh->video.fccHandler;
260 avctx->idct_algo= lavc_param->idct_algo;
261 avctx->error_concealment= lavc_param->error_concealment;
262 avctx->debug= lavc_param->debug;
263 if (lavc_param->debug)
264 av_log_set_level(AV_LOG_DEBUG);
265 avctx->debug_mv= lavc_param->vismv;
266 avctx->skip_top = lavc_param->skip_top;
267 avctx->skip_bottom= lavc_param->skip_bottom;
268 if(lavc_param->lowres_str != NULL)
270 sscanf(lavc_param->lowres_str, "%d,%d", &ctx->lowres, &lowres_w);
271 if(ctx->lowres < 1 || ctx->lowres > 16 || (lowres_w > 0 && avctx->width < lowres_w))
272 ctx->lowres = 0;
273 avctx->lowres = ctx->lowres;
275 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
276 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
277 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
279 if(lavc_param->avopt){
280 if(parse_avopts(avctx, lavc_param->avopt) < 0){
281 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Your options /%s/ look like gibberish to me pal\n", lavc_param->avopt);
282 uninit(sh);
283 return 0;
287 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2, "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
288 switch (sh->format) {
289 case mmioFOURCC('S','V','Q','3'):
290 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
291 in the phony AVI header if demux_lavf is used. The first case is
292 handled here; the second case falls through to the next section. */
293 if (sh->ImageDesc) {
294 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
295 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
296 memcpy(avctx->extradata, ((int *)sh->ImageDesc)+1, avctx->extradata_size);
297 break;
299 /* fallthrough */
301 case mmioFOURCC('A','V','R','n'):
302 case mmioFOURCC('M','J','P','G'):
303 /* AVRn stores huffman table in AVI header */
304 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
305 MJPG fourcc :( */
306 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
307 break;
308 avctx->flags |= CODEC_FLAG_EXTERN_HUFF;
309 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
310 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
311 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
313 #if 0
315 int x;
316 uint8_t *p = avctx->extradata;
318 for (x=0; x<avctx->extradata_size; x++)
319 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "[%x] ", p[x]);
320 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "\n");
322 #endif
323 break;
325 case mmioFOURCC('R', 'V', '1', '0'):
326 case mmioFOURCC('R', 'V', '1', '3'):
327 case mmioFOURCC('R', 'V', '2', '0'):
328 case mmioFOURCC('R', 'V', '3', '0'):
329 case mmioFOURCC('R', 'V', '4', '0'):
330 if(sh->bih->biSize<sizeof(*sh->bih)+8){
331 /* only 1 packet per frame & sub_id from fourcc */
332 avctx->extradata_size= 8;
333 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
334 ((uint32_t *)avctx->extradata)[0] = 0;
335 ((uint32_t *)avctx->extradata)[1] =
336 (sh->format == mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
337 } else {
338 /* has extra slice header (demux_rm or rm->avi streamcopy) */
339 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
340 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
341 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
343 avctx->sub_id= AV_RB32(avctx->extradata+4);
345 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
346 break;
348 default:
349 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
350 break;
351 avctx->extradata_size = sh->bih->biSize-sizeof(*sh->bih);
352 avctx->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
353 memcpy(avctx->extradata, sh->bih+1, avctx->extradata_size);
354 break;
356 /* Pass palette to codec */
357 if (sh->bih && (sh->bih->biBitCount <= 8)) {
358 avctx->palctrl = calloc(1, sizeof(AVPaletteControl));
359 avctx->palctrl->palette_changed = 1;
360 if (sh->bih->biSize-sizeof(*sh->bih))
361 /* Palette size in biSize */
362 memcpy(avctx->palctrl->palette, sh->bih+1,
363 FFMIN(sh->bih->biSize-sizeof(*sh->bih), AVPALETTE_SIZE));
364 else
365 /* Palette size in biClrUsed */
366 memcpy(avctx->palctrl->palette, sh->bih+1,
367 FFMIN(sh->bih->biClrUsed * 4, AVPALETTE_SIZE));
370 if(sh->bih)
371 avctx->bits_per_coded_sample= sh->bih->biBitCount;
373 if(lavc_param->threads > 1) {
374 avctx->thread_count = lavc_param->threads;
375 avcodec_thread_init(avctx, lavc_param->threads);
377 /* open it */
378 if (avcodec_open(avctx, lavc_codec) < 0) {
379 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
380 uninit(sh);
381 return 0;
383 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
384 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
387 // uninit driver
388 static void uninit(sh_video_t *sh){
389 vd_ffmpeg_ctx *ctx = sh->context;
390 AVCodecContext *avctx = ctx->avctx;
392 if(sh->opts->lavc_param.vstats){
393 int i;
394 for(i=1; i<32; i++){
395 mp_msg(MSGT_DECVIDEO, MSGL_INFO, "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
397 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
398 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
399 1.0/(ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number)
403 if (avctx) {
404 if (avctx->codec && avcodec_close(avctx) < 0)
405 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
407 av_freep(&avctx->extradata);
408 free(avctx->palctrl);
409 av_freep(&avctx->slice_offset);
412 av_freep(&avctx);
413 av_freep(&ctx->pic);
414 talloc_free(ctx);
417 static void draw_slice(struct AVCodecContext *s,
418 const AVFrame *src, int offset[4],
419 int y, int type, int height){
420 sh_video_t *sh = s->opaque;
421 uint8_t *source[MP_MAX_PLANES]= {src->data[0] + offset[0], src->data[1] + offset[1], src->data[2] + offset[2]};
422 int strides[MP_MAX_PLANES] = {src->linesize[0], src->linesize[1], src->linesize[2]};
423 #if 0
424 int start=0, i;
425 int width= s->width;
426 vd_ffmpeg_ctx *ctx = sh->context;
427 int skip_stride= ((width << ctx->lowres)+15)>>4;
428 uint8_t *skip= &s->coded_frame->mbskip_table[(y>>4)*skip_stride];
429 int threshold= s->coded_frame->age;
430 if(s->pict_type!=B_TYPE){
431 for(i=0; i*16<width+16; i++){
432 if(i*16>=width || skip[i]>=threshold){
433 if(start==i) start++;
434 else{
435 uint8_t *src2[3]= {src[0] + start*16,
436 src[1] + start*8,
437 src[2] + start*8};
438 //printf("%2d-%2d x %d\n", start, i, y);
439 mpcodecs_draw_slice (sh, src2, stride, (i-start)*16, height, start*16, y);
440 start= i+1;
444 }else
445 #endif
446 if (height < 0)
448 int i;
449 height = -height;
450 y -= height;
451 for (i = 0; i < MP_MAX_PLANES; i++)
453 strides[i] = -strides[i];
454 source[i] -= strides[i];
457 if (y < sh->disp_h) {
458 height = FFMIN(height, sh->disp_h-y);
459 mpcodecs_draw_slice (sh, source, strides, sh->disp_w, height, 0, y);
464 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt){
465 vd_ffmpeg_ctx *ctx = sh->context;
466 AVCodecContext *avctx = ctx->avctx;
467 float aspect= av_q2d(avctx->sample_aspect_ratio) * avctx->width / avctx->height;
468 int width, height;
470 width = avctx->width;
471 height = avctx->height;
473 // HACK!
474 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
475 // use dimensions from BIH to avoid black borders at the right and bottom.
476 if (sh->bih && sh->ImageDesc) {
477 width = sh->bih->biWidth >> ctx->lowres;
478 height = sh->bih->biHeight >> ctx->lowres;
481 // it is possible another vo buffers to be used after vo config()
482 // lavc reset its buffers on width/heigh change but not on aspect change!!!
483 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
484 width != sh->disp_w ||
485 height != sh->disp_h ||
486 pix_fmt != ctx->pix_fmt ||
487 !ctx->vo_initialized)
489 ctx->vo_initialized = 0;
490 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
492 // Do not overwrite s->aspect on the first call, so that a container
493 // aspect if available is preferred.
494 // But set it even if the sample aspect did not change, since a
495 // resolution change can cause an aspect change even if the
496 // _sample_ aspect is unchanged.
497 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
498 sh->aspect = aspect;
499 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
500 sh->disp_w = width;
501 sh->disp_h = height;
502 ctx->pix_fmt = pix_fmt;
503 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
504 if (!mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, ctx->best_csp))
505 return -1;
506 ctx->vo_initialized = 1;
508 return 0;
511 static int get_buffer(AVCodecContext *avctx, AVFrame *pic){
512 sh_video_t *sh = avctx->opaque;
513 vd_ffmpeg_ctx *ctx = sh->context;
514 mp_image_t *mpi=NULL;
515 int flags= MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE | MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
516 int type= MP_IMGTYPE_IPB;
517 int width= avctx->width;
518 int height= avctx->height;
519 // special case to handle reget_buffer without buffer hints
520 if (pic->opaque && pic->data[0] && !pic->buffer_hints)
521 return 0;
522 avcodec_align_dimensions(avctx, &width, &height);
523 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
525 if (pic->buffer_hints) {
526 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n", pic->buffer_hints);
527 type = MP_IMGTYPE_TEMP;
528 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
529 flags |= MP_IMGFLAG_READABLE;
530 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
531 type = MP_IMGTYPE_STATIC;
532 flags |= MP_IMGFLAG_PRESERVE;
534 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
535 type = MP_IMGTYPE_STATIC;
536 flags |= MP_IMGFLAG_PRESERVE;
538 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
539 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
540 } else {
541 if(!pic->reference){
542 ctx->b_count++;
543 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK:0;
544 }else{
545 ctx->ip_count++;
546 flags|= MP_IMGFLAG_PRESERVE|MP_IMGFLAG_READABLE
547 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
551 if(init_vo(sh, avctx->pix_fmt) < 0){
552 avctx->release_buffer= avcodec_default_release_buffer;
553 avctx->get_buffer= avcodec_default_get_buffer;
554 avctx->reget_buffer= avcodec_default_reget_buffer;
555 if (pic->data[0])
556 release_buffer(avctx, pic);
557 return avctx->get_buffer(avctx, pic);
560 if (IMGFMT_IS_HWACCEL(ctx->best_csp)) {
561 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
562 } else
563 if (!pic->buffer_hints) {
564 if(ctx->b_count>1 || ctx->ip_count>2){
565 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
567 ctx->do_dr1=0; //FIXME
568 avctx->get_buffer= avcodec_default_get_buffer;
569 avctx->reget_buffer= avcodec_default_reget_buffer;
570 if (pic->data[0])
571 release_buffer(avctx, pic);
572 return avctx->get_buffer(avctx, pic);
575 if(avctx->has_b_frames || ctx->b_count){
576 type= MP_IMGTYPE_IPB;
577 }else{
578 type= MP_IMGTYPE_IP;
580 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, type== MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
583 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
584 flags |= MP_IMGFLAG_RGB_PALETTE;
585 mpi= mpcodecs_get_image(sh, type, flags, width, height);
586 if (!mpi) return -1;
588 // ok, let's see what did we get:
589 if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK &&
590 !(mpi->flags&MP_IMGFLAG_DIRECT)){
591 // nice, filter/vo likes draw_callback :)
592 avctx->draw_horiz_band= draw_slice;
593 } else
594 avctx->draw_horiz_band= NULL;
595 if(IMGFMT_IS_HWACCEL(mpi->imgfmt)) {
596 avctx->draw_horiz_band= draw_slice;
599 pic->data[0]= mpi->planes[0];
600 pic->data[1]= mpi->planes[1];
601 pic->data[2]= mpi->planes[2];
602 pic->data[3]= mpi->planes[3];
604 #if 0
605 assert(mpi->width >= ((width +align)&(~align)));
606 assert(mpi->height >= ((height+align)&(~align)));
607 assert(mpi->stride[0] >= mpi->width);
608 if(mpi->imgfmt==IMGFMT_I420 || mpi->imgfmt==IMGFMT_YV12 || mpi->imgfmt==IMGFMT_IYUV){
609 const int y_size= mpi->stride[0] * (mpi->h-1) + mpi->w;
610 const int c_size= mpi->stride[1] * ((mpi->h>>1)-1) + (mpi->w>>1);
612 assert(mpi->planes[0] > mpi->planes[1] || mpi->planes[0] + y_size <= mpi->planes[1]);
613 assert(mpi->planes[0] > mpi->planes[2] || mpi->planes[0] + y_size <= mpi->planes[2]);
614 assert(mpi->planes[1] > mpi->planes[0] || mpi->planes[1] + c_size <= mpi->planes[0]);
615 assert(mpi->planes[1] > mpi->planes[2] || mpi->planes[1] + c_size <= mpi->planes[2]);
616 assert(mpi->planes[2] > mpi->planes[0] || mpi->planes[2] + c_size <= mpi->planes[0]);
617 assert(mpi->planes[2] > mpi->planes[1] || mpi->planes[2] + c_size <= mpi->planes[1]);
619 #endif
621 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
622 * lavc will check that and die with an error message, if its not true
624 pic->linesize[0]= mpi->stride[0];
625 pic->linesize[1]= mpi->stride[1];
626 pic->linesize[2]= mpi->stride[2];
627 pic->linesize[3]= mpi->stride[3];
629 pic->opaque = mpi;
630 //printf("%X\n", (int)mpi->planes[0]);
631 #if 0
632 if(mpi->flags&MP_IMGFLAG_DIRECT)
633 printf("D");
634 else if(mpi->flags&MP_IMGFLAG_DRAW_CALLBACK)
635 printf("S");
636 else
637 printf(".");
638 #endif
639 if(pic->reference){
640 pic->age= ctx->ip_age[0];
642 ctx->ip_age[0]= ctx->ip_age[1]+1;
643 ctx->ip_age[1]= 1;
644 ctx->b_age++;
645 }else{
646 pic->age= ctx->b_age;
648 ctx->ip_age[0]++;
649 ctx->ip_age[1]++;
650 ctx->b_age=1;
652 pic->type= FF_BUFFER_TYPE_USER;
654 /* The libavcodec reordered_opaque functionality is implemented by
655 * a similar copy in avcodec_default_get_buffer() and without a
656 * workaround like this it'd stop working when a custom buffer
657 * callback is used.
659 pic->reordered_opaque = avctx->reordered_opaque;
660 return 0;
663 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic){
664 mp_image_t *mpi= pic->opaque;
665 sh_video_t *sh = avctx->opaque;
666 vd_ffmpeg_ctx *ctx = sh->context;
667 int i;
669 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
671 if(ctx->ip_count <= 2 && ctx->b_count<=1){
672 if(mpi->flags&MP_IMGFLAG_PRESERVE)
673 ctx->ip_count--;
674 else
675 ctx->b_count--;
678 if (mpi) {
679 // Palette support: free palette buffer allocated in get_buffer
680 if (mpi->bpp == 8)
681 av_freep(&mpi->planes[1]);
682 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
683 mpi->usage_count--;
686 if(pic->type!=FF_BUFFER_TYPE_USER){
687 avcodec_default_release_buffer(avctx, pic);
688 return;
691 for(i=0; i<4; i++){
692 pic->data[i]= NULL;
694 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
697 // copypaste from demux_real.c - it should match to get it working!
698 //FIXME put into some header
699 typedef struct dp_hdr_s {
700 uint32_t chunks; // number of chunks
701 uint32_t timestamp; // timestamp from packet header
702 uint32_t len; // length of actual data
703 uint32_t chunktab; // offset to chunk offset array
704 } dp_hdr_t;
706 static av_unused void swap_palette(void *pal)
708 int i;
709 uint32_t *p = pal;
710 for (i = 0; i < AVPALETTE_COUNT; i++)
711 p[i] = le2me_32(p[i]);
714 // decode a frame
715 static struct mp_image *decode(struct sh_video *sh, void *data, int len,
716 int flags, double *reordered_pts)
718 int got_picture=0;
719 int ret;
720 vd_ffmpeg_ctx *ctx = sh->context;
721 AVFrame *pic= ctx->pic;
722 AVCodecContext *avctx = ctx->avctx;
723 struct lavc_param *lavc_param = &sh->opts->lavc_param;
724 mp_image_t *mpi=NULL;
725 int dr1= ctx->do_dr1;
726 AVPacket pkt;
728 if(len<=0) return NULL; // skipped frame
730 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
731 if (!dr1)
732 avctx->draw_horiz_band=NULL;
733 if(ctx->vo_initialized && !(flags&3) && !dr1){
734 mpi=mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE |
735 (ctx->do_slices?MP_IMGFLAG_DRAW_CALLBACK:0),
736 sh->disp_w, sh->disp_h);
737 if(mpi && mpi->flags&MP_IMGFLAG_DRAW_CALLBACK){
738 // vd core likes slices!
739 avctx->draw_horiz_band=draw_slice;
743 if (flags & 2)
744 avctx->skip_frame = AVDISCARD_ALL;
745 else if (flags & 1)
746 avctx->skip_frame = AVDISCARD_NONREF;
747 else
748 avctx->skip_frame = 0;
750 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "vd_ffmpeg data: %04x, %04x, %04x, %04x\n",
751 ((int *)data)[0], ((int *)data)[1], ((int *)data)[2], ((int *)data)[3]);
752 av_init_packet(&pkt);
753 pkt.data = data;
754 pkt.size = len;
755 // HACK: make PNGs decode normally instead of as CorePNG delta frames
756 pkt.flags = AV_PKT_FLAG_KEY;
757 // The avcodec opaque field stupidly supports only int64_t type
758 union pts { int64_t i; double d; };
759 avctx->reordered_opaque = (union pts){.d = *reordered_pts}.i;
760 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
761 *reordered_pts = (union pts){.i = pic->reordered_opaque}.d;
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 << ctx->lowres)+15) >> 4;
796 int h = ((avctx->height << ctx->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_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
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->planes[3]=pic->data[3];
860 mpi->stride[0]=pic->linesize[0];
861 mpi->stride[1]=pic->linesize[1];
862 mpi->stride[2]=pic->linesize[2];
863 mpi->stride[3]=pic->linesize[3];
866 if (!mpi->planes[0])
867 return NULL;
869 if(ctx->best_csp == IMGFMT_422P && mpi->chroma_y_shift==1){
870 // we have 422p but user wants 420p
871 mpi->stride[1]*=2;
872 mpi->stride[2]*=2;
875 #if HAVE_BIGENDIAN
876 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
877 if (mpi->bpp == 8)
878 swap_palette(mpi->planes[1]);
879 #endif
880 /* to comfirm with newer lavc style */
881 mpi->qscale =pic->qscale_table;
882 mpi->qstride=pic->qstride;
883 mpi->pict_type=pic->pict_type;
884 mpi->qscale_type= pic->qscale_type;
885 mpi->fields = MP_IMGFIELD_ORDERED;
886 if(pic->interlaced_frame) mpi->fields |= MP_IMGFIELD_INTERLACED;
887 if(pic->top_field_first ) mpi->fields |= MP_IMGFIELD_TOP_FIRST;
888 if(pic->repeat_pict == 1) mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
890 return mpi;
893 static enum PixelFormat get_format(struct AVCodecContext *avctx,
894 const enum PixelFormat *fmt){
895 enum PixelFormat selected_format;
896 int imgfmt;
897 sh_video_t *sh = avctx->opaque;
898 int i;
900 for(i=0;fmt[i]!=PIX_FMT_NONE;i++){
901 imgfmt = pixfmt2imgfmt(fmt[i]);
902 if(!IMGFMT_IS_HWACCEL(imgfmt)) continue;
903 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
904 if(init_vo(sh, fmt[i]) >= 0) {
905 break;
908 selected_format = fmt[i];
909 return selected_format;
912 const struct vd_functions mpcodecs_vd_ffmpeg = {
913 .info = &info,
914 .init = init,
915 .uninit = uninit,
916 .control = control,
917 .decode2 = decode