1 /*
2  * This file is part of mpv.
3  *
4  * mpv is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * mpv 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 Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include <float.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <pthread.h>
22 #include <assert.h>
23 #include <stdbool.h>
24 
25 #include <libavcodec/avcodec.h>
26 #include <libavutil/common.h>
27 #include <libavutil/hwcontext.h>
28 #include <libavutil/opt.h>
29 #include <libavutil/intreadwrite.h>
30 #include <libavutil/pixdesc.h>
31 
32 #include "config.h"
33 
34 #include "mpv_talloc.h"
35 #include "common/global.h"
36 #include "common/msg.h"
37 #include "options/m_config.h"
38 #include "options/options.h"
39 #include "misc/bstr.h"
40 #include "common/av_common.h"
41 #include "common/codecs.h"
42 
43 #include "video/fmt-conversion.h"
44 
45 #include "filters/f_decoder_wrapper.h"
46 #include "filters/filter_internal.h"
47 #include "video/hwdec.h"
48 #include "video/img_format.h"
49 #include "video/mp_image.h"
50 #include "video/mp_image_pool.h"
51 #include "demux/demux.h"
52 #include "demux/stheader.h"
53 #include "demux/packet.h"
54 #include "video/csputils.h"
55 #include "video/sws_utils.h"
56 #include "video/out/vo.h"
57 
58 #include "options/m_option.h"
59 
60 static void init_avctx(struct mp_filter *vd);
61 static void uninit_avctx(struct mp_filter *vd);
62 
63 static int get_buffer2_direct(AVCodecContext *avctx, AVFrame *pic, int flags);
64 static enum AVPixelFormat get_format_hwdec(struct AVCodecContext *avctx,
65                                            const enum AVPixelFormat *pix_fmt);
66 static int hwdec_opt_help(struct mp_log *log, const m_option_t *opt,
67                           struct bstr name);
68 
69 #define HWDEC_DELAY_QUEUE_COUNT 2
70 
71 #define OPT_BASE_STRUCT struct vd_lavc_params
72 
73 struct vd_lavc_params {
74     int fast;
75     int show_all;
76     int skip_loop_filter;
77     int skip_idct;
78     int skip_frame;
79     int framedrop;
80     int threads;
81     int bitexact;
82     int old_x264;
83     int check_hw_profile;
84     int software_fallback;
85     char **avopts;
86     int dr;
87     char *hwdec_api;
88     char *hwdec_codecs;
89     int hwdec_image_format;
90     int hwdec_extra_frames;
91 };
92 
93 static const struct m_opt_choice_alternatives discard_names[] = {
94     {"none",        AVDISCARD_NONE},
95     {"default",     AVDISCARD_DEFAULT},
96     {"nonref",      AVDISCARD_NONREF},
97     {"bidir",       AVDISCARD_BIDIR},
98     {"nonkey",      AVDISCARD_NONKEY},
99     {"all",         AVDISCARD_ALL},
100     {0}
101 };
102 #define OPT_DISCARD(field) OPT_CHOICE_C(field, discard_names)
103 
104 const struct m_sub_options vd_lavc_conf = {
105     .opts = (const m_option_t[]){
106         {"vd-lavc-fast", OPT_FLAG(fast)},
107         {"vd-lavc-show-all", OPT_FLAG(show_all)},
108         {"vd-lavc-skiploopfilter", OPT_DISCARD(skip_loop_filter)},
109         {"vd-lavc-skipidct", OPT_DISCARD(skip_idct)},
110         {"vd-lavc-skipframe", OPT_DISCARD(skip_frame)},
111         {"vd-lavc-framedrop", OPT_DISCARD(framedrop)},
112         {"vd-lavc-threads", OPT_INT(threads), M_RANGE(0, DBL_MAX)},
113         {"vd-lavc-bitexact", OPT_FLAG(bitexact)},
114         {"vd-lavc-assume-old-x264", OPT_FLAG(old_x264)},
115         {"vd-lavc-check-hw-profile", OPT_FLAG(check_hw_profile)},
116         {"vd-lavc-software-fallback", OPT_CHOICE(software_fallback,
117             {"no", INT_MAX}, {"yes", 1}), M_RANGE(1, INT_MAX)},
118         {"vd-lavc-o", OPT_KEYVALUELIST(avopts)},
119         {"vd-lavc-dr", OPT_FLAG(dr)},
120         {"hwdec", OPT_STRING(hwdec_api),
121             .help = hwdec_opt_help,
122             .flags = M_OPT_OPTIONAL_PARAM | UPDATE_HWDEC},
123         {"hwdec-codecs", OPT_STRING(hwdec_codecs)},
124         {"hwdec-image-format", OPT_IMAGEFORMAT(hwdec_image_format)},
125         {"hwdec-extra-frames", OPT_INT(hwdec_extra_frames), M_RANGE(0, 256)},
126         {0}
127     },
128     .size = sizeof(struct vd_lavc_params),
129     .defaults = &(const struct vd_lavc_params){
130         .show_all = 0,
131         .check_hw_profile = 1,
132         .software_fallback = 3,
133         .skip_loop_filter = AVDISCARD_DEFAULT,
134         .skip_idct = AVDISCARD_DEFAULT,
135         .skip_frame = AVDISCARD_DEFAULT,
136         .framedrop = AVDISCARD_NONREF,
137         .dr = 1,
138         .hwdec_api = "no",
139         .hwdec_codecs = "h264,vc1,hevc,vp8,vp9,av1",
140         // Maximum number of surfaces the player wants to buffer. This number
141         // might require adjustment depending on whatever the player does;
142         // for example, if vo_gpu increases the number of reference surfaces for
143         // interpolation, this value has to be increased too.
144         .hwdec_extra_frames = 6,
145     },
146 };
147 
148 struct hwdec_info {
149     char name[64];
150     char method_name[24]; // non-unique name describing the hwdec method
151     const AVCodec *codec; // implemented by this codec
152     enum AVHWDeviceType lavc_device; // if not NONE, get a hwdevice
153     bool copying; // if true, outputs sw frames, or copy to sw ourselves
154     enum AVPixelFormat pix_fmt; // if not NONE, select in get_format
155     bool use_hw_frames; // set AVCodecContext.hw_frames_ctx
156     bool use_hw_device; // set AVCodecContext.hw_device_ctx
157     unsigned int flags; // HWDEC_FLAG_*
158 
159     // for internal sorting
160     int auto_pos;
161     int rank;
162 };
163 
164 typedef struct lavc_ctx {
165     struct mp_log *log;
166     struct m_config_cache *opts_cache;
167     struct vd_lavc_params *opts;
168     struct mp_codec_params *codec;
169     AVCodecContext *avctx;
170     AVFrame *pic;
171     bool use_hwdec;
172     struct hwdec_info hwdec; // valid only if use_hwdec==true
173     AVRational codec_timebase;
174     enum AVDiscard skip_frame;
175     bool flushing;
176     struct lavc_state state;
177     const char *decoder;
178     bool hwdec_failed;
179     bool hwdec_notified;
180 
181     bool intra_only;
182     int framedrop_flags;
183 
184     bool hw_probing;
185     struct demux_packet **sent_packets;
186     int num_sent_packets;
187 
188     struct demux_packet **requeue_packets;
189     int num_requeue_packets;
190 
191     struct mp_image **delay_queue;
192     int num_delay_queue;
193     int max_delay_queue;
194 
195     // From VO
196     struct vo *vo;
197     struct mp_hwdec_devices *hwdec_devs;
198 
199     // Wrapped AVHWDeviceContext* used for decoding.
200     AVBufferRef *hwdec_dev;
201 
202     bool hwdec_request_reinit;
203     int hwdec_fail_count;
204 
205     struct mp_image_pool *hwdec_swpool;
206 
207     AVBufferRef *cached_hw_frames_ctx;
208 
209     // --- The following fields are protected by dr_lock.
210     pthread_mutex_t dr_lock;
211     bool dr_failed;
212     struct mp_image_pool *dr_pool;
213     int dr_imgfmt, dr_w, dr_h, dr_stride_align;
214 
215     struct mp_decoder public;
216 } vd_ffmpeg_ctx;
217 
218 enum {
219     HWDEC_FLAG_AUTO         = (1 << 0), // prioritize in autoprobe order
220     HWDEC_FLAG_WHITELIST    = (1 << 1), // whitelist for auto-safe
221 };
222 
223 struct autoprobe_info {
224     const char *method_name;
225     unsigned int flags;         // HWDEC_FLAG_*
226 };
227 
228 // Things not included in this list will be tried last, in random order.
229 const struct autoprobe_info hwdec_autoprobe_info[] = {
230     {"d3d11va",         HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
231     {"dxva2",           HWDEC_FLAG_AUTO},
232     {"dxva2-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
233     {"d3d11va-copy",    HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
234     {"nvdec",           HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
235     {"nvdec-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
236     {"vaapi",           HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
237     {"vaapi-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
238     {"vdpau",           HWDEC_FLAG_AUTO},
239     {"vdpau-copy",      HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
240     {"mmal",            HWDEC_FLAG_AUTO},
241     {"mmal-copy",       HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
242     {"videotoolbox",    HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
243     {"videotoolbox-copy", HWDEC_FLAG_AUTO | HWDEC_FLAG_WHITELIST},
244     {0}
245 };
246 
hwdec_compare(const void * p1,const void * p2)247 static int hwdec_compare(const void *p1, const void *p2)
248 {
249     struct hwdec_info *h1 = (void *)p1;
250     struct hwdec_info *h2 = (void *)p2;
251 
252     if (h1 == h2)
253         return 0;
254 
255     // Strictly put non-preferred hwdecs to the end of the list.
256     if ((h1->auto_pos == INT_MAX) != (h2->auto_pos == INT_MAX))
257         return h1->auto_pos == INT_MAX ? 1 : -1;
258     // List non-copying entries first, so --hwdec=auto takes them.
259     if (h1->copying != h2->copying)
260         return h1->copying ? 1 : -1;
261     // Order by autoprobe preferrence order.
262     if (h1->auto_pos != h2->auto_pos)
263         return h1->auto_pos > h2->auto_pos ? 1 : -1;
264     // Fallback sort order to make sorting stable.
265     return h1->rank > h2->rank ? 1 :-1;
266 }
267 
268 // (This takes care of some bookkeeping too, like setting info.name)
add_hwdec_item(struct hwdec_info ** infos,int * num_infos,struct hwdec_info info)269 static void add_hwdec_item(struct hwdec_info **infos, int *num_infos,
270                            struct hwdec_info info)
271 {
272     if (info.copying)
273         mp_snprintf_cat(info.method_name, sizeof(info.method_name), "-copy");
274 
275     // (Including the codec name in case this is a wrapper looks pretty dumb,
276     // but better not have them clash with hwaccels and others.)
277     snprintf(info.name, sizeof(info.name), "%s-%s",
278              info.codec->name, info.method_name);
279 
280     info.rank = *num_infos;
281     info.auto_pos = INT_MAX;
282 
283     for (int x = 0; hwdec_autoprobe_info[x].method_name; x++) {
284         const struct autoprobe_info *entry = &hwdec_autoprobe_info[x];
285         if (strcmp(entry->method_name, info.method_name) == 0) {
286             info.flags |= entry->flags;
287             if (info.flags & HWDEC_FLAG_AUTO)
288                 info.auto_pos = x;
289         }
290     }
291 
292     MP_TARRAY_APPEND(NULL, *infos, *num_infos, info);
293 }
294 
add_all_hwdec_methods(struct hwdec_info ** infos,int * num_infos)295 static void add_all_hwdec_methods(struct hwdec_info **infos, int *num_infos)
296 {
297     const AVCodec *codec = NULL;
298     void *iter = NULL;
299     while (1) {
300         codec = av_codec_iterate(&iter);
301         if (!codec)
302             break;
303         if (codec->type != AVMEDIA_TYPE_VIDEO || !av_codec_is_decoder(codec))
304             continue;
305 
306         struct hwdec_info info_template = {
307             .pix_fmt = AV_PIX_FMT_NONE,
308             .codec = codec,
309         };
310 
311         const char *wrapper = NULL;
312         if (codec->capabilities & (AV_CODEC_CAP_HARDWARE | AV_CODEC_CAP_HYBRID))
313             wrapper = codec->wrapper_name;
314 
315         // A decoder can provide multiple methods. In particular, hwaccels
316         // provide various methods (e.g. native h264 with vaapi & d3d11), but
317         // even wrapper decoders could provide multiple methods.
318         bool found_any = false;
319         for (int n = 0; ; n++) {
320             const AVCodecHWConfig *cfg = avcodec_get_hw_config(codec, n);
321             if (!cfg)
322                 break;
323 
324             if ((cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) ||
325                 (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
326             {
327                 struct hwdec_info info = info_template;
328                 info.lavc_device = cfg->device_type;
329                 info.pix_fmt = cfg->pix_fmt;
330 
331                 const char *name = av_hwdevice_get_type_name(cfg->device_type);
332                 assert(name); // API violation by libavcodec
333 
334                 // nvdec hwaccels and the cuvid full decoder clash with their
335                 // naming, so fix it here; we also prefer nvdec for the hwaccel.
336                 if (strcmp(name, "cuda") == 0 && !wrapper)
337                     name = "nvdec";
338 
339                 snprintf(info.method_name, sizeof(info.method_name), "%s", name);
340 
341                 // Usually we want to prefer using hw_frames_ctx for true
342                 // hwaccels only, but we actually don't have any way to detect
343                 // those, so always use hw_frames_ctx if offered.
344                 if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX) {
345                     info.use_hw_frames = true;
346                 } else {
347                     info.use_hw_device = true;
348                 }
349 
350                 // Direct variant.
351                 add_hwdec_item(infos, num_infos, info);
352 
353                 // Copy variant.
354                 info.copying = true;
355                 if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) {
356                     info.use_hw_frames = false;
357                     info.use_hw_device = true;
358                 }
359                 add_hwdec_item(infos, num_infos, info);
360 
361                 found_any = true;
362             } else if (cfg->methods & AV_CODEC_HW_CONFIG_METHOD_INTERNAL) {
363                 struct hwdec_info info = info_template;
364                 info.pix_fmt = cfg->pix_fmt;
365 
366                 const char *name = wrapper;
367                 if (!name)
368                     name = av_get_pix_fmt_name(info.pix_fmt);
369                 assert(name); // API violation by libavcodec
370 
371                 snprintf(info.method_name, sizeof(info.method_name), "%s", name);
372 
373                 // Direct variant.
374                 add_hwdec_item(infos, num_infos, info);
375 
376                 // Copy variant.
377                 info.copying = true;
378                 info.pix_fmt = AV_PIX_FMT_NONE; // trust it can do sw output
379                 add_hwdec_item(infos, num_infos, info);
380 
381                 found_any = true;
382             }
383         }
384 
385         if (!found_any && wrapper) {
386             // We _know_ there's something supported here, usually outputting
387             // sw surfaces. E.g. mediacodec (before hw_device_ctx support).
388 
389             struct hwdec_info info = info_template;
390             info.copying = true; // probably
391 
392             snprintf(info.method_name, sizeof(info.method_name), "%s", wrapper);
393             add_hwdec_item(infos, num_infos, info);
394         }
395     }
396 
397     qsort(*infos, *num_infos, sizeof(struct hwdec_info), hwdec_compare);
398 }
399 
hwdec_codec_allowed(struct mp_filter * vd,const char * codec)400 static bool hwdec_codec_allowed(struct mp_filter *vd, const char *codec)
401 {
402     vd_ffmpeg_ctx *ctx = vd->priv;
403     bstr s = bstr0(ctx->opts->hwdec_codecs);
404     while (s.len) {
405         bstr item;
406         bstr_split_tok(s, ",", &item, &s);
407         if (bstr_equals0(item, "all") || bstr_equals0(item, codec))
408             return true;
409     }
410     return false;
411 }
412 
hwdec_create_dev(struct mp_filter * vd,struct hwdec_info * hwdec,bool autoprobe)413 static AVBufferRef *hwdec_create_dev(struct mp_filter *vd,
414                                      struct hwdec_info *hwdec,
415                                      bool autoprobe)
416 {
417     vd_ffmpeg_ctx *ctx = vd->priv;
418     assert(hwdec->lavc_device);
419 
420     if (hwdec->copying) {
421         const struct hwcontext_fns *fns =
422             hwdec_get_hwcontext_fns(hwdec->lavc_device);
423         if (fns && fns->create_dev) {
424             struct hwcontext_create_dev_params params = {
425                 .probing = autoprobe,
426             };
427             return fns->create_dev(vd->global, vd->log, &params);
428         } else {
429             AVBufferRef* ref = NULL;
430             av_hwdevice_ctx_create(&ref, hwdec->lavc_device, NULL, NULL, 0);
431             return ref;
432         }
433     } else if (ctx->hwdec_devs) {
434         hwdec_devices_request_all(ctx->hwdec_devs);
435         return hwdec_devices_get_lavc(ctx->hwdec_devs, hwdec->lavc_device);
436     }
437 
438     return NULL;
439 }
440 
441 // Select if and which hwdec to use. Also makes sure to get the decode device.
select_and_set_hwdec(struct mp_filter * vd)442 static void select_and_set_hwdec(struct mp_filter *vd)
443 {
444     vd_ffmpeg_ctx *ctx = vd->priv;
445     const char *codec = ctx->codec->codec;
446 
447     m_config_cache_update(ctx->opts_cache);
448 
449     bstr opt = bstr0(ctx->opts->hwdec_api);
450 
451     bool hwdec_requested = !bstr_equals0(opt, "no");
452     bool hwdec_auto_all = bstr_equals0(opt, "auto") ||
453                           bstr_equals0(opt, "yes") ||
454                           bstr_equals0(opt, "");
455     bool hwdec_auto_safe = bstr_equals0(opt, "auto-safe") ||
456                            bstr_equals0(opt, "auto-copy-safe");
457     bool hwdec_auto_copy = bstr_equals0(opt, "auto-copy") ||
458                            bstr_equals0(opt, "auto-copy-safe");
459     bool hwdec_auto = hwdec_auto_all || hwdec_auto_copy || hwdec_auto_safe;
460 
461     if (!hwdec_requested) {
462         MP_VERBOSE(vd, "No hardware decoding requested.\n");
463     } else if (!hwdec_codec_allowed(vd, codec)) {
464         MP_VERBOSE(vd, "Not trying to use hardware decoding: codec %s is not "
465                    "on whitelist.\n", codec);
466     } else {
467         struct hwdec_info *hwdecs = NULL;
468         int num_hwdecs = 0;
469         add_all_hwdec_methods(&hwdecs, &num_hwdecs);
470 
471         for (int n = 0; n < num_hwdecs; n++) {
472             struct hwdec_info *hwdec = &hwdecs[n];
473 
474             const char *hw_codec = mp_codec_from_av_codec_id(hwdec->codec->id);
475             if (!hw_codec || strcmp(hw_codec, codec) != 0)
476                 continue;
477 
478             if (!hwdec_auto && !(bstr_equals0(opt, hwdec->method_name) ||
479                                  bstr_equals0(opt, hwdec->name)))
480                 continue;
481 
482             if (hwdec_auto_safe && !(hwdec->flags & HWDEC_FLAG_WHITELIST))
483                 continue;
484 
485             MP_VERBOSE(vd, "Looking at hwdec %s...\n", hwdec->name);
486 
487             if (hwdec_auto_copy && !hwdec->copying) {
488                 MP_VERBOSE(vd, "Not using this for auto-copy.\n");
489                 continue;
490             }
491 
492             if (hwdec->lavc_device) {
493                 ctx->hwdec_dev = hwdec_create_dev(vd, hwdec, hwdec_auto);
494                 if (!ctx->hwdec_dev) {
495                     MP_VERBOSE(vd, "Could not create device.\n");
496                     continue;
497                 }
498 
499                 const struct hwcontext_fns *fns =
500                             hwdec_get_hwcontext_fns(hwdec->lavc_device);
501                 if (fns && fns->is_emulated && fns->is_emulated(ctx->hwdec_dev)) {
502                     if (hwdec_auto) {
503                         MP_VERBOSE(vd, "Not using emulated API.\n");
504                         av_buffer_unref(&ctx->hwdec_dev);
505                         continue;
506                     }
507                     MP_WARN(vd, "Using emulated hardware decoding API.\n");
508                 }
509             } else if (!hwdec->copying) {
510                 // Most likely METHOD_INTERNAL, which often use delay-loaded
511                 // VO support as well.
512                 if (ctx->hwdec_devs)
513                     hwdec_devices_request_all(ctx->hwdec_devs);
514             }
515 
516             ctx->use_hwdec = true;
517             ctx->hwdec = *hwdec;
518             break;
519         }
520 
521         talloc_free(hwdecs);
522 
523         if (!ctx->use_hwdec)
524             MP_VERBOSE(vd, "No hardware decoding available for this codec.\n");
525     }
526 
527     if (ctx->use_hwdec) {
528         MP_VERBOSE(vd, "Trying hardware decoding via %s.\n", ctx->hwdec.name);
529         if (strcmp(ctx->decoder, ctx->hwdec.codec->name) != 0)
530             MP_VERBOSE(vd, "Using underlying hw-decoder '%s'\n",
531                        ctx->hwdec.codec->name);
532     } else {
533         MP_VERBOSE(vd, "Using software decoding.\n");
534     }
535 }
536 
hwdec_opt_help(struct mp_log * log,const m_option_t * opt,struct bstr name)537 static int hwdec_opt_help(struct mp_log *log, const m_option_t *opt,
538                           struct bstr name)
539 {
540     struct hwdec_info *hwdecs = NULL;
541     int num_hwdecs = 0;
542     add_all_hwdec_methods(&hwdecs, &num_hwdecs);
543 
544     mp_info(log, "Valid values (with alternative full names):\n");
545 
546     for (int n = 0; n < num_hwdecs; n++) {
547         struct hwdec_info *hwdec = &hwdecs[n];
548 
549         mp_info(log, "  %s (%s)\n", hwdec->method_name, hwdec->name);
550     }
551 
552     talloc_free(hwdecs);
553 
554     mp_info(log, "  auto (yes '')\n");
555     mp_info(log, "  no\n");
556     mp_info(log, "  auto-safe\n");
557     mp_info(log, "  auto-copy\n");
558     mp_info(log, "  auto-copy-safe\n");
559 
560     return M_OPT_EXIT;
561 }
562 
force_fallback(struct mp_filter * vd)563 static void force_fallback(struct mp_filter *vd)
564 {
565     vd_ffmpeg_ctx *ctx = vd->priv;
566 
567     uninit_avctx(vd);
568     int lev = ctx->hwdec_notified ? MSGL_WARN : MSGL_V;
569     mp_msg(vd->log, lev, "Falling back to software decoding.\n");
570     init_avctx(vd);
571 }
572 
reinit(struct mp_filter * vd)573 static void reinit(struct mp_filter *vd)
574 {
575     vd_ffmpeg_ctx *ctx = vd->priv;
576 
577     uninit_avctx(vd);
578 
579     select_and_set_hwdec(vd);
580 
581     bool use_hwdec = ctx->use_hwdec;
582     init_avctx(vd);
583     if (!ctx->avctx && use_hwdec)
584         force_fallback(vd);
585 }
586 
init_avctx(struct mp_filter * vd)587 static void init_avctx(struct mp_filter *vd)
588 {
589     vd_ffmpeg_ctx *ctx = vd->priv;
590     struct vd_lavc_params *lavc_param = ctx->opts;
591     struct mp_codec_params *c = ctx->codec;
592 
593     m_config_cache_update(ctx->opts_cache);
594 
595     assert(!ctx->avctx);
596 
597     const AVCodec *lavc_codec = NULL;
598 
599     if (ctx->use_hwdec) {
600         lavc_codec = ctx->hwdec.codec;
601     } else {
602         lavc_codec = avcodec_find_decoder_by_name(ctx->decoder);
603     }
604     if (!lavc_codec)
605         return;
606 
607     const AVCodecDescriptor *desc = avcodec_descriptor_get(lavc_codec->id);
608     ctx->intra_only = desc && (desc->props & AV_CODEC_PROP_INTRA_ONLY);
609 
610     ctx->codec_timebase = mp_get_codec_timebase(ctx->codec);
611 
612     // This decoder does not read pkt_timebase correctly yet.
613     if (strstr(lavc_codec->name, "_mmal"))
614         ctx->codec_timebase = (AVRational){1, 1000000};
615 
616     ctx->hwdec_failed = false;
617     ctx->hwdec_request_reinit = false;
618     ctx->avctx = avcodec_alloc_context3(lavc_codec);
619     AVCodecContext *avctx = ctx->avctx;
620     if (!ctx->avctx)
621         goto error;
622     avctx->codec_type = AVMEDIA_TYPE_VIDEO;
623     avctx->codec_id = lavc_codec->id;
624     avctx->pkt_timebase = ctx->codec_timebase;
625 
626     ctx->pic = av_frame_alloc();
627     if (!ctx->pic)
628         goto error;
629 
630     if (ctx->use_hwdec) {
631         avctx->opaque = vd;
632         avctx->thread_count = 1;
633         avctx->hwaccel_flags |= AV_HWACCEL_FLAG_IGNORE_LEVEL;
634         if (!lavc_param->check_hw_profile)
635             avctx->hwaccel_flags |= AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH;
636 
637         if (ctx->hwdec.use_hw_device) {
638             if (ctx->hwdec_dev)
639                 avctx->hw_device_ctx = av_buffer_ref(ctx->hwdec_dev);
640             if (!avctx->hw_device_ctx)
641                 goto error;
642         }
643         if (ctx->hwdec.use_hw_frames) {
644             if (!ctx->hwdec_dev)
645                 goto error;
646         }
647 
648         if (ctx->hwdec.pix_fmt != AV_PIX_FMT_NONE)
649             avctx->get_format = get_format_hwdec;
650 
651         // Some APIs benefit from this, for others it's additional bloat.
652         if (ctx->hwdec.copying)
653             ctx->max_delay_queue = HWDEC_DELAY_QUEUE_COUNT;
654         ctx->hw_probing = true;
655     } else {
656         mp_set_avcodec_threads(vd->log, avctx, lavc_param->threads);
657     }
658 
659     if (!ctx->use_hwdec && ctx->vo && lavc_param->dr) {
660         avctx->opaque = vd;
661         avctx->get_buffer2 = get_buffer2_direct;
662 #if LIBAVCODEC_VERSION_MAJOR < 60
663         avctx->thread_safe_callbacks = 1;
664 #endif
665     }
666 
667     avctx->flags |= lavc_param->bitexact ? AV_CODEC_FLAG_BITEXACT : 0;
668     avctx->flags2 |= lavc_param->fast ? AV_CODEC_FLAG2_FAST : 0;
669 
670     if (lavc_param->show_all)
671         avctx->flags |= AV_CODEC_FLAG_OUTPUT_CORRUPT;
672 
673     avctx->skip_loop_filter = lavc_param->skip_loop_filter;
674     avctx->skip_idct = lavc_param->skip_idct;
675     avctx->skip_frame = lavc_param->skip_frame;
676 
677     if (lavc_codec->id == AV_CODEC_ID_H264 && lavc_param->old_x264)
678         av_opt_set(avctx, "x264_build", "150", AV_OPT_SEARCH_CHILDREN);
679 
680     mp_set_avopts(vd->log, avctx, lavc_param->avopts);
681 
682     // Do this after the above avopt handling in case it changes values
683     ctx->skip_frame = avctx->skip_frame;
684 
685     if (mp_set_avctx_codec_headers(avctx, c) < 0) {
686         MP_ERR(vd, "Could not set codec parameters.\n");
687         goto error;
688     }
689 
690     /* open it */
691     if (avcodec_open2(avctx, lavc_codec, NULL) < 0)
692         goto error;
693 
694     // Sometimes, the first packet contains information required for correct
695     // decoding of the rest of the stream. The only currently known case is the
696     // x264 build number (encoded in a SEI element), needed to enable a
697     // workaround for broken 4:4:4 streams produced by older x264 versions.
698     if (lavc_codec->id == AV_CODEC_ID_H264 && c->first_packet) {
699         AVPacket avpkt;
700         mp_set_av_packet(&avpkt, c->first_packet, &ctx->codec_timebase);
701         avcodec_send_packet(avctx, &avpkt);
702         avcodec_receive_frame(avctx, ctx->pic);
703         av_frame_unref(ctx->pic);
704         avcodec_flush_buffers(ctx->avctx);
705     }
706 
707     return;
708 
709 error:
710     MP_ERR(vd, "Could not open codec.\n");
711     uninit_avctx(vd);
712 }
713 
reset_avctx(struct mp_filter * vd)714 static void reset_avctx(struct mp_filter *vd)
715 {
716     vd_ffmpeg_ctx *ctx = vd->priv;
717 
718     if (ctx->avctx && avcodec_is_open(ctx->avctx))
719         avcodec_flush_buffers(ctx->avctx);
720     ctx->flushing = false;
721     ctx->hwdec_request_reinit = false;
722 }
723 
flush_all(struct mp_filter * vd)724 static void flush_all(struct mp_filter *vd)
725 {
726     vd_ffmpeg_ctx *ctx = vd->priv;
727 
728     for (int n = 0; n < ctx->num_delay_queue; n++)
729         talloc_free(ctx->delay_queue[n]);
730     ctx->num_delay_queue = 0;
731 
732     for (int n = 0; n < ctx->num_sent_packets; n++)
733         talloc_free(ctx->sent_packets[n]);
734     ctx->num_sent_packets = 0;
735 
736     for (int n = 0; n < ctx->num_requeue_packets; n++)
737         talloc_free(ctx->requeue_packets[n]);
738     ctx->num_requeue_packets = 0;
739 
740     reset_avctx(vd);
741 }
742 
uninit_avctx(struct mp_filter * vd)743 static void uninit_avctx(struct mp_filter *vd)
744 {
745     vd_ffmpeg_ctx *ctx = vd->priv;
746 
747     flush_all(vd);
748     av_frame_free(&ctx->pic);
749     av_buffer_unref(&ctx->cached_hw_frames_ctx);
750 
751     avcodec_free_context(&ctx->avctx);
752 
753     av_buffer_unref(&ctx->hwdec_dev);
754 
755     ctx->hwdec_failed = false;
756     ctx->hwdec_fail_count = 0;
757     ctx->max_delay_queue = 0;
758     ctx->hw_probing = false;
759     ctx->hwdec = (struct hwdec_info){0};
760     ctx->use_hwdec = false;
761 }
762 
init_generic_hwaccel(struct mp_filter * vd,enum AVPixelFormat hw_fmt)763 static int init_generic_hwaccel(struct mp_filter *vd, enum AVPixelFormat hw_fmt)
764 {
765     struct lavc_ctx *ctx = vd->priv;
766     AVBufferRef *new_frames_ctx = NULL;
767 
768     if (!ctx->hwdec.use_hw_frames)
769         return 0;
770 
771     if (!ctx->hwdec_dev) {
772         MP_ERR(ctx, "Missing device context.\n");
773         goto error;
774     }
775 
776     if (avcodec_get_hw_frames_parameters(ctx->avctx,
777                                 ctx->hwdec_dev, hw_fmt, &new_frames_ctx) < 0)
778     {
779         MP_VERBOSE(ctx, "Hardware decoding of this stream is unsupported?\n");
780         goto error;
781     }
782 
783     AVHWFramesContext *new_fctx = (void *)new_frames_ctx->data;
784 
785     if (ctx->opts->hwdec_image_format)
786         new_fctx->sw_format = imgfmt2pixfmt(ctx->opts->hwdec_image_format);
787 
788     // 1 surface is already included by libavcodec. The field is 0 if the
789     // hwaccel supports dynamic surface allocation.
790     if (new_fctx->initial_pool_size)
791         new_fctx->initial_pool_size += ctx->opts->hwdec_extra_frames - 1;
792 
793     const struct hwcontext_fns *fns =
794         hwdec_get_hwcontext_fns(new_fctx->device_ctx->type);
795 
796     if (fns && fns->refine_hwframes)
797         fns->refine_hwframes(new_frames_ctx);
798 
799     // We might be able to reuse a previously allocated frame pool.
800     if (ctx->cached_hw_frames_ctx) {
801         AVHWFramesContext *old_fctx = (void *)ctx->cached_hw_frames_ctx->data;
802 
803         if (new_fctx->format            != old_fctx->format ||
804             new_fctx->sw_format         != old_fctx->sw_format ||
805             new_fctx->width             != old_fctx->width ||
806             new_fctx->height            != old_fctx->height ||
807             new_fctx->initial_pool_size != old_fctx->initial_pool_size)
808             av_buffer_unref(&ctx->cached_hw_frames_ctx);
809     }
810 
811     if (!ctx->cached_hw_frames_ctx) {
812         if (av_hwframe_ctx_init(new_frames_ctx) < 0) {
813             MP_ERR(ctx, "Failed to allocate hw frames.\n");
814             goto error;
815         }
816 
817         ctx->cached_hw_frames_ctx = new_frames_ctx;
818         new_frames_ctx = NULL;
819     }
820 
821     ctx->avctx->hw_frames_ctx = av_buffer_ref(ctx->cached_hw_frames_ctx);
822     if (!ctx->avctx->hw_frames_ctx)
823         goto error;
824 
825     av_buffer_unref(&new_frames_ctx);
826     return 0;
827 
828 error:
829     av_buffer_unref(&new_frames_ctx);
830     av_buffer_unref(&ctx->cached_hw_frames_ctx);
831     return -1;
832 }
833 
get_format_hwdec(struct AVCodecContext * avctx,const enum AVPixelFormat * fmt)834 static enum AVPixelFormat get_format_hwdec(struct AVCodecContext *avctx,
835                                            const enum AVPixelFormat *fmt)
836 {
837     struct mp_filter *vd = avctx->opaque;
838     vd_ffmpeg_ctx *ctx = vd->priv;
839 
840     MP_VERBOSE(vd, "Pixel formats supported by decoder:");
841     for (int i = 0; fmt[i] != AV_PIX_FMT_NONE; i++)
842         MP_VERBOSE(vd, " %s", av_get_pix_fmt_name(fmt[i]));
843     MP_VERBOSE(vd, "\n");
844 
845     const char *profile = avcodec_profile_name(avctx->codec_id, avctx->profile);
846     MP_VERBOSE(vd, "Codec profile: %s (0x%x)\n", profile ? profile : "unknown",
847                avctx->profile);
848 
849     assert(ctx->use_hwdec);
850 
851     ctx->hwdec_request_reinit |= ctx->hwdec_failed;
852     ctx->hwdec_failed = false;
853 
854     enum AVPixelFormat select = AV_PIX_FMT_NONE;
855     for (int i = 0; fmt[i] != AV_PIX_FMT_NONE; i++) {
856         if (ctx->hwdec.pix_fmt == fmt[i]) {
857             if (init_generic_hwaccel(vd, fmt[i]) < 0)
858                 break;
859             select = fmt[i];
860             break;
861         }
862     }
863 
864     if (select == AV_PIX_FMT_NONE) {
865         ctx->hwdec_failed = true;
866         select = avcodec_default_get_format(avctx, fmt);
867     }
868 
869     const char *name = av_get_pix_fmt_name(select);
870     MP_VERBOSE(vd, "Requesting pixfmt '%s' from decoder.\n", name ? name : "-");
871     return select;
872 }
873 
get_buffer2_direct(AVCodecContext * avctx,AVFrame * pic,int flags)874 static int get_buffer2_direct(AVCodecContext *avctx, AVFrame *pic, int flags)
875 {
876     struct mp_filter *vd = avctx->opaque;
877     vd_ffmpeg_ctx *p = vd->priv;
878 
879     pthread_mutex_lock(&p->dr_lock);
880 
881     int w = pic->width;
882     int h = pic->height;
883     int linesize_align[AV_NUM_DATA_POINTERS] = {0};
884     avcodec_align_dimensions2(avctx, &w, &h, linesize_align);
885 
886     // We assume that different alignments are just different power-of-2s.
887     // Thus, a higher alignment always satisfies a lower alignment.
888     int stride_align = MP_IMAGE_BYTE_ALIGN;
889     for (int n = 0; n < AV_NUM_DATA_POINTERS; n++)
890         stride_align = MPMAX(stride_align, linesize_align[n]);
891 
892     int imgfmt = pixfmt2imgfmt(pic->format);
893     if (!imgfmt)
894         goto fallback;
895 
896     if (p->dr_failed)
897         goto fallback;
898 
899     // (For simplicity, we realloc on any parameter change, instead of trying
900     // to be clever.)
901     if (stride_align != p->dr_stride_align || w != p->dr_w || h != p->dr_h ||
902         imgfmt != p->dr_imgfmt)
903     {
904         mp_image_pool_clear(p->dr_pool);
905         p->dr_imgfmt = imgfmt;
906         p->dr_w = w;
907         p->dr_h = h;
908         p->dr_stride_align = stride_align;
909         MP_DBG(p, "DR parameter change to %dx%d %s align=%d\n", w, h,
910                mp_imgfmt_to_name(imgfmt), stride_align);
911     }
912 
913     struct mp_image *img = mp_image_pool_get_no_alloc(p->dr_pool, imgfmt, w, h);
914     if (!img) {
915         MP_DBG(p, "Allocating new DR image...\n");
916         img = vo_get_image(p->vo, imgfmt, w, h, stride_align);
917         if (!img) {
918             MP_DBG(p, "...failed..\n");
919             goto fallback;
920         }
921 
922         // Now make the mp_image part of the pool. This requires doing magic to
923         // the image, so just add it to the pool and get it back to avoid
924         // dealing with magic ourselves. (Normally this never fails.)
925         mp_image_pool_add(p->dr_pool, img);
926         img = mp_image_pool_get_no_alloc(p->dr_pool, imgfmt, w, h);
927         if (!img)
928             goto fallback;
929     }
930 
931     // get_buffer2 callers seem very unappreciative of overwriting pic with a
932     // new reference. The AVCodecContext.get_buffer2 comments tell us exactly
933     // what we should do, so follow that.
934     for (int n = 0; n < 4; n++) {
935         pic->data[n] = img->planes[n];
936         pic->linesize[n] = img->stride[n];
937         pic->buf[n] = img->bufs[n];
938         img->bufs[n] = NULL;
939     }
940     talloc_free(img);
941 
942     pthread_mutex_unlock(&p->dr_lock);
943 
944     return 0;
945 
946 fallback:
947     if (!p->dr_failed)
948         MP_VERBOSE(p, "DR failed - disabling.\n");
949     p->dr_failed = true;
950     pthread_mutex_unlock(&p->dr_lock);
951 
952     return avcodec_default_get_buffer2(avctx, pic, flags);
953 }
954 
prepare_decoding(struct mp_filter * vd)955 static void prepare_decoding(struct mp_filter *vd)
956 {
957     vd_ffmpeg_ctx *ctx = vd->priv;
958     AVCodecContext *avctx = ctx->avctx;
959     struct vd_lavc_params *opts = ctx->opts;
960 
961     if (!avctx)
962         return;
963 
964     int drop = ctx->framedrop_flags;
965     if (drop == 1) {
966         avctx->skip_frame = opts->framedrop;    // normal framedrop
967     } else if (drop == 2) {
968         avctx->skip_frame = AVDISCARD_NONREF;   // hr-seek framedrop
969         // Can be much more aggressive for true intra codecs.
970         if (ctx->intra_only)
971             avctx->skip_frame = AVDISCARD_ALL;
972     } else {
973         avctx->skip_frame = ctx->skip_frame;    // normal playback
974     }
975 
976     if (ctx->hwdec_request_reinit)
977         reset_avctx(vd);
978 }
979 
handle_err(struct mp_filter * vd)980 static void handle_err(struct mp_filter *vd)
981 {
982     vd_ffmpeg_ctx *ctx = vd->priv;
983     struct vd_lavc_params *opts = ctx->opts;
984 
985     MP_WARN(vd, "Error while decoding frame%s!\n",
986             ctx->use_hwdec ? " (hardware decoding)" : "");
987 
988     if (ctx->use_hwdec) {
989         ctx->hwdec_fail_count += 1;
990         if (ctx->hwdec_fail_count >= opts->software_fallback)
991             ctx->hwdec_failed = true;
992     }
993 }
994 
send_packet(struct mp_filter * vd,struct demux_packet * pkt)995 static int send_packet(struct mp_filter *vd, struct demux_packet *pkt)
996 {
997     vd_ffmpeg_ctx *ctx = vd->priv;
998     AVCodecContext *avctx = ctx->avctx;
999 
1000     if (ctx->num_requeue_packets && ctx->requeue_packets[0] != pkt)
1001         return AVERROR(EAGAIN); // cannot consume the packet
1002 
1003     if (ctx->hwdec_failed)
1004         return AVERROR(EAGAIN);
1005 
1006     if (!ctx->avctx)
1007         return AVERROR_EOF;
1008 
1009     prepare_decoding(vd);
1010 
1011     if (avctx->skip_frame == AVDISCARD_ALL)
1012         return 0;
1013 
1014     AVPacket avpkt;
1015     mp_set_av_packet(&avpkt, pkt, &ctx->codec_timebase);
1016 
1017     int ret = avcodec_send_packet(avctx, pkt ? &avpkt : NULL);
1018     if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1019         return ret;
1020 
1021     if (ctx->hw_probing && ctx->num_sent_packets < 32 &&
1022         ctx->opts->software_fallback <= 32)
1023     {
1024         pkt = pkt ? demux_copy_packet(pkt) : NULL;
1025         MP_TARRAY_APPEND(ctx, ctx->sent_packets, ctx->num_sent_packets, pkt);
1026     }
1027 
1028     if (ret < 0)
1029         handle_err(vd);
1030     return ret;
1031 }
1032 
send_queued_packet(struct mp_filter * vd)1033 static void send_queued_packet(struct mp_filter *vd)
1034 {
1035     vd_ffmpeg_ctx *ctx = vd->priv;
1036 
1037     assert(ctx->num_requeue_packets);
1038     assert(!ctx->hw_probing);
1039 
1040     if (send_packet(vd, ctx->requeue_packets[0]) != AVERROR(EAGAIN)) {
1041         talloc_free(ctx->requeue_packets[0]);
1042         MP_TARRAY_REMOVE_AT(ctx->requeue_packets, ctx->num_requeue_packets, 0);
1043     }
1044 }
1045 
1046 // Returns whether decoder is still active (!EOF state).
decode_frame(struct mp_filter * vd)1047 static int decode_frame(struct mp_filter *vd)
1048 {
1049     vd_ffmpeg_ctx *ctx = vd->priv;
1050     AVCodecContext *avctx = ctx->avctx;
1051 
1052     if (!avctx)
1053         return AVERROR_EOF;
1054 
1055     prepare_decoding(vd);
1056 
1057     // Re-send old packets (typically after a hwdec fallback during init).
1058     if (ctx->num_requeue_packets)
1059         send_queued_packet(vd);
1060 
1061     int ret = avcodec_receive_frame(avctx, ctx->pic);
1062     if (ret < 0) {
1063         if (ret == AVERROR_EOF) {
1064             // If flushing was initialized earlier and has ended now, make it
1065             // start over in case we get new packets at some point in the future.
1066             // This must take the delay queue into account, so avctx returns EOF
1067             // until the delay queue has been drained.
1068             if (!ctx->num_delay_queue)
1069                 reset_avctx(vd);
1070         } else if (ret == AVERROR(EAGAIN)) {
1071             // just retry after caller writes a packet
1072         } else {
1073             handle_err(vd);
1074         }
1075         return ret;
1076     }
1077 
1078     // If something was decoded successfully, it must return a frame with valid
1079     // data.
1080     assert(ctx->pic->buf[0]);
1081 
1082     struct mp_image *mpi = mp_image_from_av_frame(ctx->pic);
1083     if (!mpi) {
1084         av_frame_unref(ctx->pic);
1085         return ret;
1086     }
1087 
1088     if (mpi->imgfmt == IMGFMT_CUDA && !mpi->planes[0]) {
1089         MP_ERR(vd, "CUDA frame without data. This is a FFmpeg bug.\n");
1090         talloc_free(mpi);
1091         handle_err(vd);
1092         return AVERROR_BUG;
1093     }
1094 
1095     ctx->hwdec_fail_count = 0;
1096 
1097     mpi->pts = mp_pts_from_av(ctx->pic->pts, &ctx->codec_timebase);
1098     mpi->dts = mp_pts_from_av(ctx->pic->pkt_dts, &ctx->codec_timebase);
1099 
1100     mpi->pkt_duration =
1101         mp_pts_from_av(ctx->pic->pkt_duration, &ctx->codec_timebase);
1102 
1103     av_frame_unref(ctx->pic);
1104 
1105     MP_TARRAY_APPEND(ctx, ctx->delay_queue, ctx->num_delay_queue, mpi);
1106     return ret;
1107 }
1108 
receive_frame(struct mp_filter * vd,struct mp_frame * out_frame)1109 static int receive_frame(struct mp_filter *vd, struct mp_frame *out_frame)
1110 {
1111     vd_ffmpeg_ctx *ctx = vd->priv;
1112 
1113     int ret = decode_frame(vd);
1114 
1115     if (ctx->hwdec_failed) {
1116         // Failed hardware decoding? Try again in software.
1117         struct demux_packet **pkts = ctx->sent_packets;
1118         int num_pkts = ctx->num_sent_packets;
1119         ctx->sent_packets = NULL;
1120         ctx->num_sent_packets = 0;
1121 
1122         force_fallback(vd);
1123 
1124         ctx->requeue_packets = pkts;
1125         ctx->num_requeue_packets = num_pkts;
1126 
1127         return 0; // force retry
1128     }
1129 
1130     if (ret == AVERROR(EAGAIN) && ctx->num_requeue_packets)
1131         return 0; // force retry, so send_queued_packet() gets called
1132 
1133     if (!ctx->num_delay_queue)
1134         return ret;
1135 
1136     if (ctx->num_delay_queue <= ctx->max_delay_queue && ret != AVERROR_EOF)
1137         return AVERROR(EAGAIN);
1138 
1139     struct mp_image *res = ctx->delay_queue[0];
1140     MP_TARRAY_REMOVE_AT(ctx->delay_queue, ctx->num_delay_queue, 0);
1141 
1142     res = res ? mp_img_swap_to_native(res) : NULL;
1143     if (!res)
1144         return AVERROR_UNKNOWN;
1145 
1146     if (ctx->use_hwdec && ctx->hwdec.copying && res->hwctx) {
1147         struct mp_image *sw = mp_image_hw_download(res, ctx->hwdec_swpool);
1148         mp_image_unrefp(&res);
1149         res = sw;
1150         if (!res) {
1151             MP_ERR(vd, "Could not copy back hardware decoded frame.\n");
1152             ctx->hwdec_fail_count = INT_MAX - 1; // force fallback
1153             handle_err(vd);
1154             return AVERROR_UNKNOWN;
1155         }
1156     }
1157 
1158     if (!ctx->hwdec_notified) {
1159         if (ctx->use_hwdec) {
1160             MP_INFO(vd, "Using hardware decoding (%s).\n",
1161                     ctx->hwdec.method_name);
1162         } else {
1163             MP_VERBOSE(vd, "Using software decoding.\n");
1164         }
1165         ctx->hwdec_notified = true;
1166     }
1167 
1168     if (ctx->hw_probing) {
1169         for (int n = 0; n < ctx->num_sent_packets; n++)
1170             talloc_free(ctx->sent_packets[n]);
1171         ctx->num_sent_packets = 0;
1172         ctx->hw_probing = false;
1173     }
1174 
1175     *out_frame = MAKE_FRAME(MP_FRAME_VIDEO, res);
1176     return 0;
1177 }
1178 
control(struct mp_filter * vd,enum dec_ctrl cmd,void * arg)1179 static int control(struct mp_filter *vd, enum dec_ctrl cmd, void *arg)
1180 {
1181     vd_ffmpeg_ctx *ctx = vd->priv;
1182     switch (cmd) {
1183     case VDCTRL_SET_FRAMEDROP:
1184         ctx->framedrop_flags = *(int *)arg;
1185         return CONTROL_TRUE;
1186     case VDCTRL_GET_BFRAMES: {
1187         AVCodecContext *avctx = ctx->avctx;
1188         if (!avctx)
1189             break;
1190         if (ctx->use_hwdec && strcmp(ctx->hwdec.method_name, "mmal") == 0)
1191             break; // MMAL has arbitrary buffering, thus unknown
1192         *(int *)arg = avctx->has_b_frames;
1193         return CONTROL_TRUE;
1194     }
1195     case VDCTRL_GET_HWDEC: {
1196         *(char **)arg = ctx->use_hwdec ? ctx->hwdec.method_name : NULL;
1197         return CONTROL_TRUE;
1198     }
1199     case VDCTRL_FORCE_HWDEC_FALLBACK:
1200         if (ctx->use_hwdec) {
1201             force_fallback(vd);
1202             return ctx->avctx ? CONTROL_OK : CONTROL_ERROR;
1203         }
1204         return CONTROL_FALSE;
1205     case VDCTRL_REINIT:
1206         reinit(vd);
1207         return CONTROL_TRUE;
1208     }
1209     return CONTROL_UNKNOWN;
1210 }
1211 
process(struct mp_filter * vd)1212 static void process(struct mp_filter *vd)
1213 {
1214     vd_ffmpeg_ctx *ctx = vd->priv;
1215 
1216     lavc_process(vd, &ctx->state, send_packet, receive_frame);
1217 }
1218 
reset(struct mp_filter * vd)1219 static void reset(struct mp_filter *vd)
1220 {
1221     vd_ffmpeg_ctx *ctx = vd->priv;
1222 
1223     flush_all(vd);
1224 
1225     ctx->state = (struct lavc_state){0};
1226     ctx->framedrop_flags = 0;
1227 }
1228 
destroy(struct mp_filter * vd)1229 static void destroy(struct mp_filter *vd)
1230 {
1231     vd_ffmpeg_ctx *ctx = vd->priv;
1232 
1233     uninit_avctx(vd);
1234 
1235     pthread_mutex_destroy(&ctx->dr_lock);
1236 }
1237 
1238 static const struct mp_filter_info vd_lavc_filter = {
1239     .name = "vd_lavc",
1240     .priv_size = sizeof(vd_ffmpeg_ctx),
1241     .process = process,
1242     .reset = reset,
1243     .destroy = destroy,
1244 };
1245 
create(struct mp_filter * parent,struct mp_codec_params * codec,const char * decoder)1246 static struct mp_decoder *create(struct mp_filter *parent,
1247                                  struct mp_codec_params *codec,
1248                                  const char *decoder)
1249 {
1250     struct mp_filter *vd = mp_filter_create(parent, &vd_lavc_filter);
1251     if (!vd)
1252         return NULL;
1253 
1254     mp_filter_add_pin(vd, MP_PIN_IN, "in");
1255     mp_filter_add_pin(vd, MP_PIN_OUT, "out");
1256 
1257     vd->log = mp_log_new(vd, parent->log, NULL);
1258 
1259     vd_ffmpeg_ctx *ctx = vd->priv;
1260     ctx->log = vd->log;
1261     ctx->opts_cache = m_config_cache_alloc(ctx, vd->global, &vd_lavc_conf);
1262     ctx->opts = ctx->opts_cache->opts;
1263     ctx->codec = codec;
1264     ctx->decoder = talloc_strdup(ctx, decoder);
1265     ctx->hwdec_swpool = mp_image_pool_new(ctx);
1266     ctx->dr_pool = mp_image_pool_new(ctx);
1267 
1268     ctx->public.f = vd;
1269     ctx->public.control = control;
1270 
1271     pthread_mutex_init(&ctx->dr_lock, NULL);
1272 
1273     // hwdec/DR
1274     struct mp_stream_info *info = mp_filter_find_stream_info(vd);
1275     if (info) {
1276         ctx->hwdec_devs = info->hwdec_devs;
1277         ctx->vo = info->dr_vo;
1278     }
1279 
1280     reinit(vd);
1281 
1282     if (!ctx->avctx) {
1283         talloc_free(vd);
1284         return NULL;
1285     }
1286     return &ctx->public;
1287 }
1288 
add_decoders(struct mp_decoder_list * list)1289 static void add_decoders(struct mp_decoder_list *list)
1290 {
1291     mp_add_lavc_decoders(list, AVMEDIA_TYPE_VIDEO);
1292 }
1293 
1294 const struct mp_decoder_fns vd_lavc = {
1295     .create = create,
1296     .add_decoders = add_decoders,
1297 };
1298