sd_ass: initialize structs for external tracks properly
[mplayer.git] / libmpcodecs / vd_ffmpeg.c
blob2ba2b4e1546e9ca18081d9ddbe6f1fbfdf6fe738
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("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, 16),
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)
111 if (!str) return AVDISCARD_DEFAULT;
112 if (strcasecmp(str, "none" ) == 0) return AVDISCARD_NONE;
113 if (strcasecmp(str, "default") == 0) return AVDISCARD_DEFAULT;
114 if (strcasecmp(str, "nonref" ) == 0) return AVDISCARD_NONREF;
115 if (strcasecmp(str, "bidir" ) == 0) return AVDISCARD_BIDIR;
116 if (strcasecmp(str, "nonkey" ) == 0) return AVDISCARD_NONKEY;
117 if (strcasecmp(str, "all" ) == 0) return AVDISCARD_ALL;
118 mp_msg(MSGT_DECVIDEO, MSGL_ERR, "Unknown discard value %s\n", str);
119 return AVDISCARD_DEFAULT;
122 static int init(sh_video_t *sh)
124 struct lavc_param *lavc_param = &sh->opts->lavc_param;
125 AVCodecContext *avctx;
126 vd_ffmpeg_ctx *ctx;
127 AVCodec *lavc_codec;
128 int do_vis_debug = lavc_param->vismv ||
129 (lavc_param->debug & (FF_DEBUG_VIS_MB_TYPE | FF_DEBUG_VIS_QP));
131 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
133 if (sh->codec->dll) {
134 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
135 if (!lavc_codec) {
136 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR,
137 "Cannot find codec '%s' in libavcodec...\n",
138 sh->codec->dll);
139 uninit(sh);
140 return 0;
142 } else if (!sh->libav_codec_id) {
143 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "No Libav codec ID known. "
144 "Generic lavc decoder is not applicable.\n");
145 return 0;
146 } else {
147 lavc_codec = avcodec_find_decoder(sh->libav_codec_id);
148 if (!lavc_codec) {
149 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "Libavcodec has no decoder "
150 "for this codec\n");
151 return 0;
155 sh->codecname = lavc_codec->long_name;
156 if (!sh->codecname)
157 sh->codecname = lavc_codec->name;
159 if (sh->opts->vd_use_slices
160 && (lavc_codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)
161 && !do_vis_debug)
162 ctx->do_slices = 1;
164 if (lavc_codec->capabilities & CODEC_CAP_DR1 && !do_vis_debug
165 && lavc_codec->id != CODEC_ID_H264
166 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO
167 && lavc_codec->id != CODEC_ID_ROQ && lavc_codec->id != CODEC_ID_VP8
168 && lavc_codec->id != CODEC_ID_LAGARITH)
169 ctx->do_dr1 = 1;
170 ctx->ip_count = ctx->b_count = 0;
172 ctx->pic = avcodec_alloc_frame();
173 ctx->avctx = avcodec_alloc_context3(lavc_codec);
174 avctx = ctx->avctx;
175 avctx->opaque = sh;
176 avctx->codec_type = AVMEDIA_TYPE_VIDEO;
177 avctx->codec_id = lavc_codec->id;
179 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
180 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
181 ctx->do_dr1 = true;
182 ctx->do_slices = true;
183 lavc_param->threads = 1;
184 avctx->get_format = get_format;
185 avctx->get_buffer = get_buffer;
186 avctx->release_buffer = release_buffer;
187 avctx->reget_buffer = get_buffer;
188 avctx->draw_horiz_band = draw_slice;
189 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
190 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
191 "decoding.\n");
192 avctx->slice_flags = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
195 if (lavc_param->threads == 0) {
196 int threads = default_thread_count();
197 if (threads < 1) {
198 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Could not determine "
199 "thread count to use, defaulting to 1.\n");
200 threads = 1;
202 threads = FFMIN(threads, 16);
203 lavc_param->threads = threads;
205 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
206 * from other threads. */
207 if (lavc_param->threads > 1) {
208 ctx->do_dr1 = false;
209 ctx->do_slices = false;
210 mp_tmsg(MSGT_DECVIDEO, MSGL_V, "Asking decoder to use "
211 "%d threads if supported.\n", lavc_param->threads);
214 if (ctx->do_dr1) {
215 avctx->flags |= CODEC_FLAG_EMU_EDGE;
216 avctx->get_buffer = get_buffer;
217 avctx->release_buffer = release_buffer;
218 avctx->reget_buffer = get_buffer;
221 avctx->flags |= lavc_param->bitexact;
223 avctx->coded_width = sh->disp_w;
224 avctx->coded_height = sh->disp_h;
225 avctx->workaround_bugs = lavc_param->workaround_bugs;
226 if (lavc_param->gray)
227 avctx->flags |= CODEC_FLAG_GRAY;
228 avctx->flags2 |= lavc_param->fast;
229 avctx->codec_tag = sh->format;
230 avctx->stream_codec_tag = sh->video.fccHandler;
231 avctx->idct_algo = lavc_param->idct_algo;
232 avctx->error_concealment = lavc_param->error_concealment;
233 avctx->debug = lavc_param->debug;
234 if (lavc_param->debug)
235 av_log_set_level(AV_LOG_DEBUG);
236 avctx->debug_mv = lavc_param->vismv;
237 avctx->skip_top = lavc_param->skip_top;
238 avctx->skip_bottom = lavc_param->skip_bottom;
239 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
240 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
241 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
243 if (lavc_param->avopt) {
244 if (parse_avopts(avctx, lavc_param->avopt) < 0) {
245 mp_msg(MSGT_DECVIDEO, MSGL_ERR,
246 "Your options /%s/ look like gibberish to me pal\n",
247 lavc_param->avopt);
248 uninit(sh);
249 return 0;
253 // Do this after the above avopt handling in case it changes values
254 ctx->skip_frame = avctx->skip_frame;
256 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2,
257 "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
258 switch (sh->format) {
259 case mmioFOURCC('S','V','Q','3'):
260 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
261 * in the phony AVI header if demux_lavf is used. The first case is
262 * handled here; the second case falls through to the next section. */
263 if (sh->ImageDesc) {
264 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
265 avctx->extradata = av_mallocz(avctx->extradata_size +
266 FF_INPUT_BUFFER_PADDING_SIZE);
267 memcpy(avctx->extradata, ((int *)sh->ImageDesc) + 1,
268 avctx->extradata_size);
269 break;
271 /* fallthrough */
273 case mmioFOURCC('A','V','R','n'):
274 case mmioFOURCC('M','J','P','G'):
275 /* AVRn stores huffman table in AVI header */
276 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
277 * MJPG fourcc :( */
278 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
279 break;
280 av_opt_set_int(avctx, "extern_huff", 1, AV_OPT_SEARCH_CHILDREN);
281 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
282 avctx->extradata = av_mallocz(avctx->extradata_size +
283 FF_INPUT_BUFFER_PADDING_SIZE);
284 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
285 break;
287 case mmioFOURCC('R','V','1','0'):
288 case mmioFOURCC('R','V','1','3'):
289 case mmioFOURCC('R','V','2','0'):
290 case mmioFOURCC('R','V','3','0'):
291 case mmioFOURCC('R','V','4','0'):
292 if (sh->bih->biSize < sizeof(*sh->bih) + 8) {
293 // only 1 packet per frame & sub_id from fourcc
294 avctx->extradata_size = 8;
295 avctx->extradata = av_mallocz(avctx->extradata_size +
296 FF_INPUT_BUFFER_PADDING_SIZE);
297 ((uint32_t *)avctx->extradata)[0] = 0;
298 ((uint32_t *)avctx->extradata)[1] =
299 sh->format == mmioFOURCC('R','V','1','3') ?
300 0x10003001 : 0x10000000;
301 } else {
302 // has extra slice header (demux_rm or rm->avi streamcopy)
303 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
304 avctx->extradata = av_mallocz(avctx->extradata_size +
305 FF_INPUT_BUFFER_PADDING_SIZE);
306 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
308 break;
310 default:
311 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
312 break;
313 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
314 avctx->extradata = av_mallocz(avctx->extradata_size +
315 FF_INPUT_BUFFER_PADDING_SIZE);
316 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
317 break;
320 if (sh->bih)
321 avctx->bits_per_coded_sample = sh->bih->biBitCount;
323 avctx->thread_count = lavc_param->threads;
325 /* open it */
326 if (avcodec_open2(avctx, lavc_codec, NULL) < 0) {
327 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
328 uninit(sh);
329 return 0;
331 return 1;
334 static void uninit(sh_video_t *sh)
336 vd_ffmpeg_ctx *ctx = sh->context;
337 AVCodecContext *avctx = ctx->avctx;
339 sh->codecname = NULL;
340 if (sh->opts->lavc_param.vstats && avctx->coded_frame) {
341 for (int i = 1; i < 32; i++)
342 mp_msg(MSGT_DECVIDEO, MSGL_INFO,
343 "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
344 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: "
345 "%2.4f, Harmonic mean of QP: %2.4f\n",
346 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
347 1.0 / (ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number));
350 if (avctx) {
351 if (avctx->codec && avcodec_close(avctx) < 0)
352 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
354 av_freep(&avctx->extradata);
355 av_freep(&avctx->slice_offset);
358 av_freep(&avctx);
359 #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54, 28, 0)
360 avcodec_free_frame(&ctx->pic);
361 #else
362 av_freep(&ctx->pic);
363 #endif
364 talloc_free(ctx);
367 static void draw_slice(struct AVCodecContext *s,
368 const AVFrame *src, int offset[4],
369 int y, int type, int height)
371 sh_video_t *sh = s->opaque;
372 uint8_t *source[MP_MAX_PLANES] = {
373 src->data[0] + offset[0], src->data[1] + offset[1],
374 src->data[2] + offset[2]
376 int strides[MP_MAX_PLANES] = {
377 src->linesize[0], src->linesize[1], src->linesize[2]
379 if (height < 0) {
380 int i;
381 height = -height;
382 y -= height;
383 for (i = 0; i < MP_MAX_PLANES; i++) {
384 strides[i] = -strides[i];
385 source[i] -= strides[i];
388 if (y < sh->disp_h) {
389 height = FFMIN(height, sh->disp_h - y);
390 mpcodecs_draw_slice(sh, source, strides, sh->disp_w, height, 0, y);
394 static enum mp_csp avcol_spc_to_mp_csp(enum AVColorSpace colorspace)
396 switch (colorspace) {
397 case AVCOL_SPC_BT709:
398 return MP_CSP_BT_709;
399 break;
400 case AVCOL_SPC_BT470BG:
401 case AVCOL_SPC_SMPTE170M:
402 return MP_CSP_BT_601;
403 break;
404 case AVCOL_SPC_SMPTE240M:
405 return MP_CSP_SMPTE_240M;
406 break;
407 default:
408 return MP_CSP_AUTO;
412 static enum mp_csp_levels avcol_range_to_mp_csp_levels(enum AVColorRange range)
414 switch (range) {
415 case AVCOL_RANGE_MPEG:
416 return MP_CSP_LEVELS_TV;
417 break;
418 case AVCOL_RANGE_JPEG:
419 return MP_CSP_LEVELS_PC;
420 break;
421 default:
422 return MP_CSP_LEVELS_AUTO;
426 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt)
428 vd_ffmpeg_ctx *ctx = sh->context;
429 AVCodecContext *avctx = ctx->avctx;
430 float aspect = av_q2d(avctx->sample_aspect_ratio) *
431 avctx->width / avctx->height;
432 int width, height;
434 width = avctx->width;
435 height = avctx->height;
437 // HACK!
438 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
439 // use dimensions from BIH to avoid black borders at the right and bottom.
440 if (sh->bih && sh->ImageDesc) {
441 width = sh->bih->biWidth;
442 height = sh->bih->biHeight;
445 /* Reconfiguring filter/VO chain may invalidate direct rendering buffers
446 * we have allocated for libavcodec (including the VDPAU HW decoding
447 * case). Is it guaranteed that the code below only triggers in a situation
448 * with no busy direct rendering buffers for reference frames?
450 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
451 width != sh->disp_w || height != sh->disp_h ||
452 pix_fmt != ctx->pix_fmt || !ctx->vo_initialized) {
453 ctx->vo_initialized = 0;
454 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
456 // Do not overwrite s->aspect on the first call, so that a container
457 // aspect if available is preferred.
458 // But set it even if the sample aspect did not change, since a
459 // resolution change can cause an aspect change even if the
460 // _sample_ aspect is unchanged.
461 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
462 sh->aspect = aspect;
463 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
464 sh->disp_w = width;
465 sh->disp_h = height;
466 ctx->pix_fmt = pix_fmt;
467 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
468 const unsigned int *supported_fmts;
469 if (ctx->best_csp == IMGFMT_YV12)
470 supported_fmts = (const unsigned int[]){
471 IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
473 else if (ctx->best_csp == IMGFMT_422P)
474 supported_fmts = (const unsigned int[]){
475 IMGFMT_422P, IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
477 else
478 supported_fmts = (const unsigned int[]){ctx->best_csp, 0xffffffff};
480 sh->colorspace = avcol_spc_to_mp_csp(avctx->colorspace);
481 sh->color_range = avcol_range_to_mp_csp_levels(avctx->color_range);
483 if (!mpcodecs_config_vo2(sh, sh->disp_w, sh->disp_h, supported_fmts,
484 ctx->best_csp))
485 return -1;
486 ctx->vo_initialized = 1;
488 return 0;
491 static int get_buffer(AVCodecContext *avctx, AVFrame *pic)
493 sh_video_t *sh = avctx->opaque;
494 vd_ffmpeg_ctx *ctx = sh->context;
495 mp_image_t *mpi = NULL;
496 int flags = MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE |
497 MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
498 int type = MP_IMGTYPE_IPB;
499 int width = avctx->width;
500 int height = avctx->height;
501 // special case to handle reget_buffer without buffer hints
502 if (pic->opaque && pic->data[0] && !pic->buffer_hints)
503 return 0;
504 avcodec_align_dimensions(avctx, &width, &height);
506 if (pic->buffer_hints) {
507 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n",
508 pic->buffer_hints);
509 type = MP_IMGTYPE_TEMP;
510 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
511 flags |= MP_IMGFLAG_READABLE;
512 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
513 type = MP_IMGTYPE_STATIC;
514 flags |= MP_IMGFLAG_PRESERVE;
516 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
517 type = MP_IMGTYPE_STATIC;
518 flags |= MP_IMGFLAG_PRESERVE;
520 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
521 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
522 type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
523 } else {
524 if (!pic->reference) {
525 ctx->b_count++;
526 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
527 } else {
528 ctx->ip_count++;
529 flags |= MP_IMGFLAG_PRESERVE | MP_IMGFLAG_READABLE
530 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
534 if (init_vo(sh, avctx->pix_fmt) < 0) {
535 avctx->release_buffer = avcodec_default_release_buffer;
536 avctx->get_buffer = avcodec_default_get_buffer;
537 avctx->reget_buffer = avcodec_default_reget_buffer;
538 if (pic->data[0])
539 release_buffer(avctx, pic);
540 return avctx->get_buffer(avctx, pic);
543 if (IMGFMT_IS_HWACCEL(ctx->best_csp))
544 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
545 else if (!pic->buffer_hints) {
546 if (ctx->b_count > 1 || ctx->ip_count > 2) {
547 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
549 ctx->do_dr1 = 0; //FIXME
550 avctx->get_buffer = avcodec_default_get_buffer;
551 avctx->reget_buffer = avcodec_default_reget_buffer;
552 if (pic->data[0])
553 release_buffer(avctx, pic);
554 return avctx->get_buffer(avctx, pic);
557 if (avctx->has_b_frames || ctx->b_count)
558 type = MP_IMGTYPE_IPB;
559 else
560 type = MP_IMGTYPE_IP;
561 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
562 type == MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
565 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
566 flags |= MP_IMGFLAG_RGB_PALETTE;
567 mpi = mpcodecs_get_image(sh, type, flags, width, height);
568 if (!mpi)
569 return -1;
571 // ok, let's see what did we get:
572 if (mpi->flags & MP_IMGFLAG_DRAW_CALLBACK &&
573 !(mpi->flags & MP_IMGFLAG_DIRECT)) {
574 // nice, filter/vo likes draw_callback :)
575 avctx->draw_horiz_band = draw_slice;
576 } else
577 avctx->draw_horiz_band = NULL;
578 if (IMGFMT_IS_HWACCEL(mpi->imgfmt))
579 avctx->draw_horiz_band = draw_slice;
581 pic->data[0] = mpi->planes[0];
582 pic->data[1] = mpi->planes[1];
583 pic->data[2] = mpi->planes[2];
584 pic->data[3] = mpi->planes[3];
586 /* Note: some (many) codecs in libavcodec require
587 * linesize[1] == linesize[2] and no changes between frames.
588 * Lavc will check that and die with an error message if it's not true.
590 pic->linesize[0] = mpi->stride[0];
591 pic->linesize[1] = mpi->stride[1];
592 pic->linesize[2] = mpi->stride[2];
593 pic->linesize[3] = mpi->stride[3];
595 pic->opaque = mpi;
597 pic->type = FF_BUFFER_TYPE_USER;
599 /* The libavcodec reordered_opaque functionality is implemented by
600 * a similar copy in avcodec_default_get_buffer() and without a
601 * workaround like this it'd stop working when a custom buffer
602 * callback is used.
604 pic->reordered_opaque = avctx->reordered_opaque;
605 return 0;
608 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic)
610 mp_image_t *mpi = pic->opaque;
611 sh_video_t *sh = avctx->opaque;
612 vd_ffmpeg_ctx *ctx = sh->context;
614 if (ctx->ip_count <= 2 && ctx->b_count <= 1) {
615 if (mpi->flags & MP_IMGFLAG_PRESERVE)
616 ctx->ip_count--;
617 else
618 ctx->b_count--;
621 if (mpi) {
622 // Palette support: free palette buffer allocated in get_buffer
623 if (mpi->bpp == 8)
624 av_freep(&mpi->planes[1]);
625 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
626 mpi->usage_count--;
629 if (pic->type != FF_BUFFER_TYPE_USER) {
630 avcodec_default_release_buffer(avctx, pic);
631 return;
634 for (int i = 0; i < 4; i++)
635 pic->data[i] = NULL;
638 static av_unused void swap_palette(void *pal)
640 int i;
641 uint32_t *p = pal;
642 for (i = 0; i < AVPALETTE_COUNT; i++)
643 p[i] = le2me_32(p[i]);
646 static struct mp_image *decode(struct sh_video *sh, struct demux_packet *packet,
647 void *data, int len, int flags,
648 double *reordered_pts)
650 int got_picture = 0;
651 int ret;
652 vd_ffmpeg_ctx *ctx = sh->context;
653 AVFrame *pic = ctx->pic;
654 AVCodecContext *avctx = ctx->avctx;
655 struct lavc_param *lavc_param = &sh->opts->lavc_param;
656 mp_image_t *mpi = NULL;
657 int dr1 = ctx->do_dr1;
658 AVPacket pkt;
660 if (!dr1)
661 avctx->draw_horiz_band = NULL;
663 if (flags & 2)
664 avctx->skip_frame = AVDISCARD_ALL;
665 else if (flags & 1)
666 avctx->skip_frame = AVDISCARD_NONREF;
667 else
668 avctx->skip_frame = ctx->skip_frame;
670 av_init_packet(&pkt);
671 pkt.data = data;
672 pkt.size = len;
673 /* Some codecs (ZeroCodec, some cases of PNG) may want keyframe info
674 * from demuxer. */
675 if (packet && packet->keyframe)
676 pkt.flags |= AV_PKT_FLAG_KEY;
677 if (packet && packet->avpacket) {
678 pkt.side_data = packet->avpacket->side_data;
679 pkt.side_data_elems = packet->avpacket->side_data_elems;
681 // The avcodec opaque field stupidly supports only int64_t type
682 union pts { int64_t i; double d; };
683 avctx->reordered_opaque = (union pts){.d = *reordered_pts}.i;
684 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
685 *reordered_pts = (union pts){.i = pic->reordered_opaque}.d;
687 dr1 = ctx->do_dr1;
688 if (ret < 0)
689 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
690 //-- vstats generation
691 while (lavc_param->vstats) { // always one time loop
692 static FILE *fvstats = NULL;
693 char filename[20];
694 static long long int all_len = 0;
695 static int frame_number = 0;
696 static double all_frametime = 0.0;
697 AVFrame *pic = avctx->coded_frame;
698 double quality = 0.0;
700 if (!pic)
701 break;
703 if (!fvstats) {
704 time_t today2;
705 struct tm *today;
706 today2 = time(NULL);
707 today = localtime(&today2);
708 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
709 today->tm_min, today->tm_sec);
710 fvstats = fopen(filename, "w");
711 if (!fvstats) {
712 perror("fopen");
713 lavc_param->vstats = 0; // disable block
714 break;
715 /*exit(1);*/
719 // average MB quantizer
721 int x, y;
722 int w = (avctx->width + 15) >> 4;
723 int h = (avctx->height + 15) >> 4;
724 int8_t *q = pic->qscale_table;
725 for (y = 0; y < h; y++) {
726 for (x = 0; x < w; x++)
727 quality += (double)*(q + x);
728 q += pic->qstride;
730 quality /= w * h;
733 all_len += len;
734 all_frametime += sh->frametime;
735 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
736 ++frame_number, quality, len, (double)all_len / 1024);
737 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
738 all_frametime, (double)(len * 8) / sh->frametime / 1000.0,
739 (double)(all_len * 8) / all_frametime / 1000.0);
740 switch (pic->pict_type) {
741 case AV_PICTURE_TYPE_I:
742 fprintf(fvstats, "type= I\n");
743 break;
744 case AV_PICTURE_TYPE_P:
745 fprintf(fvstats, "type= P\n");
746 break;
747 case AV_PICTURE_TYPE_S:
748 fprintf(fvstats, "type= S\n");
749 break;
750 case AV_PICTURE_TYPE_B:
751 fprintf(fvstats, "type= B\n");
752 break;
753 default:
754 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
755 break;
758 ctx->qp_stat[(int)(quality + 0.5)]++;
759 ctx->qp_sum += quality;
760 ctx->inv_qp_sum += 1.0 / (double)quality;
762 break;
764 //--
766 if (!got_picture)
767 return NULL; // skipped image
769 if (init_vo(sh, avctx->pix_fmt) < 0)
770 return NULL;
772 if (dr1 && pic->opaque)
773 mpi = (mp_image_t *)pic->opaque;
775 if (!mpi)
776 mpi = mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
777 avctx->width, avctx->height);
778 if (!mpi) { // temporary error?
779 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN,
780 "[VD_FFMPEG] Couldn't allocate image for codec.\n");
781 return NULL;
784 if (!dr1) {
785 mpi->planes[0] = pic->data[0];
786 mpi->planes[1] = pic->data[1];
787 mpi->planes[2] = pic->data[2];
788 mpi->planes[3] = pic->data[3];
789 mpi->stride[0] = pic->linesize[0];
790 mpi->stride[1] = pic->linesize[1];
791 mpi->stride[2] = pic->linesize[2];
792 mpi->stride[3] = pic->linesize[3];
795 if (!mpi->planes[0])
796 return NULL;
798 if (ctx->best_csp == IMGFMT_422P && mpi->chroma_y_shift == 1) {
799 // we have 422p but user wants 420p
800 mpi->stride[1] *= 2;
801 mpi->stride[2] *= 2;
804 #if HAVE_BIGENDIAN
805 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
806 if (mpi->bpp == 8)
807 swap_palette(mpi->planes[1]);
808 #endif
810 mpi->qscale = pic->qscale_table;
811 mpi->qstride = pic->qstride;
812 mpi->pict_type = pic->pict_type;
813 mpi->qscale_type = pic->qscale_type;
814 mpi->fields = MP_IMGFIELD_ORDERED;
815 if (pic->interlaced_frame)
816 mpi->fields |= MP_IMGFIELD_INTERLACED;
817 if (pic->top_field_first)
818 mpi->fields |= MP_IMGFIELD_TOP_FIRST;
819 if (pic->repeat_pict == 1)
820 mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
822 return mpi;
825 static enum PixelFormat get_format(struct AVCodecContext *avctx,
826 const enum PixelFormat *fmt)
828 sh_video_t *sh = avctx->opaque;
829 int i;
831 for (i = 0; fmt[i] != PIX_FMT_NONE; i++) {
832 int imgfmt = pixfmt2imgfmt(fmt[i]);
833 if (!IMGFMT_IS_HWACCEL(imgfmt))
834 continue;
835 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
836 if (init_vo(sh, fmt[i]) >= 0)
837 break;
839 return fmt[i];
842 static int control(sh_video_t *sh, int cmd, void *arg, ...)
844 vd_ffmpeg_ctx *ctx = sh->context;
845 AVCodecContext *avctx = ctx->avctx;
846 switch (cmd) {
847 case VDCTRL_QUERY_FORMAT: {
848 int format = (*((int *)arg));
849 if (format == ctx->best_csp)
850 return CONTROL_TRUE;
851 // possible conversions:
852 switch (format) {
853 case IMGFMT_YV12:
854 case IMGFMT_IYUV:
855 case IMGFMT_I420:
856 // "converted" using pointer/stride modification
857 if (ctx->best_csp == IMGFMT_YV12)
858 return CONTROL_TRUE; // u/v swap
859 if (ctx->best_csp == IMGFMT_422P && !ctx->do_dr1)
860 return CONTROL_TRUE; // half stride
861 break;
863 return CONTROL_FALSE;
865 case VDCTRL_RESYNC_STREAM:
866 avcodec_flush_buffers(avctx);
867 return CONTROL_TRUE;
868 case VDCTRL_QUERY_UNSEEN_FRAMES:;
869 int delay = avctx->has_b_frames;
870 if (avctx->active_thread_type & FF_THREAD_FRAME)
871 delay += avctx->thread_count - 1;
872 return delay + 10;
873 case VDCTRL_RESET_ASPECT:
874 if (ctx->vo_initialized)
875 ctx->vo_initialized = false;
876 init_vo(sh, avctx->pix_fmt);
877 return true;
879 return CONTROL_UNKNOWN;
882 const struct vd_functions mpcodecs_vd_ffmpeg = {
883 .info = &info,
884 .init = init,
885 .uninit = uninit,
886 .control = control,
887 .decode2 = decode