ao_pulse: support native mute control
[mplayer.git] / libmpcodecs / vd_ffmpeg.c
blob5a45fef6d83294ceaf6f535f0c3ef4289d26b4c6
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"
45 static const vd_info_t info = {
46 "FFmpeg's libavcodec codec family",
47 "ffmpeg",
48 "A'rpi",
49 "A'rpi, Michael, Alex",
50 "native codecs"
53 #include "libavcodec/avcodec.h"
55 #if AVPALETTE_SIZE > 1024
56 #error palette too large, adapt libmpcodecs/vf.c:vf_get_image
57 #endif
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 qp_stat[32];
68 double qp_sum;
69 double inv_qp_sum;
70 int ip_count;
71 int b_count;
72 AVRational last_sample_aspect_ratio;
73 enum AVDiscard skip_frame;
74 } vd_ffmpeg_ctx;
76 #include "m_option.h"
78 static int get_buffer(AVCodecContext *avctx, AVFrame *pic);
79 static void release_buffer(AVCodecContext *avctx, AVFrame *pic);
80 static void draw_slice(struct AVCodecContext *s, const AVFrame *src,
81 int offset[4], int y, int type, int height);
83 static enum PixelFormat get_format(struct AVCodecContext *avctx,
84 const enum PixelFormat *pix_fmt);
85 static void uninit(struct sh_video *sh);
87 const m_option_t lavc_decode_opts_conf[] = {
88 OPT_INTRANGE("bug", lavc_param.workaround_bugs, 0, -1, 999999),
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_STRING("lowres", lavc_param.lowres_str, 0),
99 OPT_STRING("skiploopfilter", lavc_param.skip_loop_filter_str, 0),
100 OPT_STRING("skipidct", lavc_param.skip_idct_str, 0),
101 OPT_STRING("skipframe", lavc_param.skip_frame_str, 0),
102 OPT_INTRANGE("threads", lavc_param.threads, 0, 0, 16),
103 OPT_FLAG_CONSTANTS("bitexact", lavc_param.bitexact, 0, 0, CODEC_FLAG_BITEXACT),
104 OPT_STRING("o", lavc_param.avopt, 0),
105 {NULL, NULL, 0, 0, 0, 0, NULL}
108 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 static int init(sh_video_t *sh)
123 struct lavc_param *lavc_param = &sh->opts->lavc_param;
124 AVCodecContext *avctx;
125 vd_ffmpeg_ctx *ctx;
126 AVCodec *lavc_codec;
127 int do_vis_debug = lavc_param->vismv ||
128 (lavc_param->debug & (FF_DEBUG_VIS_MB_TYPE | FF_DEBUG_VIS_QP));
130 ctx = sh->context = talloc_zero(NULL, vd_ffmpeg_ctx);
132 lavc_codec = avcodec_find_decoder_by_name(sh->codec->dll);
133 if (!lavc_codec) {
134 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR,
135 "Cannot find codec '%s' in libavcodec...\n", sh->codec->dll);
136 uninit(sh);
137 return 0;
140 if (sh->opts->vd_use_slices
141 && (lavc_codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)
142 && !do_vis_debug)
143 ctx->do_slices = 1;
145 if (lavc_codec->capabilities & CODEC_CAP_DR1 && !do_vis_debug
146 && lavc_codec->id != CODEC_ID_H264
147 && lavc_codec->id != CODEC_ID_INTERPLAY_VIDEO
148 && lavc_codec->id != CODEC_ID_ROQ && lavc_codec->id != CODEC_ID_VP8
149 && lavc_codec->id != CODEC_ID_LAGARITH)
150 ctx->do_dr1 = 1;
151 ctx->ip_count = ctx->b_count = 0;
153 ctx->pic = avcodec_alloc_frame();
154 ctx->avctx = avcodec_alloc_context3(lavc_codec);
155 avctx = ctx->avctx;
156 avctx->opaque = sh;
157 avctx->codec_type = AVMEDIA_TYPE_VIDEO;
158 avctx->codec_id = lavc_codec->id;
160 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL // XvMC
161 || lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
162 ctx->do_dr1 = true;
163 ctx->do_slices = true;
164 lavc_param->threads = 1;
165 avctx->get_format = get_format;
166 avctx->get_buffer = get_buffer;
167 avctx->release_buffer = release_buffer;
168 avctx->reget_buffer = get_buffer;
169 avctx->draw_horiz_band = draw_slice;
170 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL)
171 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] XVMC-accelerated "
172 "MPEG-2.\n");
173 if (lavc_codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
174 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] VDPAU hardware "
175 "decoding.\n");
176 avctx->slice_flags = SLICE_FLAG_CODED_ORDER | SLICE_FLAG_ALLOW_FIELD;
179 if (lavc_param->threads == 0) {
180 int threads = default_thread_count();
181 if (threads < 1) {
182 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] Could not determine "
183 "thread count to use, defaulting to 1.\n");
184 threads = 1;
186 threads = FFMIN(threads, 16);
187 lavc_param->threads = threads;
189 /* Our get_buffer and draw_horiz_band callbacks are not safe to call
190 * from other threads. */
191 if (lavc_param->threads > 1) {
192 ctx->do_dr1 = false;
193 ctx->do_slices = false;
194 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "Asking decoder to use "
195 "%d threads if supported.\n", lavc_param->threads);
198 if (ctx->do_dr1) {
199 avctx->flags |= CODEC_FLAG_EMU_EDGE;
200 avctx->get_buffer = get_buffer;
201 avctx->release_buffer = release_buffer;
202 avctx->reget_buffer = get_buffer;
205 avctx->flags |= lavc_param->bitexact;
207 avctx->coded_width = sh->disp_w;
208 avctx->coded_height = sh->disp_h;
209 avctx->workaround_bugs = lavc_param->workaround_bugs;
210 if (lavc_param->gray)
211 avctx->flags |= CODEC_FLAG_GRAY;
212 avctx->flags2 |= lavc_param->fast;
213 avctx->codec_tag = sh->format;
214 avctx->stream_codec_tag = sh->video.fccHandler;
215 avctx->idct_algo = lavc_param->idct_algo;
216 avctx->error_concealment = lavc_param->error_concealment;
217 avctx->debug = lavc_param->debug;
218 if (lavc_param->debug)
219 av_log_set_level(AV_LOG_DEBUG);
220 avctx->debug_mv = lavc_param->vismv;
221 avctx->skip_top = lavc_param->skip_top;
222 avctx->skip_bottom = lavc_param->skip_bottom;
223 if (lavc_param->lowres_str != NULL) {
224 int lowres, lowres_w;
225 sscanf(lavc_param->lowres_str, "%d,%d", &lowres, &lowres_w);
226 if (lowres < 1 || lowres > 16 ||
227 lowres_w > 0 && avctx->width < lowres_w)
228 lowres = 0;
229 avctx->lowres = lowres;
231 avctx->skip_loop_filter = str2AVDiscard(lavc_param->skip_loop_filter_str);
232 avctx->skip_idct = str2AVDiscard(lavc_param->skip_idct_str);
233 avctx->skip_frame = str2AVDiscard(lavc_param->skip_frame_str);
235 if (lavc_param->avopt) {
236 if (parse_avopts(avctx, lavc_param->avopt) < 0) {
237 mp_msg(MSGT_DECVIDEO, MSGL_ERR,
238 "Your options /%s/ look like gibberish to me pal\n",
239 lavc_param->avopt);
240 uninit(sh);
241 return 0;
245 // Do this after the above avopt handling in case it changes values
246 ctx->skip_frame = avctx->skip_frame;
248 mp_dbg(MSGT_DECVIDEO, MSGL_DBG2,
249 "libavcodec.size: %d x %d\n", avctx->width, avctx->height);
250 switch (sh->format) {
251 case mmioFOURCC('S','V','Q','3'):
252 /* SVQ3 extradata can show up as sh->ImageDesc if demux_mov is used, or
253 * in the phony AVI header if demux_lavf is used. The first case is
254 * handled here; the second case falls through to the next section. */
255 if (sh->ImageDesc) {
256 avctx->extradata_size = (*(int *)sh->ImageDesc) - sizeof(int);
257 avctx->extradata = av_mallocz(avctx->extradata_size +
258 FF_INPUT_BUFFER_PADDING_SIZE);
259 memcpy(avctx->extradata, ((int *)sh->ImageDesc) + 1,
260 avctx->extradata_size);
261 break;
263 /* fallthrough */
265 case mmioFOURCC('A','V','R','n'):
266 case mmioFOURCC('M','J','P','G'):
267 /* AVRn stores huffman table in AVI header */
268 /* Pegasus MJPEG stores it also in AVI header, but it uses the common
269 * MJPG fourcc :( */
270 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
271 break;
272 av_opt_set_int(avctx, "extern_huff", 1, AV_OPT_SEARCH_CHILDREN);
273 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
274 avctx->extradata = av_mallocz(avctx->extradata_size +
275 FF_INPUT_BUFFER_PADDING_SIZE);
276 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
277 break;
279 case mmioFOURCC('R','V','1','0'):
280 case mmioFOURCC('R','V','1','3'):
281 case mmioFOURCC('R','V','2','0'):
282 case mmioFOURCC('R','V','3','0'):
283 case mmioFOURCC('R','V','4','0'):
284 if (sh->bih->biSize < sizeof(*sh->bih) + 8) {
285 // only 1 packet per frame & sub_id from fourcc
286 avctx->extradata_size = 8;
287 avctx->extradata = av_mallocz(avctx->extradata_size +
288 FF_INPUT_BUFFER_PADDING_SIZE);
289 ((uint32_t *)avctx->extradata)[0] = 0;
290 ((uint32_t *)avctx->extradata)[1] =
291 sh->format == mmioFOURCC('R','V','1','3') ?
292 0x10003001 : 0x10000000;
293 } else {
294 // has extra slice header (demux_rm or rm->avi streamcopy)
295 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
296 avctx->extradata = av_mallocz(avctx->extradata_size +
297 FF_INPUT_BUFFER_PADDING_SIZE);
298 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
300 break;
302 default:
303 if (!sh->bih || sh->bih->biSize <= sizeof(*sh->bih))
304 break;
305 avctx->extradata_size = sh->bih->biSize - sizeof(*sh->bih);
306 avctx->extradata = av_mallocz(avctx->extradata_size +
307 FF_INPUT_BUFFER_PADDING_SIZE);
308 memcpy(avctx->extradata, sh->bih + 1, avctx->extradata_size);
309 break;
312 if (sh->bih)
313 avctx->bits_per_coded_sample = sh->bih->biBitCount;
315 avctx->thread_count = lavc_param->threads;
317 /* open it */
318 if (avcodec_open2(avctx, lavc_codec, NULL) < 0) {
319 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not open codec.\n");
320 uninit(sh);
321 return 0;
323 mp_msg(MSGT_DECVIDEO, MSGL_V, "INFO: libavcodec init OK!\n");
324 return 1; //mpcodecs_config_vo(sh, sh->disp_w, sh->disp_h, IMGFMT_YV12);
327 static void uninit(sh_video_t *sh)
329 vd_ffmpeg_ctx *ctx = sh->context;
330 AVCodecContext *avctx = ctx->avctx;
332 if (sh->opts->lavc_param.vstats && avctx->coded_frame) {
333 for (int i = 1; i < 32; i++)
334 mp_msg(MSGT_DECVIDEO, MSGL_INFO,
335 "QP: %d, count: %d\n", i, ctx->qp_stat[i]);
336 mp_tmsg(MSGT_DECVIDEO, MSGL_INFO, "[VD_FFMPEG] Arithmetic mean of QP: "
337 "%2.4f, Harmonic mean of QP: %2.4f\n",
338 ctx->qp_sum / avctx->coded_frame->coded_picture_number,
339 1.0 / (ctx->inv_qp_sum / avctx->coded_frame->coded_picture_number));
342 if (avctx) {
343 if (avctx->codec && avcodec_close(avctx) < 0)
344 mp_tmsg(MSGT_DECVIDEO, MSGL_ERR, "Could not close codec.\n");
346 av_freep(&avctx->extradata);
347 av_freep(&avctx->slice_offset);
350 av_freep(&avctx);
351 av_freep(&ctx->pic);
352 talloc_free(ctx);
355 static void draw_slice(struct AVCodecContext *s,
356 const AVFrame *src, int offset[4],
357 int y, int type, int height)
359 sh_video_t *sh = s->opaque;
360 uint8_t *source[MP_MAX_PLANES] = {
361 src->data[0] + offset[0], src->data[1] + offset[1],
362 src->data[2] + offset[2]
364 int strides[MP_MAX_PLANES] = {
365 src->linesize[0], src->linesize[1], src->linesize[2]
367 if (height < 0) {
368 int i;
369 height = -height;
370 y -= height;
371 for (i = 0; i < MP_MAX_PLANES; i++) {
372 strides[i] = -strides[i];
373 source[i] -= strides[i];
376 if (y < sh->disp_h) {
377 height = FFMIN(height, sh->disp_h - y);
378 mpcodecs_draw_slice(sh, source, strides, sh->disp_w, height, 0, y);
383 static int init_vo(sh_video_t *sh, enum PixelFormat pix_fmt)
385 vd_ffmpeg_ctx *ctx = sh->context;
386 AVCodecContext *avctx = ctx->avctx;
387 float aspect = av_q2d(avctx->sample_aspect_ratio) *
388 avctx->width / avctx->height;
389 int width, height;
391 width = avctx->width;
392 height = avctx->height;
394 // HACK!
395 // if sh->ImageDesc is non-NULL, it means we decode QuickTime(tm) video.
396 // use dimensions from BIH to avoid black borders at the right and bottom.
397 if (sh->bih && sh->ImageDesc) {
398 width = sh->bih->biWidth >> avctx->lowres;
399 height = sh->bih->biHeight >> avctx->lowres;
402 /* Reconfiguring filter/VO chain may invalidate direct rendering buffers
403 * we have allocated for libavcodec (including the VDPAU HW decoding
404 * case). Is it guaranteed that the code below only triggers in a situation
405 * with no busy direct rendering buffers for reference frames?
407 if (av_cmp_q(avctx->sample_aspect_ratio, ctx->last_sample_aspect_ratio) ||
408 width != sh->disp_w || height != sh->disp_h ||
409 pix_fmt != ctx->pix_fmt || !ctx->vo_initialized) {
410 ctx->vo_initialized = 0;
411 mp_msg(MSGT_DECVIDEO, MSGL_V, "[ffmpeg] aspect_ratio: %f\n", aspect);
413 // Do not overwrite s->aspect on the first call, so that a container
414 // aspect if available is preferred.
415 // But set it even if the sample aspect did not change, since a
416 // resolution change can cause an aspect change even if the
417 // _sample_ aspect is unchanged.
418 if (sh->aspect == 0 || ctx->last_sample_aspect_ratio.den)
419 sh->aspect = aspect;
420 ctx->last_sample_aspect_ratio = avctx->sample_aspect_ratio;
421 sh->disp_w = width;
422 sh->disp_h = height;
423 ctx->pix_fmt = pix_fmt;
424 ctx->best_csp = pixfmt2imgfmt(pix_fmt);
425 const unsigned int *supported_fmts;
426 if (ctx->best_csp == IMGFMT_YV12)
427 supported_fmts = (const unsigned int[]){
428 IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
430 else if (ctx->best_csp == IMGFMT_422P)
431 supported_fmts = (const unsigned int[]){
432 IMGFMT_422P, IMGFMT_YV12, IMGFMT_I420, IMGFMT_IYUV, 0xffffffff
434 else
435 supported_fmts = (const unsigned int[]){ctx->best_csp, 0xffffffff};
436 if (!mpcodecs_config_vo2(sh, sh->disp_w, sh->disp_h, supported_fmts,
437 ctx->best_csp))
438 return -1;
439 ctx->vo_initialized = 1;
441 return 0;
444 static int get_buffer(AVCodecContext *avctx, AVFrame *pic)
446 sh_video_t *sh = avctx->opaque;
447 vd_ffmpeg_ctx *ctx = sh->context;
448 mp_image_t *mpi = NULL;
449 int flags = MP_IMGFLAG_ACCEPT_ALIGNED_STRIDE |
450 MP_IMGFLAG_PREFER_ALIGNED_STRIDE;
451 int type = MP_IMGTYPE_IPB;
452 int width = avctx->width;
453 int height = avctx->height;
454 // special case to handle reget_buffer without buffer hints
455 if (pic->opaque && pic->data[0] && !pic->buffer_hints)
456 return 0;
457 avcodec_align_dimensions(avctx, &width, &height);
459 if (pic->buffer_hints) {
460 mp_msg(MSGT_DECVIDEO, MSGL_DBG2, "Buffer hints: %u\n",
461 pic->buffer_hints);
462 type = MP_IMGTYPE_TEMP;
463 if (pic->buffer_hints & FF_BUFFER_HINTS_READABLE)
464 flags |= MP_IMGFLAG_READABLE;
465 if (pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) {
466 type = MP_IMGTYPE_STATIC;
467 flags |= MP_IMGFLAG_PRESERVE;
469 if (pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) {
470 type = MP_IMGTYPE_STATIC;
471 flags |= MP_IMGFLAG_PRESERVE;
473 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
474 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
475 type == MP_IMGTYPE_STATIC ? "using STATIC\n" : "using TEMP\n");
476 } else {
477 if (!pic->reference) {
478 ctx->b_count++;
479 flags |= ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0;
480 } else {
481 ctx->ip_count++;
482 flags |= MP_IMGFLAG_PRESERVE | MP_IMGFLAG_READABLE
483 | (ctx->do_slices ? MP_IMGFLAG_DRAW_CALLBACK : 0);
487 if (init_vo(sh, avctx->pix_fmt) < 0) {
488 avctx->release_buffer = avcodec_default_release_buffer;
489 avctx->get_buffer = avcodec_default_get_buffer;
490 avctx->reget_buffer = avcodec_default_reget_buffer;
491 if (pic->data[0])
492 release_buffer(avctx, pic);
493 return avctx->get_buffer(avctx, pic);
496 if (IMGFMT_IS_HWACCEL(ctx->best_csp))
497 type = MP_IMGTYPE_NUMBERED | (0xffff << 16);
498 else if (!pic->buffer_hints) {
499 if (ctx->b_count > 1 || ctx->ip_count > 2) {
500 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN, "[VD_FFMPEG] DRI failure.\n");
502 ctx->do_dr1 = 0; //FIXME
503 avctx->get_buffer = avcodec_default_get_buffer;
504 avctx->reget_buffer = avcodec_default_reget_buffer;
505 if (pic->data[0])
506 release_buffer(avctx, pic);
507 return avctx->get_buffer(avctx, pic);
510 if (avctx->has_b_frames || ctx->b_count)
511 type = MP_IMGTYPE_IPB;
512 else
513 type = MP_IMGTYPE_IP;
514 mp_msg(MSGT_DECVIDEO, MSGL_DBG2,
515 type == MP_IMGTYPE_IPB ? "using IPB\n" : "using IP\n");
518 if (ctx->best_csp == IMGFMT_RGB8 || ctx->best_csp == IMGFMT_BGR8)
519 flags |= MP_IMGFLAG_RGB_PALETTE;
520 mpi = mpcodecs_get_image(sh, type, flags, width, height);
521 if (!mpi)
522 return -1;
524 // ok, let's see what did we get:
525 if (mpi->flags & MP_IMGFLAG_DRAW_CALLBACK &&
526 !(mpi->flags & MP_IMGFLAG_DIRECT)) {
527 // nice, filter/vo likes draw_callback :)
528 avctx->draw_horiz_band = draw_slice;
529 } else
530 avctx->draw_horiz_band = NULL;
531 if (IMGFMT_IS_HWACCEL(mpi->imgfmt))
532 avctx->draw_horiz_band = draw_slice;
534 pic->data[0] = mpi->planes[0];
535 pic->data[1] = mpi->planes[1];
536 pic->data[2] = mpi->planes[2];
537 pic->data[3] = mpi->planes[3];
539 /* Note: some (many) codecs in libavcodec require
540 * linesize[1] == linesize[2] and no changes between frames.
541 * Lavc will check that and die with an error message if it's not true.
543 pic->linesize[0] = mpi->stride[0];
544 pic->linesize[1] = mpi->stride[1];
545 pic->linesize[2] = mpi->stride[2];
546 pic->linesize[3] = mpi->stride[3];
548 pic->opaque = mpi;
550 pic->type = FF_BUFFER_TYPE_USER;
552 /* The libavcodec reordered_opaque functionality is implemented by
553 * a similar copy in avcodec_default_get_buffer() and without a
554 * workaround like this it'd stop working when a custom buffer
555 * callback is used.
557 pic->reordered_opaque = avctx->reordered_opaque;
558 return 0;
561 static void release_buffer(struct AVCodecContext *avctx, AVFrame *pic)
563 mp_image_t *mpi = pic->opaque;
564 sh_video_t *sh = avctx->opaque;
565 vd_ffmpeg_ctx *ctx = sh->context;
567 if (ctx->ip_count <= 2 && ctx->b_count <= 1) {
568 if (mpi->flags & MP_IMGFLAG_PRESERVE)
569 ctx->ip_count--;
570 else
571 ctx->b_count--;
574 if (mpi) {
575 // Palette support: free palette buffer allocated in get_buffer
576 if (mpi->bpp == 8)
577 av_freep(&mpi->planes[1]);
578 // release mpi (in case MPI_IMGTYPE_NUMBERED is used, e.g. for VDPAU)
579 mpi->usage_count--;
582 if (pic->type != FF_BUFFER_TYPE_USER) {
583 avcodec_default_release_buffer(avctx, pic);
584 return;
587 for (int i = 0; i < 4; i++)
588 pic->data[i] = NULL;
591 static av_unused void swap_palette(void *pal)
593 int i;
594 uint32_t *p = pal;
595 for (i = 0; i < AVPALETTE_COUNT; i++)
596 p[i] = le2me_32(p[i]);
599 static struct mp_image *decode(struct sh_video *sh, struct demux_packet *packet,
600 void *data, int len, int flags,
601 double *reordered_pts)
603 int got_picture = 0;
604 int ret;
605 vd_ffmpeg_ctx *ctx = sh->context;
606 AVFrame *pic = ctx->pic;
607 AVCodecContext *avctx = ctx->avctx;
608 struct lavc_param *lavc_param = &sh->opts->lavc_param;
609 mp_image_t *mpi = NULL;
610 int dr1 = ctx->do_dr1;
611 AVPacket pkt;
613 if (!dr1)
614 avctx->draw_horiz_band = NULL;
616 if (flags & 2)
617 avctx->skip_frame = AVDISCARD_ALL;
618 else if (flags & 1)
619 avctx->skip_frame = AVDISCARD_NONREF;
620 else
621 avctx->skip_frame = ctx->skip_frame;
623 av_init_packet(&pkt);
624 pkt.data = data;
625 pkt.size = len;
626 // HACK: make PNGs decode normally instead of as CorePNG delta frames
627 pkt.flags = AV_PKT_FLAG_KEY;
628 if (packet && packet->avpacket) {
629 pkt.side_data = packet->avpacket->side_data;
630 pkt.side_data_elems = packet->avpacket->side_data_elems;
632 // The avcodec opaque field stupidly supports only int64_t type
633 union pts { int64_t i; double d; };
634 avctx->reordered_opaque = (union pts){.d = *reordered_pts}.i;
635 ret = avcodec_decode_video2(avctx, pic, &got_picture, &pkt);
636 *reordered_pts = (union pts){.i = pic->reordered_opaque}.d;
638 dr1 = ctx->do_dr1;
639 if (ret < 0)
640 mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Error while decoding frame!\n");
641 //-- vstats generation
642 while (lavc_param->vstats) { // always one time loop
643 static FILE *fvstats = NULL;
644 char filename[20];
645 static long long int all_len = 0;
646 static int frame_number = 0;
647 static double all_frametime = 0.0;
648 AVFrame *pic = avctx->coded_frame;
649 double quality = 0.0;
651 if (!pic)
652 break;
654 if (!fvstats) {
655 time_t today2;
656 struct tm *today;
657 today2 = time(NULL);
658 today = localtime(&today2);
659 sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
660 today->tm_min, today->tm_sec);
661 fvstats = fopen(filename, "w");
662 if (!fvstats) {
663 perror("fopen");
664 lavc_param->vstats = 0; // disable block
665 break;
666 /*exit(1);*/
670 // average MB quantizer
672 int x, y;
673 int w = ((avctx->width << avctx->lowres) + 15) >> 4;
674 int h = ((avctx->height << avctx->lowres) + 15) >> 4;
675 int8_t *q = pic->qscale_table;
676 for (y = 0; y < h; y++) {
677 for (x = 0; x < w; x++)
678 quality += (double)*(q + x);
679 q += pic->qstride;
681 quality /= w * h;
684 all_len += len;
685 all_frametime += sh->frametime;
686 fprintf(fvstats, "frame= %5d q= %2.2f f_size= %6d s_size= %8.0fkB ",
687 ++frame_number, quality, len, (double)all_len / 1024);
688 fprintf(fvstats, "time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
689 all_frametime, (double)(len * 8) / sh->frametime / 1000.0,
690 (double)(all_len * 8) / all_frametime / 1000.0);
691 switch (pic->pict_type) {
692 case AV_PICTURE_TYPE_I:
693 fprintf(fvstats, "type= I\n");
694 break;
695 case AV_PICTURE_TYPE_P:
696 fprintf(fvstats, "type= P\n");
697 break;
698 case AV_PICTURE_TYPE_S:
699 fprintf(fvstats, "type= S\n");
700 break;
701 case AV_PICTURE_TYPE_B:
702 fprintf(fvstats, "type= B\n");
703 break;
704 default:
705 fprintf(fvstats, "type= ? (%d)\n", pic->pict_type);
706 break;
709 ctx->qp_stat[(int)(quality + 0.5)]++;
710 ctx->qp_sum += quality;
711 ctx->inv_qp_sum += 1.0 / (double)quality;
713 break;
715 //--
717 if (!got_picture)
718 return NULL; // skipped image
720 if (init_vo(sh, avctx->pix_fmt) < 0)
721 return NULL;
723 if (dr1 && pic->opaque)
724 mpi = (mp_image_t *)pic->opaque;
726 if (!mpi)
727 mpi = mpcodecs_get_image(sh, MP_IMGTYPE_EXPORT, MP_IMGFLAG_PRESERVE,
728 avctx->width, avctx->height);
729 if (!mpi) { // temporary error?
730 mp_tmsg(MSGT_DECVIDEO, MSGL_WARN,
731 "[VD_FFMPEG] Couldn't allocate image for codec.\n");
732 return NULL;
735 if (!dr1) {
736 mpi->planes[0] = pic->data[0];
737 mpi->planes[1] = pic->data[1];
738 mpi->planes[2] = pic->data[2];
739 mpi->planes[3] = pic->data[3];
740 mpi->stride[0] = pic->linesize[0];
741 mpi->stride[1] = pic->linesize[1];
742 mpi->stride[2] = pic->linesize[2];
743 mpi->stride[3] = pic->linesize[3];
746 if (!mpi->planes[0])
747 return NULL;
749 if (ctx->best_csp == IMGFMT_422P && mpi->chroma_y_shift == 1) {
750 // we have 422p but user wants 420p
751 mpi->stride[1] *= 2;
752 mpi->stride[2] *= 2;
755 #if HAVE_BIGENDIAN
756 // FIXME: this might cause problems for buffers with FF_BUFFER_HINTS_PRESERVE
757 if (mpi->bpp == 8)
758 swap_palette(mpi->planes[1]);
759 #endif
761 mpi->qscale = pic->qscale_table;
762 mpi->qstride = pic->qstride;
763 mpi->pict_type = pic->pict_type;
764 mpi->qscale_type = pic->qscale_type;
765 mpi->fields = MP_IMGFIELD_ORDERED;
766 if (pic->interlaced_frame)
767 mpi->fields |= MP_IMGFIELD_INTERLACED;
768 if (pic->top_field_first)
769 mpi->fields |= MP_IMGFIELD_TOP_FIRST;
770 if (pic->repeat_pict == 1)
771 mpi->fields |= MP_IMGFIELD_REPEAT_FIRST;
773 return mpi;
776 static enum PixelFormat get_format(struct AVCodecContext *avctx,
777 const enum PixelFormat *fmt)
779 sh_video_t *sh = avctx->opaque;
780 int i;
782 for (i = 0; fmt[i] != PIX_FMT_NONE; i++) {
783 int imgfmt = pixfmt2imgfmt(fmt[i]);
784 if (!IMGFMT_IS_HWACCEL(imgfmt))
785 continue;
786 mp_msg(MSGT_DECVIDEO, MSGL_V, "[VD_FFMPEG] Trying pixfmt=%d.\n", i);
787 if (init_vo(sh, fmt[i]) >= 0)
788 break;
790 return fmt[i];
793 static int control(sh_video_t *sh, int cmd, void *arg, ...)
795 vd_ffmpeg_ctx *ctx = sh->context;
796 AVCodecContext *avctx = ctx->avctx;
797 switch (cmd) {
798 case VDCTRL_QUERY_FORMAT: {
799 int format = (*((int *)arg));
800 if (format == ctx->best_csp)
801 return CONTROL_TRUE;
802 // possible conversions:
803 switch (format) {
804 case IMGFMT_YV12:
805 case IMGFMT_IYUV:
806 case IMGFMT_I420:
807 // "converted" using pointer/stride modification
808 if (ctx->best_csp == IMGFMT_YV12)
809 return CONTROL_TRUE; // u/v swap
810 if (ctx->best_csp == IMGFMT_422P && !ctx->do_dr1)
811 return CONTROL_TRUE; // half stride
812 break;
814 return CONTROL_FALSE;
816 case VDCTRL_RESYNC_STREAM:
817 avcodec_flush_buffers(avctx);
818 return CONTROL_TRUE;
819 case VDCTRL_QUERY_UNSEEN_FRAMES:;
820 int delay = avctx->has_b_frames;
821 if (avctx->active_thread_type & FF_THREAD_FRAME)
822 delay += avctx->thread_count - 1;
823 return delay + 10;
824 case VDCTRL_RESET_ASPECT:
825 if (ctx->vo_initialized)
826 ctx->vo_initialized = false;
827 init_vo(sh, avctx->pix_fmt);
828 return true;
830 return CONTROL_UNKNOWN;
833 const struct vd_functions mpcodecs_vd_ffmpeg = {
834 .info = &info,
835 .init = init,
836 .uninit = uninit,
837 .control = control,
838 .decode2 = decode