13 #include "libavutil/common.h"
14 #include "ffmpeg_files/intreadwrite.h"
16 #include "fmt-conversion.h"
19 #include "img_format.h"
20 #include "libmpdemux/stheader.h"
21 #include "codec-cfg.h"
23 static const vd_info_t info
= {
24 "FFmpeg's libavcodec codec family",
27 "A'rpi, Michael, Alex",
31 #include "libavcodec/avcodec.h"
33 #if defined(__LINUX__) && defined(CONFIG_THREAD)
35 #elif defined(__BEOS__)
36 #include <kernel/OS.h>
37 #elif defined(__MACH__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
38 #include <sys/types.h>
39 #include <sys/sysctl.h>
40 #elif defined(__OpenBSD__)
41 #include <sys/param.h>
42 #include <sys/sysctl.h>
43 #include <machine/cpu.h>
46 #if AVPALETTE_SIZE > 1024
47 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
51 #include "libavcodec/xvmc.h"
54 int avcodec_initialized
=0;
57 AVCodecContext
*avctx
;
59 enum PixelFormat pix_fmt
;
71 AVRational last_sample_aspect_ratio
;
77 static int get_buffer(AVCodecContext
*avctx
, AVFrame
*pic
);
78 static void release_buffer(AVCodecContext
*avctx
, AVFrame
*pic
);
79 static void draw_slice(struct AVCodecContext
*s
, const AVFrame
*src
,
80 int offset
[4], int y
, int type
, int height
);
82 static enum PixelFormat
get_format(struct AVCodecContext
*avctx
,
83 const enum PixelFormat
*pix_fmt
);
84 static void uninit(struct sh_video
*sh
);
86 const m_option_t lavc_decode_opts_conf
[]={
87 OPT_INTRANGE("bug", lavc_param
.workaround_bugs
, 0, -1, 999999),
88 OPT_INTRANGE("er", lavc_param
.error_resilience
, 0, 0, 99),
89 OPT_FLAG_ON("gray", lavc_param
.gray
, 0),
90 OPT_INTRANGE("idct", lavc_param
.idct_algo
, 0, 0, 99),
91 OPT_INTRANGE("ec", lavc_param
.error_concealment
, 0, 0, 99),
92 OPT_FLAG_ON("vstats", lavc_param
.vstats
, 0),
93 OPT_INTRANGE("debug", lavc_param
.debug
, 0, 0, 9999999),
94 OPT_INTRANGE("vismv", lavc_param
.vismv
, 0, 0, 9999999),
95 OPT_INTRANGE("st", lavc_param
.skip_top
, 0, 0, 999),
96 OPT_INTRANGE("sb", lavc_param
.skip_bottom
, 0, 0, 999),
97 OPT_FLAG_CONSTANTS("fast", lavc_param
.fast
, 0, 0, CODEC_FLAG2_FAST
),
98 OPT_FLAG_CONSTANTS("h264fast", lavc_param
.h264fast
, 0, 0, 1), // Automatically enables "fast" if the codec is H.264
99 OPT_STRING("lowres", lavc_param
.lowres_str
, 0),
100 OPT_STRING("skiploopfilter", lavc_param
.skip_loop_filter_str
, 0),
101 OPT_STRING("skipidct", lavc_param
.skip_idct_str
, 0),
102 OPT_STRING("skipframe", lavc_param
.skip_frame_str
, 0),
103 OPT_INTRANGE("threads", lavc_param
.threads
, 0, 0, 8),
104 OPT_FLAG_CONSTANTS("bitexact", lavc_param
.bitexact
, 0, 0, CODEC_FLAG_BITEXACT
),
105 OPT_STRING("o", lavc_param
.avopt
, 0),
106 {NULL
, NULL
, 0, 0, 0, 0, NULL
}
109 static enum AVDiscard
str2AVDiscard(char *str
) {
110 if (!str
) return AVDISCARD_DEFAULT
;
111 if (strcasecmp(str
, "none" ) == 0) return AVDISCARD_NONE
;
112 if (strcasecmp(str
, "default") == 0) return AVDISCARD_DEFAULT
;
113 if (strcasecmp(str
, "nonref" ) == 0) return AVDISCARD_NONREF
;
114 if (strcasecmp(str
, "bidir" ) == 0) return AVDISCARD_BIDIR
;
115 if (strcasecmp(str
, "nonkey" ) == 0) return AVDISCARD_NONKEY
;
116 if (strcasecmp(str
, "all" ) == 0) return AVDISCARD_ALL
;
117 mp_msg(MSGT_DECVIDEO
, MSGL_ERR
, "Unknown discard value %s\n", str
);
118 return AVDISCARD_DEFAULT
;
121 // to set/get/query special features/parameters
122 static int control(sh_video_t
*sh
, int cmd
, void *arg
, ...){
123 vd_ffmpeg_ctx
*ctx
= sh
->context
;
124 AVCodecContext
*avctx
= ctx
->avctx
;
126 case VDCTRL_QUERY_FORMAT
:
128 int format
=(*((int *)arg
));
129 if(format
== ctx
->best_csp
) return CONTROL_TRUE
;//supported
130 // possible conversions:
135 // "converted" using pointer/stride modification
136 if(avctx
->pix_fmt
==PIX_FMT_YUV420P
) return CONTROL_TRUE
;// u/v swap
137 if(avctx
->pix_fmt
==PIX_FMT_YUV422P
&& !ctx
->do_dr1
) return CONTROL_TRUE
;// half stride
140 case IMGFMT_XVMC_IDCT_MPEG2
:
141 case IMGFMT_XVMC_MOCO_MPEG2
:
142 if(avctx
->pix_fmt
==PIX_FMT_XVMC_MPEG2_IDCT
) return CONTROL_TRUE
;
145 return CONTROL_FALSE
;
147 case VDCTRL_RESYNC_STREAM
:
148 avcodec_flush_buffers(avctx
);
150 case VDCTRL_QUERY_UNSEEN_FRAMES
:;
151 int delay
= avctx
->has_b_frames
;
152 #if defined(FF_THREAD_FRAME) && LIBAVCODEC_VERSION_MAJOR <= 52 && LIBAVCODEC_VERSION_MINOR < 49
153 // FFmpeg-mt has extra delay when using frame threading
154 // In newer versions that is included in has_b_frames
155 if (avctx
->thread_type
& FF_THREAD_FRAME
)
156 delay
+= avctx
->thread_count
- 1;
160 return CONTROL_UNKNOWN
;
164 static int init(sh_video_t
*sh
){
165 struct lavc_param
*lavc_param
= &sh
->opts
->lavc_param
;
166 AVCodecContext
*avctx
;
170 int do_vis_debug
= lavc_param
->vismv
|| (lavc_param
->debug
&(FF_DEBUG_VIS_MB_TYPE
|FF_DEBUG_VIS_QP
));
172 if(!avcodec_initialized
){
174 avcodec_register_all();
175 avcodec_initialized
=1;
178 ctx
= sh
->context
= malloc(sizeof(vd_ffmpeg_ctx
));
181 memset(ctx
, 0, sizeof(vd_ffmpeg_ctx
));
183 lavc_codec
= (AVCodec
*)avcodec_find_decoder_by_name(sh
->codec
->dll
);
185 mp_tmsg(MSGT_DECVIDEO
, MSGL_ERR
, "Cannot find codec '%s' in libavcodec...\n", sh
->codec
->dll
);
190 if(sh
->opts
->vd_use_slices
&& (lavc_codec
->capabilities
&CODEC_CAP_DRAW_HORIZ_BAND
) && !do_vis_debug
)
193 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
)
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();
202 avctx
->codec_type
= CODEC_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
) {
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 "
218 if (lavc_codec
->capabilities
& CODEC_CAP_HWACCEL_VDPAU
)
219 mp_msg(MSGT_DECVIDEO
, MSGL_V
, "[VD_FFMPEG] VDPAU hardware "
221 avctx
->slice_flags
= SLICE_FLAG_CODED_ORDER
|SLICE_FLAG_ALLOW_FIELD
;
224 if ( lavc_param
->threads
== 0 ) {
225 #if defined(__WIN32__)
226 lavc_param
->threads
= pthread_num_processors_np();
227 #elif defined(__LINUX__)
231 memset( &p_aff
, 0, sizeof(p_aff
) );
232 sched_getaffinity( 0, sizeof(p_aff
), &p_aff
);
233 for( np
= 0, bit
= 0; bit
< sizeof(p_aff
); bit
++ )
234 np
+= (((uint8_t *)&p_aff
)[bit
/ 8] >> (bit
% 8)) & 1;
236 lavc_param
->threads
= np
;
237 #elif defined(__BEOS__)
239 get_system_info( &info
);
240 lavc_param
->threads
= info
.cpu_count
;
242 #elif defined(__MACH__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
244 size_t length
= sizeof( numberOfCPUs
);
246 int mib
[2] = { CTL_HW
, HW_NCPU
};
247 if( sysctl(mib
, 2, &numberOfCPUs
, &length
, NULL
, 0) )
249 if( sysctlbyname("hw.ncpu", &numberOfCPUs
, &length
, NULL
, 0) )
254 lavc_param
->threads
= numberOfCPUs
;
255 #else /* No CPU detection routine available */
256 lavc_param
->threads
= 1;
260 if ( lavc_codec
->id
== CODEC_ID_MPEG4
) { /* Run away from packed b-frames (It is now blocked by ffmpeg-mt itself but show the warning anyway) */
261 mp_msg(MSGT_DECVIDEO
, MSGL_WARN
, "Multithreading is broken on MPEG-4 ASP, forcing only 1 thread.\n");
262 lavc_param
->threads
= 1;
263 } else if ( lavc_codec
->id
== CODEC_ID_VP3
|| lavc_codec
->id
== CODEC_ID_THEORA
) {
264 mp_msg(MSGT_DECVIDEO
, MSGL_WARN
, "Multithreading is broken on Theora, forcing only 1 thread.\n");
265 lavc_param
->threads
= 1;
267 mp_msg(MSGT_DECVIDEO
, MSGL_INFO
, "Using %d decoding thread%s.\n",
268 lavc_param
->threads
, lavc_param
->threads
== 1 ? "" : "s");
271 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
272 * from other threads. */
273 if (lavc_param
->threads
> 1) {
275 ctx
->do_slices
= false;
279 avctx
->flags
|= CODEC_FLAG_EMU_EDGE
;
280 avctx
->get_buffer
= get_buffer
;
281 avctx
->release_buffer
= release_buffer
;
282 avctx
->reget_buffer
= get_buffer
;
285 avctx
->flags
|= lavc_param
->bitexact
;
287 avctx
->width
= sh
->disp_w
;
288 avctx
->height
= sh
->disp_h
;
289 avctx
->workaround_bugs
= lavc_param
->workaround_bugs
;
290 avctx
->error_recognition
= lavc_param
->error_resilience
;
291 if(lavc_param
->gray
) avctx
->flags
|= CODEC_FLAG_GRAY
;
292 if(lavc_param
->h264fast
&& lavc_codec
->id
== CODEC_ID_H264
)
293 avctx
->flags2
|= CODEC_FLAG2_FAST
;
295 avctx
->flags2
|= lavc_param
->fast
;
296 avctx
->codec_tag
= sh
->format
;
297 avctx
->stream_codec_tag
= sh
->video
.fccHandler
;
298 avctx
->idct_algo
= lavc_param
->idct_algo
;
299 avctx
->error_concealment
= lavc_param
->error_concealment
;
300 avctx
->debug
= lavc_param
->debug
;
301 if (lavc_param
->debug
)
302 av_log_set_level(AV_LOG_DEBUG
);
303 avctx
->debug_mv
= lavc_param
->vismv
;
304 avctx
->skip_top
= lavc_param
->skip_top
;
305 avctx
->skip_bottom
= lavc_param
->skip_bottom
;
306 if(lavc_param
->lowres_str
!= NULL
)
308 sscanf(lavc_param
->lowres_str
, "%d,%d", &ctx
->lowres
, &lowres_w
);
309 if(ctx
->lowres
< 1 || ctx
->lowres
> 16 || (lowres_w
> 0 && avctx
->width
< lowres_w
))
311 avctx
->lowres
= ctx
->lowres
;
313 avctx
->skip_loop_filter
= str2AVDiscard(lavc_param
->skip_loop_filter_str
);
314 avctx
->skip_idct
= str2AVDiscard(lavc_param
->skip_idct_str
);
315 avctx
->skip_frame
= str2AVDiscard(lavc_param
->skip_frame_str
);
317 if(lavc_param
->avopt
){
318 if(parse_avopts(avctx
, lavc_param
->avopt
) < 0){
319 mp_msg(MSGT_DECVIDEO
, MSGL_ERR
, "Your options /%s/ look like gibberish to me pal\n", lavc_param
->avopt
);
325 mp_dbg(MSGT_DECVIDEO
, MSGL_DBG2
, "libavcodec.size: %d x %d\n", avctx
->width
, avctx
->height
);
326 switch (sh
->format
) {
327 case mmioFOURCC('S','V','Q','3'):
328 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
329 in the phony AVI header if demux_lavf is used. The first case is
330 handled here; the second case falls through to the next section. */
332 avctx
->extradata_size
= (*(int *)sh
->ImageDesc
) - sizeof(int);
333 avctx
->extradata
= av_mallocz(avctx
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
334 memcpy(avctx
->extradata
, ((int *)sh
->ImageDesc
)+1, avctx
->extradata_size
);
339 case mmioFOURCC('A','V','R','n'):
340 case mmioFOURCC('M','J','P','G'):
341 /* AVRn stores huffman table in AVI header */
342 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
344 if (!sh
->bih
|| sh
->bih
->biSize
<= sizeof(BITMAPINFOHEADER
))
346 avctx
->flags
|= CODEC_FLAG_EXTERN_HUFF
;
347 avctx
->extradata_size
= sh
->bih
->biSize
-sizeof(BITMAPINFOHEADER
);
348 avctx
->extradata
= av_mallocz(avctx
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
349 memcpy(avctx
->extradata
, sh
->bih
+1, avctx
->extradata_size
);
354 uint8_t *p
= avctx
->extradata
;
356 for (x
=0; x
<avctx
->extradata_size
; x
++)
357 mp_msg(MSGT_DECVIDEO
, MSGL_INFO
, "[%x] ", p
[x
]);
358 mp_msg(MSGT_DECVIDEO
, MSGL_INFO
, "\n");
363 case mmioFOURCC('R', 'V', '1', '0'):
364 case mmioFOURCC('R', 'V', '1', '3'):
365 case mmioFOURCC('R', 'V', '2', '0'):
366 case mmioFOURCC('R', 'V', '3', '0'):
367 case mmioFOURCC('R', 'V', '4', '0'):
368 if(sh
->bih
->biSize
<sizeof(*sh
->bih
)+8){
369 /* only 1 packet per frame & sub_id from fourcc */
370 avctx
->extradata_size
= 8;
371 avctx
->extradata
= av_mallocz(avctx
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
372 ((uint32_t *)avctx
->extradata
)[0] = 0;
373 ((uint32_t *)avctx
->extradata
)[1] =
374 (sh
->format
== mmioFOURCC('R', 'V', '1', '3')) ? 0x10003001 : 0x10000000;
376 /* has extra slice header (demux_rm or rm->avi streamcopy) */
377 avctx
->extradata_size
= sh
->bih
->biSize
-sizeof(BITMAPINFOHEADER
);
378 avctx
->extradata
= av_mallocz(avctx
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
379 memcpy(avctx
->extradata
, sh
->bih
+1, avctx
->extradata_size
);
381 avctx
->sub_id
= AV_RB32(avctx
->extradata
+4);
383 // printf("%X %X %d %d\n", extrahdr[0], extrahdr[1]);
387 if (!sh
->bih
|| sh
->bih
->biSize
<= sizeof(BITMAPINFOHEADER
))
389 avctx
->extradata_size
= sh
->bih
->biSize
-sizeof(BITMAPINFOHEADER
);
390 avctx
->extradata
= av_mallocz(avctx
->extradata_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
391 memcpy(avctx
->extradata
, sh
->bih
+1, avctx
->extradata_size
);
394 /* Pass palette to codec */
395 if (sh
->bih
&& (sh
->bih
->biBitCount
<= 8)) {
396 avctx
->palctrl
= calloc(1, sizeof(AVPaletteControl
));
397 avctx
->palctrl
->palette_changed
= 1;
398 if (sh
->bih
->biSize
-sizeof(BITMAPINFOHEADER
))
399 /* Palette size in biSize */
400 memcpy(avctx
->palctrl
->palette
, sh
->bih
+1,
401 FFMIN(sh
->bih
->biSize
-sizeof(BITMAPINFOHEADER
), AVPALETTE_SIZE
));
403 /* Palette size in biClrUsed */
404 memcpy(avctx
->palctrl
->palette
, sh
->bih
+1,
405 FFMIN(sh
->bih
->biClrUsed
* 4, AVPALETTE_SIZE
));
409 avctx
->bits_per_coded_sample
= sh
->bih
->biBitCount
;
411 if(lavc_param
->threads
> 1) {
412 avcodec_thread_init(avctx
, lavc_param
->threads
);
413 mp_msg(MSGT_DECVIDEO
, MSGL_WARN
, "WARNING: Multithreading is experimental and may break in weird ways.\n");
416 if (avcodec_open(avctx
, lavc_codec
) < 0) {
417 mp_tmsg(MSGT_DECVIDEO
, MSGL_ERR
, "Could not open codec.\n");
421 mp_msg(MSGT_DECVIDEO
, MSGL_V
, "INFO: libavcodec init OK!\n");
422 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
426 static void uninit(sh_video_t
*sh
){
427 vd_ffmpeg_ctx
*ctx
= sh
->context
;
428 AVCodecContext
*avctx
= ctx
->avctx
;
430 if(sh
->opts
->lavc_param
.vstats
){
433 mp_msg(MSGT_DECVIDEO
, MSGL_INFO
, "QP: %d, count: %d\n", i
, ctx
->qp_stat
[i
]);
435 mp_tmsg(MSGT_DECVIDEO
, MSGL_INFO
, "[VD_FFMPEG] Arithmetic mean of QP: %2.4f, Harmonic mean of QP: %2.4f\n",
436 ctx
->qp_sum
/ avctx
->coded_frame
->coded_picture_number
,
437 1.0/(ctx
->inv_qp_sum
/ avctx
->coded_frame
->coded_picture_number
)
442 if (avctx
->codec
&& avcodec_close(avctx
) < 0)
443 mp_tmsg(MSGT_DECVIDEO
, MSGL_ERR
, "Could not close codec.\n");
445 av_freep(&avctx
->extradata
);
446 av_freep(&avctx
->palctrl
);
447 av_freep(&avctx
->slice_offset
);
456 static void draw_slice(struct AVCodecContext
*s
,
457 const AVFrame
*src
, int offset
[4],
458 int y
, int type
, int height
){
459 sh_video_t
*sh
= s
->opaque
;
460 uint8_t *source
[MP_MAX_PLANES
]= {src
->data
[0] + offset
[0], src
->data
[1] + offset
[1], src
->data
[2] + offset
[2]};
464 vd_ffmpeg_ctx
*ctx
= sh
->context
;
465 int skip_stride
= ((width
<< ctx
->lowres
)+15)>>4;
466 uint8_t *skip
= &s
->coded_frame
->mbskip_table
[(y
>>4)*skip_stride
];
467 int threshold
= s
->coded_frame
->age
;
468 if(s
->pict_type
!=B_TYPE
){
469 for(i
=0; i
*16<width
+16; i
++){
470 if(i
*16>=width
|| skip
[i
]>=threshold
){
471 if(start
==i
) start
++;
473 uint8_t *src2
[3]= {src
[0] + start
*16,
476 //printf("%2d-%2d x %d\n", start, i, y);
477 mpcodecs_draw_slice (sh
, src2
, stride
, (i
-start
)*16, height
, start
*16, y
);
484 if (y
< sh
->disp_h
) {
485 mpcodecs_draw_slice (sh
, source
, src
->linesize
, sh
->disp_w
, (y
+height
)<=sh
->disp_h
?height
:sh
->disp_h
-y
, 0, y
);
490 static int init_vo(sh_video_t
*sh
, enum PixelFormat pix_fmt
){
491 vd_ffmpeg_ctx
*ctx
= sh
->context
;
492 AVCodecContext
*avctx
= ctx
->avctx
;
493 float aspect
= av_q2d(avctx
->sample_aspect_ratio
) * avctx
->width
/ avctx
->height
;
496 width
= avctx
->width
;
497 height
= avctx
->height
;
500 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
501 // use dimensions from BIH to avoid black borders at the right and bottom.
502 if (sh
->bih
&& sh
->ImageDesc
) {
503 width
= sh
->bih
->biWidth
>> ctx
->lowres
;
504 height
= sh
->bih
->biHeight
>> ctx
->lowres
;
507 // it is possible another vo buffers to be used after vo config()
508 // lavc reset its buffers on width/heigh change but not on aspect change!!!
509 if (av_cmp_q(avctx
->sample_aspect_ratio
, ctx
->last_sample_aspect_ratio
) ||
510 width
!= sh
->disp_w
||
511 height
!= sh
->disp_h
||
512 pix_fmt
!= ctx
->pix_fmt
||
513 !ctx
->vo_initialized
)
515 mp_msg(MSGT_DECVIDEO
, MSGL_V
, "[ffmpeg] aspect_ratio: %f\n", aspect
);
516 if (sh
->aspect
== 0 ||
517 av_cmp_q(avctx
->sample_aspect_ratio
,
518 ctx
->last_sample_aspect_ratio
))
520 ctx
->last_sample_aspect_ratio
= avctx
->sample_aspect_ratio
;
523 ctx
->pix_fmt
= pix_fmt
;
524 ctx
->best_csp
= pixfmt2imgfmt(pix_fmt
);
525 if (!mpcodecs_config_vo(sh
, sh
->disp_w
, sh
->disp_h
, ctx
->best_csp
))
527 ctx
->vo_initialized
= 1;
532 static int get_buffer(AVCodecContext
*avctx
, AVFrame
*pic
){
533 sh_video_t
*sh
= avctx
->opaque
;
534 vd_ffmpeg_ctx
*ctx
= sh
->context
;
535 mp_image_t
*mpi
=NULL
;
536 int flags
= MP_IMGFLAG_ACCEPT_STRIDE
| MP_IMGFLAG_PREFER_ALIGNED_STRIDE
;
537 int type
= MP_IMGTYPE_IPB
;
538 int width
= avctx
->width
;
539 int height
= avctx
->height
;
540 avcodec_align_dimensions(avctx
, &width
, &height
);
541 //printf("get_buffer %d %d %d\n", pic->reference, ctx->ip_count, ctx->b_count);
543 if (pic
->buffer_hints
) {
544 mp_msg(MSGT_DECVIDEO
, MSGL_DBG2
, "Buffer hints: %u\n", pic
->buffer_hints
);
545 type
= MP_IMGTYPE_TEMP
;
546 if (pic
->buffer_hints
& FF_BUFFER_HINTS_READABLE
)
547 flags
|= MP_IMGFLAG_READABLE
;
548 if (pic
->buffer_hints
& FF_BUFFER_HINTS_PRESERVE
) {
549 type
= MP_IMGTYPE_STATIC
;
550 flags
|= MP_IMGFLAG_PRESERVE
;
552 if (pic
->buffer_hints
& FF_BUFFER_HINTS_REUSABLE
) {
553 type
= MP_IMGTYPE_STATIC
;
554 flags
|= MP_IMGFLAG_PRESERVE
;
556 flags
|=(!avctx
->hurry_up
&& ctx
->do_slices
) ?
557 MP_IMGFLAG_DRAW_CALLBACK
:0;
558 mp_msg(MSGT_DECVIDEO
, MSGL_DBG2
, type
== MP_IMGTYPE_STATIC
? "using STATIC\n" : "using TEMP\n");
562 flags
|=(!avctx
->hurry_up
&& ctx
->do_slices
) ?
563 MP_IMGFLAG_DRAW_CALLBACK
:0;
566 flags
|= MP_IMGFLAG_PRESERVE
|MP_IMGFLAG_READABLE
567 | (ctx
->do_slices
? MP_IMGFLAG_DRAW_CALLBACK
: 0);
571 if(init_vo(sh
, avctx
->pix_fmt
) < 0){
572 avctx
->release_buffer
= avcodec_default_release_buffer
;
573 avctx
->get_buffer
= avcodec_default_get_buffer
;
574 return avctx
->get_buffer(avctx
, pic
);
577 if (IMGFMT_IS_XVMC(ctx
->best_csp
) || IMGFMT_IS_VDPAU(ctx
->best_csp
)) {
578 type
= MP_IMGTYPE_NUMBERED
| (0xffff << 16);
580 if (!pic
->buffer_hints
) {
581 if(ctx
->b_count
>1 || ctx
->ip_count
>2){
582 mp_tmsg(MSGT_DECVIDEO
, MSGL_WARN
, "[VD_FFMPEG] DRI failure.\n");
584 ctx
->do_dr1
=0; //FIXME
585 avctx
->get_buffer
= avcodec_default_get_buffer
;
586 return avctx
->get_buffer(avctx
, pic
);
589 if(avctx
->has_b_frames
){
590 type
= MP_IMGTYPE_IPB
;
594 mp_msg(MSGT_DECVIDEO
, MSGL_DBG2
, type
== MP_IMGTYPE_IPB
? "using IPB\n" : "using IP\n");
597 if (ctx
->best_csp
== IMGFMT_RGB8
|| ctx
->best_csp
== IMGFMT_BGR8
)
598 flags
|= MP_IMGFLAG_RGB_PALETTE
;
599 mpi
= mpcodecs_get_image(sh
, type
, flags
, width
, height
);
602 // ok, let's see what did we get:
603 if(mpi
->flags
&MP_IMGFLAG_DRAW_CALLBACK
&&
604 !(mpi
->flags
&MP_IMGFLAG_DIRECT
)){
605 // nice, filter/vo likes draw_callback :)
606 avctx
->draw_horiz_band
= draw_slice
;
608 avctx
->draw_horiz_band
= NULL
;
609 if(IMGFMT_IS_VDPAU(mpi
->imgfmt
)) {
610 avctx
->draw_horiz_band
= draw_slice
;
613 if(IMGFMT_IS_XVMC(mpi
->imgfmt
)) {
614 struct xvmc_pix_fmt
*render
= mpi
->priv
; //same as data[2]
615 avctx
->draw_horiz_band
= draw_slice
;
616 if(!avctx
->xvmc_acceleration
) {
617 mp_tmsg(MSGT_DECVIDEO
, MSGL_INFO
, "[VD_FFMPEG] The mc_get_buffer should work only with XVMC acceleration!!");
620 // return -1;//!!fixme check error conditions in ffmpeg
622 if(!(mpi
->flags
& MP_IMGFLAG_DIRECT
)) {
623 mp_tmsg(MSGT_DECVIDEO
, MSGL_ERR
, "[VD_FFMPEG] Only buffers allocated by vo_xvmc allowed.\n");
626 // return -1;//!!fixme check error conditions in ffmpeg
628 if(mp_msg_test(MSGT_DECVIDEO
, MSGL_DBG5
))
629 mp_msg(MSGT_DECVIDEO
, MSGL_DBG5
, "vd_ffmpeg::get_buffer (xvmc render=%p)\n", render
);
631 assert(render
->xvmc_id
== AV_XVMC_ID
);
632 render
->state
|= AV_XVMC_STATE_PREDICTION
;
636 pic
->data
[0]= mpi
->planes
[0];
637 pic
->data
[1]= mpi
->planes
[1];
638 pic
->data
[2]= mpi
->planes
[2];
639 pic
->data
[3]= mpi
->planes
[3];
642 assert(mpi
->width
>= ((width
+align
)&(~align
)));
643 assert(mpi
->height
>= ((height
+align
)&(~align
)));
644 assert(mpi
->stride
[0] >= mpi
->width
);
645 if(mpi
->imgfmt
==IMGFMT_I420
|| mpi
->imgfmt
==IMGFMT_YV12
|| mpi
->imgfmt
==IMGFMT_IYUV
){
646 const int y_size
= mpi
->stride
[0] * (mpi
->h
-1) + mpi
->w
;
647 const int c_size
= mpi
->stride
[1] * ((mpi
->h
>>1)-1) + (mpi
->w
>>1);
649 assert(mpi
->planes
[0] > mpi
->planes
[1] || mpi
->planes
[0] + y_size
<= mpi
->planes
[1]);
650 assert(mpi
->planes
[0] > mpi
->planes
[2] || mpi
->planes
[0] + y_size
<= mpi
->planes
[2]);
651 assert(mpi
->planes
[1] > mpi
->planes
[0] || mpi
->planes
[1] + c_size
<= mpi
->planes
[0]);
652 assert(mpi
->planes
[1] > mpi
->planes
[2] || mpi
->planes
[1] + c_size
<= mpi
->planes
[2]);
653 assert(mpi
->planes
[2] > mpi
->planes
[0] || mpi
->planes
[2] + c_size
<= mpi
->planes
[0]);
654 assert(mpi
->planes
[2] > mpi
->planes
[1] || mpi
->planes
[2] + c_size
<= mpi
->planes
[1]);
658 /* Note, some (many) codecs in libavcodec must have stride1==stride2 && no changes between frames
659 * lavc will check that and die with an error message, if its not true
661 pic
->linesize
[0]= mpi
->stride
[0];
662 pic
->linesize
[1]= mpi
->stride
[1];
663 pic
->linesize
[2]= mpi
->stride
[2];
664 pic
->linesize
[3]= mpi
->stride
[3];
667 //printf("%X\n", (int)mpi->planes[0]);
669 if(mpi
->flags
&MP_IMGFLAG_DIRECT
)
671 else if(mpi
->flags
&MP_IMGFLAG_DRAW_CALLBACK
)
677 pic
->age
= ctx
->ip_age
[0];
679 ctx
->ip_age
[0]= ctx
->ip_age
[1]+1;
683 pic
->age
= ctx
->b_age
;
689 pic
->type
= FF_BUFFER_TYPE_USER
;
691 /* The libavcodec reordered_opaque functionality is implemented by
692 * a similar copy in avcodec_default_get_buffer() and without a
693 * workaround like this it'd stop working when a custom buffer
696 pic
->reordered_opaque
= avctx
->reordered_opaque
;
700 static void release_buffer(struct AVCodecContext
*avctx
, AVFrame
*pic
){
701 mp_image_t
*mpi
= pic
->opaque
;
702 sh_video_t
*sh
= avctx
->opaque
;
703 vd_ffmpeg_ctx
*ctx
= sh
->context
;
706 //printf("release buffer %d %d %d\n", mpi ? mpi->flags&MP_IMGFLAG_PRESERVE : -99, ctx->ip_count, ctx->b_count);
708 if(ctx
->ip_count
<= 2 && ctx
->b_count
<=1){
709 if(mpi
->flags
&MP_IMGFLAG_PRESERVE
)
716 // Palette support: free palette buffer allocated in get_buffer
718 av_freep(&mpi
->planes
[1]);
720 if (IMGFMT_IS_XVMC(mpi
->imgfmt
)) {
721 struct xvmc_pix_fmt
*render
= (struct xvmc_pix_fmt
*)pic
->data
[2]; //same as mpi->priv
722 if(mp_msg_test(MSGT_DECVIDEO
, MSGL_DBG5
))
723 mp_msg(MSGT_DECVIDEO
, MSGL_DBG5
, "vd_ffmpeg::release_buffer (xvmc render=%p)\n", render
);
724 assert(render
!=NULL
);
725 assert(render
->xvmc_id
== AV_XVMC_ID
);
726 render
->state
&=~AV_XVMC_STATE_PREDICTION
;
729 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
733 if(pic
->type
!=FF_BUFFER_TYPE_USER
){
734 avcodec_default_release_buffer(avctx
, pic
);
741 //printf("R%X %X\n", pic->linesize[0], pic->data[0]);
744 // copypaste from demux_real.c - it should match to get it working!
745 //FIXME put into some header
746 typedef struct dp_hdr_s
{
747 uint32_t chunks
; // number of chunks
748 uint32_t timestamp
; // timestamp from packet header
749 uint32_t len
; // length of actual data
750 uint32_t chunktab
; // offset to chunk offset array
753 static void swap_palette(void *pal
) {
756 for (i
= 0; i
< AVPALETTE_COUNT
; i
++)
757 p
[i
] = le2me_32(p
[i
]);
761 static struct mp_image
*decode(struct sh_video
*sh
, void *data
, int len
,
762 int flags
, double *reordered_pts
)
766 vd_ffmpeg_ctx
*ctx
= sh
->context
;
767 AVFrame
*pic
= ctx
->pic
;
768 AVCodecContext
*avctx
= ctx
->avctx
;
769 struct lavc_param
*lavc_param
= &sh
->opts
->lavc_param
;
770 mp_image_t
*mpi
=NULL
;
771 int dr1
= ctx
->do_dr1
;
774 if(len
<=0) return NULL
; // skipped frame
776 //ffmpeg interlace (mpeg2) bug have been fixed. no need of -noslices
778 avctx
->draw_horiz_band
=NULL
;
779 if(ctx
->vo_initialized
&& !(flags
&3) && !dr1
){
780 mpi
=mpcodecs_get_image(sh
, MP_IMGTYPE_EXPORT
, MP_IMGFLAG_PRESERVE
|
781 (ctx
->do_slices
?MP_IMGFLAG_DRAW_CALLBACK
:0),
782 sh
->disp_w
, sh
->disp_h
);
783 if(mpi
&& mpi
->flags
&MP_IMGFLAG_DRAW_CALLBACK
){
784 // vd core likes slices!
785 avctx
->draw_horiz_band
=draw_slice
;
789 avctx
->hurry_up
=(flags
&3)?((flags
&2)?2:1):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
);
796 // HACK: make PNGs decode normally instead of as CorePNG delta frames
797 pkt
.flags
= PKT_FLAG_KEY
;
798 // The avcodec opaque field stupidly supports only int64_t type
799 *(double *)&avctx
->reordered_opaque
= *reordered_pts
;
800 ret
= avcodec_decode_video2(avctx
, pic
, &got_picture
, &pkt
);
801 *reordered_pts
= *(double *)&pic
->reordered_opaque
;
804 if(ret
<0) mp_msg(MSGT_DECVIDEO
, MSGL_WARN
, "Error while decoding frame!\n");
805 //printf("repeat: %d\n", pic->repeat_pict);
806 //-- vstats generation
807 while(lavc_param
->vstats
){ // always one time loop
808 static FILE *fvstats
=NULL
;
810 static long long int all_len
=0;
811 static int frame_number
=0;
812 static double all_frametime
=0.0;
813 AVFrame
*pic
= avctx
->coded_frame
;
820 today
= localtime(&today2
);
821 sprintf(filename
, "vstats_%02d%02d%02d.log", today
->tm_hour
,
822 today
->tm_min
, today
->tm_sec
);
823 fvstats
= fopen(filename
, "w");
826 lavc_param
->vstats
=0; // disable block
832 // average MB quantizer
835 int w
= ((avctx
->width
<< ctx
->lowres
)+15) >> 4;
836 int h
= ((avctx
->height
<< ctx
->lowres
)+15) >> 4;
837 int8_t *q
= pic
->qscale_table
;
838 for(y
= 0; y
< h
; y
++) {
839 for(x
= 0; x
< w
; x
++)
840 quality
+= (double)*(q
+x
);
847 all_frametime
+=sh
->frametime
;
848 fprintf(fvstats
, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
849 ++frame_number
, quality
, len
, (double)all_len
/1024);
850 fprintf(fvstats
, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
851 all_frametime
, (double)(len
*8)/sh
->frametime
/1000.0,
852 (double)(all_len
*8)/all_frametime
/1000.0);
853 switch(pic
->pict_type
){
855 fprintf(fvstats
, "type= I\n");
858 fprintf(fvstats
, "type= P\n");
861 fprintf(fvstats
, "type= S\n");
864 fprintf(fvstats
, "type= B\n");
867 fprintf(fvstats
, "type= ? (%d)\n", pic
->pict_type
);
871 ctx
->qp_stat
[(int)(quality
+0.5)]++;
872 ctx
->qp_sum
+= quality
;
873 ctx
->inv_qp_sum
+= 1.0/(double)quality
;
879 if(!got_picture
) return NULL
; // skipped image
881 if(init_vo(sh
, avctx
->pix_fmt
) < 0) return NULL
;
883 if(dr1
&& pic
->opaque
){
884 mpi
= (mp_image_t
*)pic
->opaque
;
888 mpi
=mpcodecs_get_image(sh
, MP_IMGTYPE_EXPORT
, MP_IMGFLAG_PRESERVE
,
889 avctx
->width
, avctx
->height
);
890 if(!mpi
){ // temporary!
891 mp_tmsg(MSGT_DECVIDEO
, MSGL_WARN
, "[VD_FFMPEG] Couldn't allocate image for codec.\n");
896 mpi
->planes
[0]=pic
->data
[0];
897 mpi
->planes
[1]=pic
->data
[1];
898 mpi
->planes
[2]=pic
->data
[2];
899 mpi
->planes
[3]=pic
->data
[3];
900 mpi
->stride
[0]=pic
->linesize
[0];
901 mpi
->stride
[1]=pic
->linesize
[1];
902 mpi
->stride
[2]=pic
->linesize
[2];
903 mpi
->stride
[3]=pic
->linesize
[3];
909 if(avctx
->pix_fmt
==PIX_FMT_YUV422P
&& mpi
->chroma_y_shift
==1){
910 // we have 422p but user wants 420p
916 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
918 swap_palette(mpi
->planes
[1]);
920 /* to comfirm with newer lavc style */
921 mpi
->qscale
=pic
->qscale_table
;
922 mpi
->qstride
=pic
->qstride
;
923 mpi
->pict_type
=pic
->pict_type
;
924 mpi
->qscale_type
= pic
->qscale_type
;
925 mpi
->fields
= MP_IMGFIELD_ORDERED
;
926 if(pic
->interlaced_frame
) mpi
->fields
|= MP_IMGFIELD_INTERLACED
;
927 if(pic
->top_field_first
) mpi
->fields
|= MP_IMGFIELD_TOP_FIRST
;
928 if(pic
->repeat_pict
== 1) mpi
->fields
|= MP_IMGFIELD_REPEAT_FIRST
;
933 static enum PixelFormat
get_format(struct AVCodecContext
*avctx
,
934 const enum PixelFormat
*fmt
){
935 enum PixelFormat selected_format
;
937 sh_video_t
*sh
= avctx
->opaque
;
940 for(i
=0;fmt
[i
]!=PIX_FMT_NONE
;i
++){
941 imgfmt
= pixfmt2imgfmt(fmt
[i
]);
942 if(!IMGFMT_IS_XVMC(imgfmt
) && !IMGFMT_IS_VDPAU(imgfmt
)) continue;
943 mp_msg(MSGT_DECVIDEO
, MSGL_V
, "[VD_FFMPEG] Trying pixfmt=%d.\n", i
);
944 if(init_vo(sh
, fmt
[i
]) >= 0) {
948 selected_format
= fmt
[i
];
949 return selected_format
;
952 const struct vd_functions mpcodecs_vd_ffmpeg
= {