docs: convert manpage contents into reStructuredText markup
[mplayer.git] / libmpcodecs / vd_ffmpeg.c
blob834503aba6fde24aed6524c82ff75e0ec58b97be
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 <libavutil/common.h>
26 #include <libavutil/opt.h>
27 #include <libavutil/intreadwrite.h>
29 #include "talloc.h"
30 #include "config.h"
31 #include "mp_msg.h"
32 #include "options.h"
33 #include "av_opts.h"
35 #include "mpbswap.h"
36 #include "fmt-conversion.h"
38 #include "vd.h"
39 #include "img_format.h"
40 #include "libmpdemux/stheader.h"
41 #include "libmpdemux/demux_packet.h"
42 #include "codec-cfg.h"
43 #include "osdep/numcores.h"
44 #include "libvo/csputils.h"
46 static const vd_info_t info = {
47 "libavcodec video codecs",
48 "ffmpeg",
49 "",
50 "",
51 "native codecs",
52 .print_name = "libavcodec",
55 #include "libavcodec/avcodec.h"
57 #if AVPALETTE_SIZE > 1024
58 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
59 #endif
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 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 enum AVDiscard skip_frame;
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_FLAG_ON("gray", lavc_param.gray, 0),
92 OPT_INTRANGE("idct", lavc_param.idct_algo, 0, 0, 99),
93 OPT_INTRANGE("ec", lavc_param.error_concealment, 0, 0, 99),
94 OPT_FLAG_ON("vstats", lavc_param.vstats, 0),
95 OPT_INTRANGE("debug", lavc_param.debug, 0, 0, 9999999),
96 OPT_INTRANGE("vismv", lavc_param.vismv, 0, 0, 9999999),
97 OPT_INTRANGE("st", lavc_param.skip_top, 0, 0, 999),
98 OPT_INTRANGE("sb", lavc_param.skip_bottom, 0, 0, 999),
99 OPT_FLAG_CONSTANTS("fast", lavc_param.fast, 0, 0, CODEC_FLAG2_FAST),
100 OPT_STRING("lowres", lavc_param.lowres_str, 0),
101 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
102 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
103 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
104 OPT_INTRANGE("threads", lavc_param.threads, 0, 0, 16),
105 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
106 OPT_STRING("o", lavc_param.avopt, 0),
107 {NULL, NULL, 0, 0, 0, 0, NULL}
110 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 static int init(sh_video_t *sh)
125 struct lavc_param *lavc_param = &sh->opts->lavc_param;
126 AVCodecContext *avctx;
127 vd_ffmpeg_ctx *ctx;
128 AVCodec *lavc_codec;
129 int do_vis_debug = lavc_param->vismv ||
130 (lavc_param->debug & (FF_DEBUG_VIS_MB_TYPE | FF_DEBUG_VIS_QP));
132 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
134 if (sh->codec->dll) {
135 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
136 if (!lavc_codec) {
137 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR,
138 "Cannot find codec '%s' in libavcodec...\n",
139 sh->codec->dll);
140 uninit(sh);
141 return 0;
143 } else if (!sh->libav_codec_id) {
144 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "No Libav codec ID known. "
145 "Generic lavc decoder is not applicable.\n");
146 return 0;
147 } else {
148 lavc_codec = avcodec_find_decoder(sh->libav_codec_id);
149 if (!lavc_codec) {
150 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "Libavcodec has no decoder "
151 "for this codec\n");
152 return 0;
156 sh->codecname = lavc_codec->long_name;
157 if (!sh->codecname)
158 sh->codecname = lavc_codec->name;
160 if (sh->opts->vd_use_slices
161 && (lavc_codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)
162 && !do_vis_debug)
163 ctx->do_slices = 1;
165 if (lavc_codec->capabilities & CODEC_CAP_DR1 && !do_vis_debug
166 && lavc_codec->id != CODEC_ID_H264
167 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO
168 && lavc_codec->id != CODEC_ID_ROQ && lavc_codec->id != CODEC_ID_VP8
169 && lavc_codec->id != CODEC_ID_LAGARITH)
170 ctx->do_dr1 = 1;
171 ctx->ip_count = ctx->b_count = 0;
173 ctx->pic = avcodec_alloc_frame();
174 ctx->avctx = avcodec_alloc_context3(lavc_codec);
175 avctx = ctx->avctx;
176 avctx->opaque = sh;
177 avctx->codec_type = AVMEDIA_TYPE_VIDEO;
178 avctx->codec_id = lavc_codec->id;
180 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
181 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
182 ctx->do_dr1 = true;
183 ctx->do_slices = true;
184 lavc_param->threads = 1;
185 avctx->get_format = get_format;
186 avctx->get_buffer = get_buffer;
187 avctx->release_buffer = release_buffer;
188 avctx->reget_buffer = get_buffer;
189 avctx->draw_horiz_band = draw_slice;
190 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
191 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
192 "decoding.\n");
193 avctx->slice_flags = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
196 if (lavc_param->threads == 0) {
197 int threads = default_thread_count();
198 if (threads < 1) {
199 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Could not determine "
200 "thread count to use, defaulting to 1.\n");
201 threads = 1;
203 threads = FFMIN(threads, 16);
204 lavc_param->threads = threads;
206 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
207 * from other threads. */
208 if (lavc_param->threads > 1) {
209 ctx->do_dr1 = false;
210 ctx->do_slices = false;
211 mp_tmsg(MSGT_DECVIDEO, MSGL_V, "Asking decoder to use "
212 "%d threads if supported.\n", lavc_param->threads);
215 if (ctx->do_dr1) {
216 avctx->flags |= CODEC_FLAG_EMU_EDGE;
217 avctx->get_buffer = get_buffer;
218 avctx->release_buffer = release_buffer;
219 avctx->reget_buffer = get_buffer;
222 avctx->flags |= lavc_param->bitexact;
224 avctx->coded_width = sh->disp_w;
225 avctx->coded_height = sh->disp_h;
226 avctx->workaround_bugs = lavc_param->workaround_bugs;
227 if (lavc_param->gray)
228 avctx->flags |= CODEC_FLAG_GRAY;
229 avctx->flags2 |= lavc_param->fast;
230 avctx->codec_tag = sh->format;
231 avctx->stream_codec_tag = sh->video.fccHandler;
232 avctx->idct_algo = lavc_param->idct_algo;
233 avctx->error_concealment = lavc_param->error_concealment;
234 avctx->debug = lavc_param->debug;
235 if (lavc_param->debug)
236 av_log_set_level(AV_LOG_DEBUG);
237 avctx->debug_mv = lavc_param->vismv;
238 avctx->skip_top = lavc_param->skip_top;
239 avctx->skip_bottom = lavc_param->skip_bottom;
240 if (lavc_param->lowres_str != NULL) {
241 int lowres, lowres_w;
242 sscanf(lavc_param->lowres_str, "%d,%d", &lowres, &lowres_w);
243 if (lowres < 1 || lowres > 16 ||
244 lowres_w > 0 && avctx->width < lowres_w)
245 lowres = 0;
246 avctx->lowres = lowres;
248 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
249 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
250 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
252 if (lavc_param->avopt) {
253 if (parse_avopts(avctx, lavc_param->avopt) < 0) {
254 mp_msg(MSGT_DECVIDEO, MSGL_ERR,
255 "Your options /%s/ look like gibberish to me pal\n",
256 lavc_param->avopt);
257 uninit(sh);
258 return 0;
262 // Do this after the above avopt handling in case it changes values
263 ctx->skip_frame = avctx->skip_frame;
265 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2,
266 "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
267 switch (sh->format) {
268 case mmioFOURCC('S','V','Q','3'):
269 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
270 * in the phony AVI header if demux_lavf is used. The first case is
271 * handled here; the second case falls through to the next section. */
272 if (sh->ImageDesc) {
273 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
274 avctx->extradata = av_mallocz(avctx->extradata_size +
275 FF_INPUT_BUFFER_PADDING_SIZE);
276 memcpy(avctx->extradata, ((int *)sh->ImageDesc) + 1,
277 avctx->extradata_size);
278 break;
280 /* fallthrough */
282 case mmioFOURCC('A','V','R','n'):
283 case mmioFOURCC('M','J','P','G'):
284 /* AVRn stores huffman table in AVI header */
285 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
286 * MJPG fourcc :( */
287 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
288 break;
289 av_opt_set_int(avctx, "extern_huff", 1, AV_OPT_SEARCH_CHILDREN);
290 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
291 avctx->extradata = av_mallocz(avctx->extradata_size +
292 FF_INPUT_BUFFER_PADDING_SIZE);
293 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
294 break;
296 case mmioFOURCC('R','V','1','0'):
297 case mmioFOURCC('R','V','1','3'):
298 case mmioFOURCC('R','V','2','0'):
299 case mmioFOURCC('R','V','3','0'):
300 case mmioFOURCC('R','V','4','0'):
301 if (sh->bih->biSize < sizeof(*sh->bih) + 8) {
302 // only 1 packet per frame & sub_id from fourcc
303 avctx->extradata_size = 8;
304 avctx->extradata = av_mallocz(avctx->extradata_size +
305 FF_INPUT_BUFFER_PADDING_SIZE);
306 ((uint32_t *)avctx->extradata)[0] = 0;
307 ((uint32_t *)avctx->extradata)[1] =
308 sh->format == mmioFOURCC('R','V','1','3') ?
309 0x10003001 : 0x10000000;
310 } else {
311 // has extra slice header (demux_rm or rm->avi streamcopy)
312 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
313 avctx->extradata = av_mallocz(avctx->extradata_size +
314 FF_INPUT_BUFFER_PADDING_SIZE);
315 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
317 break;
319 default:
320 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
321 break;
322 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
323 avctx->extradata = av_mallocz(avctx->extradata_size +
324 FF_INPUT_BUFFER_PADDING_SIZE);
325 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
326 break;
329 if (sh->bih)
330 avctx->bits_per_coded_sample = sh->bih->biBitCount;
332 avctx->thread_count = lavc_param->threads;
334 /* open it */
335 if (avcodec_open2(avctx, lavc_codec, NULL) < 0) {
336 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
337 uninit(sh);
338 return 0;
340 return 1;
343 static void uninit(sh_video_t *sh)
345 vd_ffmpeg_ctx *ctx = sh->context;
346 AVCodecContext *avctx = ctx->avctx;
348 sh->codecname = NULL;
349 if (sh->opts->lavc_param.vstats && avctx->coded_frame) {
350 for (int i = 1; i < 32; i++)
351 mp_msg(MSGT_DECVIDEO, MSGL_INFO,
352 "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
353 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: "
354 "%2.4f, Harmonic mean of QP: %2.4f\n",
355 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
356 1.0 / (ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number));
359 if (avctx) {
360 if (avctx->codec && avcodec_close(avctx) < 0)
361 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
363 av_freep(&avctx->extradata);
364 av_freep(&avctx->slice_offset);
367 av_freep(&avctx);
368 av_freep(&ctx->pic);
369 talloc_free(ctx);
372 static void draw_slice(struct AVCodecContext *s,
373 const AVFrame *src, int offset[4],
374 int y, int type, int height)
376 sh_video_t *sh = s->opaque;
377 uint8_t *source[MP_MAX_PLANES] = {
378 src->data[0] + offset[0], src->data[1] + offset[1],
379 src->data[2] + offset[2]
381 int strides[MP_MAX_PLANES] = {
382 src->linesize[0], src->linesize[1], src->linesize[2]
384 if (height < 0) {
385 int i;
386 height = -height;
387 y -= height;
388 for (i = 0; i < MP_MAX_PLANES; i++) {
389 strides[i] = -strides[i];
390 source[i] -= strides[i];
393 if (y < sh->disp_h) {
394 height = FFMIN(height, sh->disp_h - y);
395 mpcodecs_draw_slice(sh, source, strides, sh->disp_w, height, 0, y);
399 static enum mp_csp avcol_spc_to_mp_csp(enum AVColorSpace colorspace)
401 switch (colorspace) {
402 case AVCOL_SPC_BT709:
403 return MP_CSP_BT_709;
404 break;
405 case AVCOL_SPC_BT470BG:
406 case AVCOL_SPC_SMPTE170M:
407 return MP_CSP_BT_601;
408 break;
409 case AVCOL_SPC_SMPTE240M:
410 return MP_CSP_SMPTE_240M;
411 break;
412 default:
413 return MP_CSP_AUTO;
417 static enum mp_csp_levels avcol_range_to_mp_csp_levels(enum AVColorRange range)
419 switch (range) {
420 case AVCOL_RANGE_MPEG:
421 return MP_CSP_LEVELS_TV;
422 break;
423 case AVCOL_RANGE_JPEG:
424 return MP_CSP_LEVELS_PC;
425 break;
426 default:
427 return MP_CSP_LEVELS_AUTO;
431 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt)
433 vd_ffmpeg_ctx *ctx = sh->context;
434 AVCodecContext *avctx = ctx->avctx;
435 float aspect = av_q2d(avctx->sample_aspect_ratio) *
436 avctx->width / avctx->height;
437 int width, height;
439 width = avctx->width;
440 height = avctx->height;
442 // HACK!
443 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
444 // use dimensions from BIH to avoid black borders at the right and bottom.
445 if (sh->bih && sh->ImageDesc) {
446 width = sh->bih->biWidth >> avctx->lowres;
447 height = sh->bih->biHeight >> avctx->lowres;
450 /* Reconfiguring filter/VO chain may invalidate direct rendering buffers
451 * we have allocated for libavcodec (including the VDPAU HW decoding
452 * case). Is it guaranteed that the code below only triggers in a situation
453 * with no busy direct rendering buffers for reference frames?
455 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
456 width != sh->disp_w || height != sh->disp_h ||
457 pix_fmt != ctx->pix_fmt || !ctx->vo_initialized) {
458 ctx->vo_initialized = 0;
459 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
461 // Do not overwrite s->aspect on the first call, so that a container
462 // aspect if available is preferred.
463 // But set it even if the sample aspect did not change, since a
464 // resolution change can cause an aspect change even if the
465 // _sample_ aspect is unchanged.
466 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
467 sh->aspect = aspect;
468 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
469 sh->disp_w = width;
470 sh->disp_h = height;
471 ctx->pix_fmt = pix_fmt;
472 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
473 const unsigned int *supported_fmts;
474 if (ctx->best_csp == IMGFMT_YV12)
475 supported_fmts = (const unsigned int[]){
476 IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
478 else if (ctx->best_csp == IMGFMT_422P)
479 supported_fmts = (const unsigned int[]){
480 IMGFMT_422P, IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
482 else
483 supported_fmts = (const unsigned int[]){ctx->best_csp, 0xffffffff};
485 sh->colorspace = avcol_spc_to_mp_csp(avctx->colorspace);
486 sh->color_range = avcol_range_to_mp_csp_levels(avctx->color_range);
488 if (!mpcodecs_config_vo2(sh, sh->disp_w, sh->disp_h, supported_fmts,
489 ctx->best_csp))
490 return -1;
491 ctx->vo_initialized = 1;
493 return 0;
496 static int get_buffer(AVCodecContext *avctx, AVFrame *pic)
498 sh_video_t *sh = avctx->opaque;
499 vd_ffmpeg_ctx *ctx = sh->context;
500 mp_image_t *mpi = NULL;
501 int flags = MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE |
502 MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
503 int type = MP_IMGTYPE_IPB;
504 int width = avctx->width;
505 int height = avctx->height;
506 // special case to handle reget_buffer without buffer hints
507 if (pic->opaque && pic->data[0] && !pic->buffer_hints)
508 return 0;
509 avcodec_align_dimensions(avctx, &width, &height);
511 if (pic->buffer_hints) {
512 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n",
513 pic->buffer_hints);
514 type = MP_IMGTYPE_TEMP;
515 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
516 flags |= MP_IMGFLAG_READABLE;
517 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
518 type = MP_IMGTYPE_STATIC;
519 flags |= MP_IMGFLAG_PRESERVE;
521 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
522 type = MP_IMGTYPE_STATIC;
523 flags |= MP_IMGFLAG_PRESERVE;
525 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
526 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
527 type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
528 } else {
529 if (!pic->reference) {
530 ctx->b_count++;
531 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
532 } else {
533 ctx->ip_count++;
534 flags |= MP_IMGFLAG_PRESERVE | MP_IMGFLAG_READABLE
535 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
539 if (init_vo(sh, avctx->pix_fmt) < 0) {
540 avctx->release_buffer = avcodec_default_release_buffer;
541 avctx->get_buffer = avcodec_default_get_buffer;
542 avctx->reget_buffer = avcodec_default_reget_buffer;
543 if (pic->data[0])
544 release_buffer(avctx, pic);
545 return avctx->get_buffer(avctx, pic);
548 if (IMGFMT_IS_HWACCEL(ctx->best_csp))
549 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
550 else if (!pic->buffer_hints) {
551 if (ctx->b_count > 1 || ctx->ip_count > 2) {
552 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
554 ctx->do_dr1 = 0; //FIXME
555 avctx->get_buffer = avcodec_default_get_buffer;
556 avctx->reget_buffer = avcodec_default_reget_buffer;
557 if (pic->data[0])
558 release_buffer(avctx, pic);
559 return avctx->get_buffer(avctx, pic);
562 if (avctx->has_b_frames || ctx->b_count)
563 type = MP_IMGTYPE_IPB;
564 else
565 type = MP_IMGTYPE_IP;
566 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
567 type == MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
570 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
571 flags |= MP_IMGFLAG_RGB_PALETTE;
572 mpi = mpcodecs_get_image(sh, type, flags, width, height);
573 if (!mpi)
574 return -1;
576 // ok, let's see what did we get:
577 if (mpi->flags & MP_IMGFLAG_DRAW_CALLBACK &&
578 !(mpi->flags & MP_IMGFLAG_DIRECT)) {
579 // nice, filter/vo likes draw_callback :)
580 avctx->draw_horiz_band = draw_slice;
581 } else
582 avctx->draw_horiz_band = NULL;
583 if (IMGFMT_IS_HWACCEL(mpi->imgfmt))
584 avctx->draw_horiz_band = draw_slice;
586 pic->data[0] = mpi->planes[0];
587 pic->data[1] = mpi->planes[1];
588 pic->data[2] = mpi->planes[2];
589 pic->data[3] = mpi->planes[3];
591 /* Note: some (many) codecs in libavcodec require
592 * linesize[1] == linesize[2] and no changes between frames.
593 * Lavc will check that and die with an error message if it's not true.
595 pic->linesize[0] = mpi->stride[0];
596 pic->linesize[1] = mpi->stride[1];
597 pic->linesize[2] = mpi->stride[2];
598 pic->linesize[3] = mpi->stride[3];
600 pic->opaque = mpi;
602 pic->type = FF_BUFFER_TYPE_USER;
604 /* The libavcodec reordered_opaque functionality is implemented by
605 * a similar copy in avcodec_default_get_buffer() and without a
606 * workaround like this it'd stop working when a custom buffer
607 * callback is used.
609 pic->reordered_opaque = avctx->reordered_opaque;
610 return 0;
613 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic)
615 mp_image_t *mpi = pic->opaque;
616 sh_video_t *sh = avctx->opaque;
617 vd_ffmpeg_ctx *ctx = sh->context;
619 if (ctx->ip_count <= 2 && ctx->b_count <= 1) {
620 if (mpi->flags & MP_IMGFLAG_PRESERVE)
621 ctx->ip_count--;
622 else
623 ctx->b_count--;
626 if (mpi) {
627 // Palette support: free palette buffer allocated in get_buffer
628 if (mpi->bpp == 8)
629 av_freep(&mpi->planes[1]);
630 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
631 mpi->usage_count--;
634 if (pic->type != FF_BUFFER_TYPE_USER) {
635 avcodec_default_release_buffer(avctx, pic);
636 return;
639 for (int i = 0; i < 4; i++)
640 pic->data[i] = NULL;
643 static av_unused void swap_palette(void *pal)
645 int i;
646 uint32_t *p = pal;
647 for (i = 0; i < AVPALETTE_COUNT; i++)
648 p[i] = le2me_32(p[i]);
651 static struct mp_image *decode(struct sh_video *sh, struct demux_packet *packet,
652 void *data, int len, int flags,
653 double *reordered_pts)
655 int got_picture = 0;
656 int ret;
657 vd_ffmpeg_ctx *ctx = sh->context;
658 AVFrame *pic = ctx->pic;
659 AVCodecContext *avctx = ctx->avctx;
660 struct lavc_param *lavc_param = &sh->opts->lavc_param;
661 mp_image_t *mpi = NULL;
662 int dr1 = ctx->do_dr1;
663 AVPacket pkt;
665 if (!dr1)
666 avctx->draw_horiz_band = NULL;
668 if (flags & 2)
669 avctx->skip_frame = AVDISCARD_ALL;
670 else if (flags & 1)
671 avctx->skip_frame = AVDISCARD_NONREF;
672 else
673 avctx->skip_frame = ctx->skip_frame;
675 av_init_packet(&pkt);
676 pkt.data = data;
677 pkt.size = len;
678 /* Some codecs (ZeroCodec, some cases of PNG) may want keyframe info
679 * from demuxer. */
680 if (packet && packet->keyframe)
681 pkt.flags |= AV_PKT_FLAG_KEY;
682 if (packet && packet->avpacket) {
683 pkt.side_data = packet->avpacket->side_data;
684 pkt.side_data_elems = packet->avpacket->side_data_elems;
686 // The avcodec opaque field stupidly supports only int64_t type
687 union pts { int64_t i; double d; };
688 avctx->reordered_opaque = (union pts){.d = *reordered_pts}.i;
689 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
690 *reordered_pts = (union pts){.i = pic->reordered_opaque}.d;
692 dr1 = ctx->do_dr1;
693 if (ret < 0)
694 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
695 //-- vstats generation
696 while (lavc_param->vstats) { // always one time loop
697 static FILE *fvstats = NULL;
698 char filename[20];
699 static long long int all_len = 0;
700 static int frame_number = 0;
701 static double all_frametime = 0.0;
702 AVFrame *pic = avctx->coded_frame;
703 double quality = 0.0;
705 if (!pic)
706 break;
708 if (!fvstats) {
709 time_t today2;
710 struct tm *today;
711 today2 = time(NULL);
712 today = localtime(&today2);
713 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
714 today->tm_min, today->tm_sec);
715 fvstats = fopen(filename, "w");
716 if (!fvstats) {
717 perror("fopen");
718 lavc_param->vstats = 0; // disable block
719 break;
720 /*exit(1);*/
724 // average MB quantizer
726 int x, y;
727 int w = ((avctx->width << avctx->lowres) + 15) >> 4;
728 int h = ((avctx->height << avctx->lowres) + 15) >> 4;
729 int8_t *q = pic->qscale_table;
730 for (y = 0; y < h; y++) {
731 for (x = 0; x < w; x++)
732 quality += (double)*(q + x);
733 q += pic->qstride;
735 quality /= w * h;
738 all_len += len;
739 all_frametime += sh->frametime;
740 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
741 ++frame_number, quality, len, (double)all_len / 1024);
742 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
743 all_frametime, (double)(len * 8) / sh->frametime / 1000.0,
744 (double)(all_len * 8) / all_frametime / 1000.0);
745 switch (pic->pict_type) {
746 case AV_PICTURE_TYPE_I:
747 fprintf(fvstats, "type= I\n");
748 break;
749 case AV_PICTURE_TYPE_P:
750 fprintf(fvstats, "type= P\n");
751 break;
752 case AV_PICTURE_TYPE_S:
753 fprintf(fvstats, "type= S\n");
754 break;
755 case AV_PICTURE_TYPE_B:
756 fprintf(fvstats, "type= B\n");
757 break;
758 default:
759 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
760 break;
763 ctx->qp_stat[(int)(quality + 0.5)]++;
764 ctx->qp_sum += quality;
765 ctx->inv_qp_sum += 1.0 / (double)quality;
767 break;
769 //--
771 if (!got_picture)
772 return NULL; // skipped image
774 if (init_vo(sh, avctx->pix_fmt) < 0)
775 return NULL;
777 if (dr1 && pic->opaque)
778 mpi = (mp_image_t *)pic->opaque;
780 if (!mpi)
781 mpi = mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
782 avctx->width, avctx->height);
783 if (!mpi) { // temporary error?
784 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN,
785 "[VD_FFMPEG] Couldn't allocate image for codec.\n");
786 return NULL;
789 if (!dr1) {
790 mpi->planes[0] = pic->data[0];
791 mpi->planes[1] = pic->data[1];
792 mpi->planes[2] = pic->data[2];
793 mpi->planes[3] = pic->data[3];
794 mpi->stride[0] = pic->linesize[0];
795 mpi->stride[1] = pic->linesize[1];
796 mpi->stride[2] = pic->linesize[2];
797 mpi->stride[3] = pic->linesize[3];
800 if (!mpi->planes[0])
801 return NULL;
803 if (ctx->best_csp == IMGFMT_422P && mpi->chroma_y_shift == 1) {
804 // we have 422p but user wants 420p
805 mpi->stride[1] *= 2;
806 mpi->stride[2] *= 2;
809 #if HAVE_BIGENDIAN
810 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
811 if (mpi->bpp == 8)
812 swap_palette(mpi->planes[1]);
813 #endif
815 mpi->qscale = pic->qscale_table;
816 mpi->qstride = pic->qstride;
817 mpi->pict_type = pic->pict_type;
818 mpi->qscale_type = pic->qscale_type;
819 mpi->fields = MP_IMGFIELD_ORDERED;
820 if (pic->interlaced_frame)
821 mpi->fields |= MP_IMGFIELD_INTERLACED;
822 if (pic->top_field_first)
823 mpi->fields |= MP_IMGFIELD_TOP_FIRST;
824 if (pic->repeat_pict == 1)
825 mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
827 return mpi;
830 static enum PixelFormat get_format(struct AVCodecContext *avctx,
831 const enum PixelFormat *fmt)
833 sh_video_t *sh = avctx->opaque;
834 int i;
836 for (i = 0; fmt[i] != PIX_FMT_NONE; i++) {
837 int imgfmt = pixfmt2imgfmt(fmt[i]);
838 if (!IMGFMT_IS_HWACCEL(imgfmt))
839 continue;
840 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
841 if (init_vo(sh, fmt[i]) >= 0)
842 break;
844 return fmt[i];
847 static int control(sh_video_t *sh, int cmd, void *arg, ...)
849 vd_ffmpeg_ctx *ctx = sh->context;
850 AVCodecContext *avctx = ctx->avctx;
851 switch (cmd) {
852 case VDCTRL_QUERY_FORMAT: {
853 int format = (*((int *)arg));
854 if (format == ctx->best_csp)
855 return CONTROL_TRUE;
856 // possible conversions:
857 switch (format) {
858 case IMGFMT_YV12:
859 case IMGFMT_IYUV:
860 case IMGFMT_I420:
861 // "converted" using pointer/stride modification
862 if (ctx->best_csp == IMGFMT_YV12)
863 return CONTROL_TRUE; // u/v swap
864 if (ctx->best_csp == IMGFMT_422P && !ctx->do_dr1)
865 return CONTROL_TRUE; // half stride
866 break;
868 return CONTROL_FALSE;
870 case VDCTRL_RESYNC_STREAM:
871 avcodec_flush_buffers(avctx);
872 return CONTROL_TRUE;
873 case VDCTRL_QUERY_UNSEEN_FRAMES:;
874 int delay = avctx->has_b_frames;
875 if (avctx->active_thread_type & FF_THREAD_FRAME)
876 delay += avctx->thread_count - 1;
877 return delay + 10;
878 case VDCTRL_RESET_ASPECT:
879 if (ctx->vo_initialized)
880 ctx->vo_initialized = false;
881 init_vo(sh, avctx->pix_fmt);
882 return true;
884 return CONTROL_UNKNOWN;
887 const struct vd_functions mpcodecs_vd_ffmpeg = {
888 .info = &info,
889 .init = init,
890 .uninit = uninit,
891 .control = control,
892 .decode2 = decode