Ticket #10774: ffmpeg-4.4.4-libvmaf-2.0.0.patch

File ffmpeg-4.4.4-libvmaf-2.0.0.patch, 34.1 KB (added by Ștefan Talpalaru, 3 years ago)

ffmpeg-4.4.4-libvmaf-2.0.0.patch

  • ffmpeg-4.4.4

    adapted from: https://ffmpeg.org/pipermail/ffmpeg-devel/attachments/20220119/70fd3e3e/attachment.obj
    
    diff -ur ffmpeg-4.4.4.orig/configure ffmpeg-4.4.4/configure
    old new  
    36633663vaguedenoiser_filter_deps="gpl"
    36643664vidstabdetect_filter_deps="libvidstab"
    36653665vidstabtransform_filter_deps="libvidstab"
    3666 libvmaf_filter_deps="libvmaf pthreads"
     3666libvmaf_filter_deps="libvmaf"
    36673667zmq_filter_deps="libzmq"
    36683668zoompan_filter_deps="swscale"
    36693669zscale_filter_deps="libzimg const_nan"
    … …  
    64486448enabled libuavs3d         && require_pkg_config libuavs3d "uavs3d >= 1.1.41" uavs3d.h uavs3d_decode
    64496449enabled libv4l2           && require_pkg_config libv4l2 libv4l2 libv4l2.h v4l2_ioctl
    64506450enabled libvidstab        && require_pkg_config libvidstab "vidstab >= 0.98" vid.stab/libvidstab.h vsMotionDetectInit
    6451 enabled libvmaf           && require_pkg_config libvmaf "libvmaf >= 1.5.2" libvmaf.h compute_vmaf
     6451enabled libvmaf           && require_pkg_config libvmaf "libvmaf >= 2.0.0" libvmaf.h vmaf_init
    64526452enabled libvo_amrwbenc    && require libvo_amrwbenc vo-amrwbenc/enc_if.h E_IF_init -lvo-amrwbenc
    64536453enabled libvorbis         && require_pkg_config libvorbis vorbis vorbis/codec.h vorbis_info_init &&
    64546454                             require_pkg_config libvorbisenc vorbisenc vorbis/vorbisenc.h vorbis_encode_init
  • doc/filters.texi

    diff -ur ffmpeg-4.4.4.orig/doc/filters.texi ffmpeg-4.4.4/doc/filters.texi
    old new  
    1386713867
    1386813868@section libvmaf
    1386913869
    13870 Obtain the VMAF (Video Multi-Method Assessment Fusion)
    13871 score between two input videos.
     13870Calculate the VMAF (Video Multi-Method Assessment Fusion) score for a
     13871reference/distorted pair of input videos.
     13872
     13873The first input is the distorted video, and the second input is the reference video.
    1387213874
    1387313875The obtained VMAF score is printed through the logging system.
    1387413876
    1387513877It requires Netflix's vmaf library (libvmaf) as a pre-requisite.
    1387613878After installing the library it can be enabled using:
    1387713879@code{./configure --enable-libvmaf}.
    13878 If no model path is specified it uses the default model: @code{vmaf_v0.6.1.pkl}.
    1387913880
    1388013881The filter has following options:
    1388113882
    1388213883@table @option
    13883 @item model_path
    13884 Set the model path which is to be used for SVM.
    13885 Default value: @code{"/usr/local/share/model/vmaf_v0.6.1.pkl"}
     13884@item model
     13885A `|` delimited list of vmaf models. Each model can be configured with a number of parameters.
     13886Default value: @code{"version=vmaf_v0.6.1"}
    1388613887
    13887 @item log_path
    13888 Set the file path to be used to store logs.
    13889 
    13890 @item log_fmt
    13891 Set the format of the log file (csv, json or xml).
     13888@item model_path
     13889Deprecated, use model='path=...'.
    1389213890
    1389313891@item enable_transform
    13894 This option can enable/disable the @code{score_transform} applied to the final predicted VMAF score,
    13895 if you have specified score_transform option in the input parameter file passed to @code{run_vmaf_training.py}
    13896 Default value: @code{false}
     13892Deprecated, use model='enable_transform=true'.
    1389713893
    1389813894@item phone_model
    13899 Invokes the phone model which will generate VMAF scores higher than in the
    13900 regular model, which is more suitable for laptop, TV, etc. viewing conditions.
    13901 Default value: @code{false}
     13895Deprecated, use model='enable_transform=true'.
     13896
     13897@item enable_conf_interval
     13898Deprecated, use model='enable_conf_interval=true'.
     13899
     13900@item feature
     13901A `|` delimited list of features. Each feature can be configured with a number of parameters.
    1390213902
    1390313903@item psnr
    13904 Enables computing psnr along with vmaf.
    13905 Default value: @code{false}
     13904Deprecated, use feature='name=psnr'.
    1390613905
    1390713906@item ssim
    13908 Enables computing ssim along with vmaf.
    13909 Default value: @code{false}
     13907Deprecated, use feature='name=ssim'.
    1391013908
    1391113909@item ms_ssim
    13912 Enables computing ms_ssim along with vmaf.
    13913 Default value: @code{false}
     13910Deprecated, use feature='name=ms_ssim'.
     13911
     13912@item log_path
     13913Set the file path to be used to store log files.
    1391413914
    13915 @item pool
    13916 Set the pool method to be used for computing vmaf.
    13917 Options are @code{min}, @code{harmonic_mean} or @code{mean} (default).
     13915@item log_fmt
     13916Set the format of the log file (xml, json, csv, or sub).
    1391813917
    1391913918@item n_threads
    13920 Set number of threads to be used when computing vmaf.
    13921 Default value: @code{0}, which makes use of all available logical processors.
     13919Set number of threads to be used when initializing libvmaf.
     13920Default value: @code{0}, no threads.
    1392213921
    1392313922@item n_subsample
    13924 Set interval for frame subsampling used when computing vmaf.
    13925 Default value: @code{1}
    13926 
    13927 @item enable_conf_interval
    13928 Enables confidence interval.
    13929 Default value: @code{false}
     13923Set frame subsampling interval to be used.
    1393013924@end table
    1393113925
    1393213926This filter also supports the @ref{framesync} options.
    … …  
    1393413928@subsection Examples
    1393513929@itemize
    1393613930@item
    13937 On the below examples the input file @file{main.mpg} being processed is
    13938 compared with the reference file @file{ref.mpg}.
     13931In the examples below, a distorted video @file{distorted.mpg} is
     13932compared with a reference file @file{reference.mpg}.
     13933
     13934@item
     13935Basic usage:
     13936@example
     13937ffmpeg -i distorted.mpg -i reference.mpg -lavfi libvmaf=log_path=output.xml -f null -
     13938@end example
     13939
     13940@item
     13941Example with multiple models:
    1393913942
    1394013943@example
    13941 ffmpeg -i main.mpg -i ref.mpg -lavfi libvmaf -f null -
     13944ffmpeg -i distorted.mpg -i reference.mpg -lavfi libvmaf='model=version=vmaf_v0.6.1\\:name=vmaf|version=vmaf_v0.6.1neg\\:name=vmaf_neg' -f null -
    1394213945@end example
    1394313946
    1394413947@item
    13945 Example with options:
     13948Example with multiple addtional features:
    1394613949@example
    13947 ffmpeg -i main.mpg -i ref.mpg -lavfi libvmaf="psnr=1:log_fmt=json" -f null -
     13950ffmpeg -i distorted.mpg -i reference.mpg -lavfi libvmaf='feature=name=psnr|name=ciede' -f null -
    1394813951@end example
    1394913952
    1395013953@item
    1395113954Example with options and different containers:
    1395213955@example
    13953 ffmpeg -i main.mpg -i ref.mkv -lavfi "[0:v]settb=AVTB,setpts=PTS-STARTPTS[main];[1:v]settb=AVTB,setpts=PTS-STARTPTS[ref];[main][ref]libvmaf=psnr=1:log_fmt=json" -f null -
     13956ffmpeg -i distorted.mpg -i reference.mkv -lavfi "[0:v]settb=AVTB,setpts=PTS-STARTPTS[main];[1:v]settb=AVTB,setpts=PTS-STARTPTS[ref];[main][ref]libvmaf=log_fmt=json:log_path=output.json" -f null -
    1395413957@end example
    1395513958@end itemize
    1395613959
  • libavfilter/vf_libvmaf.c

    diff -ur ffmpeg-4.4.4.orig/libavfilter/vf_libvmaf.c ffmpeg-4.4.4/libavfilter/vf_libvmaf.c
    old new  
    2424 * Calculate the VMAF between two input videos.
    2525 */
    2626
    27 #include <pthread.h>
    2827#include <libvmaf.h>
     28
    2929#include "libavutil/avstring.h"
    3030#include "libavutil/opt.h"
    3131#include "libavutil/pixdesc.h"
    … …  
    3939typedef struct LIBVMAFContext {
    4040    const AVClass *class;
    4141    FFFrameSync fs;
    42     const AVPixFmtDescriptor *desc;
    43     int width;
    44     int height;
    45     double vmaf_score;
    46     int vmaf_thread_created;
    47     pthread_t vmaf_thread;
    48     pthread_mutex_t lock;
    49     pthread_cond_t cond;
    50     int eof;
    51     AVFrame *gmain;
    52     AVFrame *gref;
    53     int frame_set;
    5442    char *model_path;
    5543    char *log_path;
    5644    char *log_fmt;
    57     int disable_clip;
    58     int disable_avx;
    5945    int enable_transform;
    6046    int phone_model;
    6147    int psnr;
    … …  
    6551    int n_threads;
    6652    int n_subsample;
    6753    int enable_conf_interval;
    68     int error;
     54    char *model_cfg;
     55    char *feature_cfg;
     56    VmafContext *vmaf;
     57    VmafModel **model;
     58    unsigned model_cnt;
     59    unsigned frame_cnt;
     60    unsigned bpc;
    6961} LIBVMAFContext;
    7062
    7163#define OFFSET(x) offsetof(LIBVMAFContext, x)
    7264#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
    7365
    7466static const AVOption libvmaf_options[] = {
    75     {"model_path",  "Set the model to be used for computing vmaf.",                     OFFSET(model_path), AV_OPT_TYPE_STRING, {.str="/usr/share/vmaf/model/vmaf_v0.6.1.json"}, 0, 1, FLAGS},
    76     {"log_path",  "Set the file path to be used to store logs.",                        OFFSET(log_path), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS},
    77     {"log_fmt",  "Set the format of the log (csv, json or xml).",                       OFFSET(log_fmt), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS},
    78     {"enable_transform",  "Enables transform for computing vmaf.",                      OFFSET(enable_transform), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
    79     {"phone_model",  "Invokes the phone model that will generate higher VMAF scores.",  OFFSET(phone_model), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
    80     {"psnr",  "Enables computing psnr along with vmaf.",                                OFFSET(psnr), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
    81     {"ssim",  "Enables computing ssim along with vmaf.",                                OFFSET(ssim), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
    82     {"ms_ssim",  "Enables computing ms-ssim along with vmaf.",                          OFFSET(ms_ssim), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
     67    {"model_path",  "use model='path=...'.",                                            OFFSET(model_path), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     68    {"log_path",  "Set the file path to be used to write log.",                         OFFSET(log_path), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS},
     69    {"log_fmt",  "Set the format of the log (csv, json, xml, or sub).",                 OFFSET(log_fmt), AV_OPT_TYPE_STRING, {.str="xml"}, 0, 1, FLAGS},
     70    {"enable_transform",  "use model='enable_transform=true'.",                         OFFSET(enable_transform), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     71    {"phone_model",  "use model='enable_transform=true'.",                              OFFSET(phone_model), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     72    {"psnr",  "use feature='name=psnr'.",                                               OFFSET(psnr), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     73    {"ssim",  "use feature='name=ssim'.",                                               OFFSET(ssim), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     74    {"ms_ssim",  "use feature='name=ms_ssim'.",                                         OFFSET(ms_ssim), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
    8375    {"pool",  "Set the pool method to be used for computing vmaf.",                     OFFSET(pool), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS},
    8476    {"n_threads", "Set number of threads to be used when computing vmaf.",              OFFSET(n_threads), AV_OPT_TYPE_INT, {.i64=0}, 0, UINT_MAX, FLAGS},
    8577    {"n_subsample", "Set interval for frame subsampling used when computing vmaf.",     OFFSET(n_subsample), AV_OPT_TYPE_INT, {.i64=1}, 1, UINT_MAX, FLAGS},
    86     {"enable_conf_interval",  "Enables confidence interval.",                           OFFSET(enable_conf_interval), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
     78    {"enable_conf_interval",  "model='enable_conf_interval=true'.",                     OFFSET(enable_conf_interval), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS|AV_OPT_FLAG_DEPRECATED},
     79    {"model",  "Set the model to be used for computing vmaf.",                          OFFSET(model_cfg), AV_OPT_TYPE_STRING, {.str="version=vmaf_v0.6.1"}, 0, 1, FLAGS},
     80    {"feature",  "Set the feature to be used for computing vmaf.",                      OFFSET(feature_cfg), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS},
    8781    { NULL }
    8882};
    8983
    9084FRAMESYNC_DEFINE_CLASS(libvmaf, LIBVMAFContext, fs);
    9185
    92 #define read_frame_fn(type, bits)                                               \
    93     static int read_frame_##bits##bit(float *ref_data, float *main_data,        \
    94                                       float *temp_data, int stride, void *ctx)  \
    95 {                                                                               \
    96     LIBVMAFContext *s = (LIBVMAFContext *) ctx;                                 \
    97     int ret;                                                                    \
    98     \
    99     pthread_mutex_lock(&s->lock);                                               \
    100     \
    101     while (!s->frame_set && !s->eof) {                                          \
    102         pthread_cond_wait(&s->cond, &s->lock);                                  \
    103     }                                                                           \
    104     \
    105     if (s->frame_set) {                                                         \
    106         int ref_stride = s->gref->linesize[0];                                  \
    107         int main_stride = s->gmain->linesize[0];                                \
    108         \
    109         const type *ref_ptr = (const type *) s->gref->data[0];                  \
    110         const type *main_ptr = (const type *) s->gmain->data[0];                \
    111         \
    112         float *ptr = ref_data;                                                  \
    113         float factor = 1.f / (1 << (bits - 8));                                 \
    114         \
    115         int h = s->height;                                                      \
    116         int w = s->width;                                                       \
    117         \
    118         int i,j;                                                                \
    119         \
    120         for (i = 0; i < h; i++) {                                               \
    121             for ( j = 0; j < w; j++) {                                          \
    122                 ptr[j] = ref_ptr[j] * factor;                                   \
    123             }                                                                   \
    124             ref_ptr += ref_stride / sizeof(*ref_ptr);                           \
    125             ptr += stride / sizeof(*ptr);                                       \
    126         }                                                                       \
    127         \
    128         ptr = main_data;                                                        \
    129         \
    130         for (i = 0; i < h; i++) {                                               \
    131             for (j = 0; j < w; j++) {                                           \
    132                 ptr[j] = main_ptr[j] * factor;                                  \
    133             }                                                                   \
    134             main_ptr += main_stride / sizeof(*main_ptr);                        \
    135             ptr += stride / sizeof(*ptr);                                       \
    136         }                                                                       \
    137     }                                                                           \
    138     \
    139     ret = !s->frame_set;                                                        \
    140     \
    141     av_frame_unref(s->gref);                                                    \
    142     av_frame_unref(s->gmain);                                                   \
    143     s->frame_set = 0;                                                           \
    144     \
    145     pthread_cond_signal(&s->cond);                                              \
    146     pthread_mutex_unlock(&s->lock);                                             \
    147     \
    148     if (ret) {                                                                  \
    149         return 2;                                                               \
    150     }                                                                           \
    151     \
    152     return 0;                                                                   \
    153 }
    154 
    155 read_frame_fn(uint8_t, 8);
    156 read_frame_fn(uint16_t, 10);
    157 
    158 static void compute_vmaf_score(LIBVMAFContext *s)
    159 {
    160     int (*read_frame)(float *ref_data, float *main_data, float *temp_data,
    161                       int stride, void *ctx);
    162     char *format;
    163 
    164     if (s->desc->comp[0].depth <= 8) {
    165         read_frame = read_frame_8bit;
    166     } else {
    167         read_frame = read_frame_10bit;
     86static enum VmafPixelFormat pix_fmt_map(enum AVPixelFormat av_pix_fmt)
     87{
     88    switch (av_pix_fmt) {
     89    case AV_PIX_FMT_YUV420P:
     90    case AV_PIX_FMT_YUV420P10LE:
     91    case AV_PIX_FMT_YUV420P12LE:
     92    case AV_PIX_FMT_YUV420P16LE:
     93        return VMAF_PIX_FMT_YUV420P;
     94    case AV_PIX_FMT_YUV422P:
     95    case AV_PIX_FMT_YUV422P10LE:
     96    case AV_PIX_FMT_YUV422P12LE:
     97    case AV_PIX_FMT_YUV422P16LE:
     98        return VMAF_PIX_FMT_YUV422P;
     99    case AV_PIX_FMT_YUV444P:
     100    case AV_PIX_FMT_YUV444P10LE:
     101    case AV_PIX_FMT_YUV444P12LE:
     102    case AV_PIX_FMT_YUV444P16LE:
     103        return VMAF_PIX_FMT_YUV444P;
     104    default:
     105        return VMAF_PIX_FMT_UNKNOWN;
    168106    }
    169 
    170     format = (char *) s->desc->name;
    171 
    172     s->error = compute_vmaf(&s->vmaf_score, format, s->width, s->height,
    173                             read_frame, s, s->model_path, s->log_path,
    174                             s->log_fmt, 0, 0, s->enable_transform,
    175                             s->phone_model, s->psnr, s->ssim,
    176                             s->ms_ssim, s->pool,
    177                             s->n_threads, s->n_subsample, s->enable_conf_interval);
    178107}
    179108
    180 static void *call_vmaf(void *ctx)
     109static int copy_picture_data(AVFrame *src, VmafPicture *dst, unsigned bpc)
    181110{
    182     LIBVMAFContext *s = (LIBVMAFContext *) ctx;
    183     compute_vmaf_score(s);
    184     if (!s->error) {
    185         av_log(ctx, AV_LOG_INFO, "VMAF score: %f\n",s->vmaf_score);
    186     } else {
    187         pthread_mutex_lock(&s->lock);
    188         pthread_cond_signal(&s->cond);
    189         pthread_mutex_unlock(&s->lock);
     111    int err = vmaf_picture_alloc(dst, pix_fmt_map(src->format), bpc,
     112                                 src->width, src->height);
     113    if (err)
     114        return AVERROR(ENOMEM);
     115
     116    for (unsigned i = 0; i < 3; i++) {
     117        uint8_t *src_data = src->data[i];
     118        uint8_t *dst_data = dst->data[i];
     119        for (unsigned j = 0; j < dst->h[i]; j++) {
     120            memcpy(dst_data, src_data, sizeof(*dst_data) * dst->w[i]);
     121            src_data += src->linesize[i];
     122            dst_data += dst->stride[i];
     123        }
    190124    }
    191     pthread_exit(NULL);
    192     return NULL;
     125
     126    return 0;
    193127}
    194128
    195129static int do_vmaf(FFFrameSync *fs)
    196130{
    197131    AVFilterContext *ctx = fs->parent;
    198132    LIBVMAFContext *s = ctx->priv;
    199     AVFrame *master, *ref;
    200     int ret;
     133    VmafPicture pic_ref, pic_dist;
     134    AVFrame *ref, *dist;
     135    int err = 0;
    201136
    202     ret = ff_framesync_dualinput_get(fs, &master, &ref);
     137    int ret = ff_framesync_dualinput_get(fs, &dist, &ref);
    203138    if (ret < 0)
    204139        return ret;
    205     if (!ref)
    206         return ff_filter_frame(ctx->outputs[0], master);
     140    if (ctx->is_disabled || !ref)
     141        return ff_filter_frame(ctx->outputs[0], dist);
     142
     143    err = copy_picture_data(ref, &pic_ref, s->bpc);
     144    if (err) {
     145        av_log(s, AV_LOG_ERROR, "problem during vmaf_picture_alloc.\n");
     146        return AVERROR(ENOMEM);
     147    }
     148
     149    err = copy_picture_data(dist, &pic_dist, s->bpc);
     150    if (err) {
     151        av_log(s, AV_LOG_ERROR, "problem during vmaf_picture_alloc.\n");
     152        vmaf_picture_unref(&pic_ref);
     153        return AVERROR(ENOMEM);
     154    }
     155
     156    err = vmaf_read_pictures(s->vmaf, &pic_ref, &pic_dist, s->frame_cnt++);
     157    if (err) {
     158        av_log(s, AV_LOG_ERROR, "problem during vmaf_read_pictures.\n");
     159        return AVERROR(EINVAL);
     160    }
     161
     162    return ff_filter_frame(ctx->outputs[0], dist);
     163}
     164
     165static AVDictionary **delimited_dict_parse(char *str, unsigned *cnt)
     166{
     167    AVDictionary **dict = NULL;
     168    char *str_copy = NULL;
     169    char *saveptr = NULL;
     170    unsigned cnt2;
     171    int err = 0;
     172
     173    if (!str)
     174        return NULL;
     175
     176    cnt2 = 1;
     177    for (char *p = str; *p; p++) {
     178        if (*p == '|')
     179            cnt2++;
     180    }
     181
     182    dict = av_calloc(cnt2, sizeof(*dict));
     183    if (!dict)
     184        goto fail;
     185
     186    str_copy = av_strdup(str);
     187    if (!str_copy)
     188        goto fail;
     189
     190    *cnt = 0;
     191    for (unsigned i = 0; i < cnt2; i++) {
     192        char *s = av_strtok(i == 0 ? str_copy : NULL, "|", &saveptr);
     193        if (!s)
     194            continue;
     195        err = av_dict_parse_string(&dict[(*cnt)++], s, "=", ":", 0);
     196        if (err)
     197            goto fail;
     198    }
     199
     200    av_free(str_copy);
     201    return dict;
     202
     203fail:
     204    if (dict) {
     205        for (unsigned i = 0; i < *cnt; i++) {
     206            if (dict[i])
     207                av_dict_free(&dict[i]);
     208        }
     209        av_free(dict);
     210    }
     211
     212    av_free(str_copy);
     213    *cnt = 0;
     214    return NULL;
     215}
     216
     217static int parse_features(AVFilterContext *ctx)
     218{
     219    LIBVMAFContext *s = ctx->priv;
     220    AVDictionary **dict = NULL;
     221    unsigned dict_cnt;
     222    int err = 0;
    207223
    208     pthread_mutex_lock(&s->lock);
     224    if (!s->feature_cfg)
     225        return 0;
    209226
    210     while (s->frame_set && !s->error) {
    211         pthread_cond_wait(&s->cond, &s->lock);
     227    dict = delimited_dict_parse(s->feature_cfg, &dict_cnt);
     228    if (!dict) {
     229        av_log(ctx, AV_LOG_ERROR,
     230               "could not parse feature config: %s\n", s->feature_cfg);
     231        return AVERROR(EINVAL);
     232    }
     233
     234    for (unsigned i = 0; i < dict_cnt; i++) {
     235        char *feature_name = NULL;
     236        VmafFeatureDictionary *feature_opts_dict = NULL;
     237        AVDictionaryEntry *e = NULL;
     238
     239        while (e = av_dict_get(dict[i], "", e, AV_DICT_IGNORE_SUFFIX)) {
     240            if (av_stristr(e->key, "name")) {
     241                feature_name = e->value;
     242                continue;
     243            }
     244
     245            err = vmaf_feature_dictionary_set(&feature_opts_dict, e->key,
     246                                              e->value);
     247            if (err) {
     248                av_log(ctx, AV_LOG_ERROR,
     249                       "could not set feature option: %s.%s=%s\n",
     250                       feature_name, e->key, e->value);
     251                goto exit;
     252            }
     253        }
     254
     255        err = vmaf_use_feature(s->vmaf, feature_name, feature_opts_dict);
     256        if (err) {
     257            av_log(ctx, AV_LOG_ERROR,
     258                   "problem during vmaf_use_feature: %s\n", feature_name);
     259            goto exit;
     260        }
    212261    }
    213262
    214     if (s->error) {
     263exit:
     264    for (unsigned i = 0; i < dict_cnt; i++) {
     265        if (dict[i])
     266            av_dict_free(&dict[i]);
     267    }
     268    av_free(dict);
     269    return err;
     270}
     271
     272static int parse_models(AVFilterContext *ctx)
     273{
     274    LIBVMAFContext *s = ctx->priv;
     275    AVDictionary **dict;
     276    unsigned dict_cnt;
     277    int err = 0;
     278
     279    if (!s->model_cfg) return 0;
     280
     281    dict_cnt = 0;
     282    dict = delimited_dict_parse(s->model_cfg, &dict_cnt);
     283    if (!dict) {
    215284        av_log(ctx, AV_LOG_ERROR,
    216                "libvmaf encountered an error, check log for details\n");
    217         pthread_mutex_unlock(&s->lock);
     285               "could not parse model config: %s\n", s->model_cfg);
    218286        return AVERROR(EINVAL);
    219287    }
    220288
    221     av_frame_ref(s->gref, ref);
    222     av_frame_ref(s->gmain, master);
     289    s->model_cnt = dict_cnt;
     290    s->model = av_calloc(s->model_cnt, sizeof(*s->model));
     291    if (!s->model)
     292        return AVERROR(ENOMEM);
    223293
    224     s->frame_set = 1;
     294    for (unsigned i = 0; i < dict_cnt; i++) {
     295        VmafModelConfig model_cfg = { 0 };
     296        AVDictionaryEntry *e = NULL;
     297        char *version = NULL;
     298        char  *path = NULL;
     299
     300        while (e = av_dict_get(dict[i], "", e, AV_DICT_IGNORE_SUFFIX)) {
     301            if (av_stristr(e->key, "disable_clip")) {
     302                model_cfg.flags |= av_stristr(e->value, "true") ?
     303                    VMAF_MODEL_FLAG_DISABLE_CLIP : 0;
     304                continue;
     305            }
     306
     307            if (av_stristr(e->key, "enable_transform")) {
     308                model_cfg.flags |= av_stristr(e->value, "true") ?
     309                    VMAF_MODEL_FLAG_ENABLE_TRANSFORM : 0;
     310                continue;
     311            }
     312
     313            if (av_stristr(e->key, "name")) {
     314                model_cfg.name = e->value;
     315                continue;
     316            }
     317
     318            if (av_stristr(e->key, "version")) {
     319                version = e->value;
     320                continue;
     321            }
     322
     323            if (av_stristr(e->key, "path")) {
     324                path = e->value;
     325                continue;
     326            }
     327        }
     328
     329        if (version) {
     330            err = vmaf_model_load(&s->model[i], &model_cfg, version);
     331            if (err) {
     332                av_log(ctx, AV_LOG_ERROR,
     333                       "could not load libvmaf model with version: %s\n",
     334                       version);
     335                goto exit;
     336            }
     337        }
     338
     339        if (path && !s->model[i]) {
     340            err = vmaf_model_load_from_path(&s->model[i], &model_cfg, path);
     341            if (err) {
     342                av_log(ctx, AV_LOG_ERROR,
     343                       "could not load libvmaf model with path: %s\n",
     344                       path);
     345                goto exit;
     346            }
     347        }
     348
     349        if (!s->model[i]) {
     350            av_log(ctx, AV_LOG_ERROR,
     351                   "could not load libvmaf model with config: %s\n",
     352                   s->model_cfg);
     353            goto exit;
     354        }
     355
     356        while (e = av_dict_get(dict[i], "", e, AV_DICT_IGNORE_SUFFIX)) {
     357            VmafFeatureDictionary *feature_opts_dict = NULL;
     358            char *feature_opt = NULL;
     359
     360            char *feature_name = av_strtok(e->key, ".", &feature_opt);
     361            if (!feature_opt)
     362                continue;
     363
     364            err = vmaf_feature_dictionary_set(&feature_opts_dict,
     365                                              feature_opt, e->value);
     366            if (err) {
     367                av_log(ctx, AV_LOG_ERROR,
     368                       "could not set feature option: %s.%s=%s\n",
     369                       feature_name, feature_opt, e->value);
     370                err = AVERROR(EINVAL);
     371                goto exit;
     372            }
     373
     374            err = vmaf_model_feature_overload(s->model[i], feature_name,
     375                                              feature_opts_dict);
     376            if (err) {
     377                av_log(ctx, AV_LOG_ERROR,
     378                       "could not overload feature: %s\n", feature_name);
     379                err = AVERROR(EINVAL);
     380                goto exit;
     381            }
     382        }
     383    }
    225384
    226     pthread_cond_signal(&s->cond);
    227     pthread_mutex_unlock(&s->lock);
     385    for (unsigned i = 0; i < s->model_cnt; i++) {
     386        err = vmaf_use_features_from_model(s->vmaf, s->model[i]);
     387        if (err) {
     388            av_log(ctx, AV_LOG_ERROR,
     389                   "problem during vmaf_use_features_from_model\n");
     390            err = AVERROR(EINVAL);
     391            goto exit;
     392        }
     393    }
    228394
    229     return ff_filter_frame(ctx->outputs[0], master);
     395exit:
     396    for (unsigned i = 0; i < dict_cnt; i++) {
     397        if (dict[i])
     398            av_dict_free(&dict[i]);
     399    }
     400    av_free(dict);
     401    return err;
     402}
     403
     404static enum VmafLogLevel log_level_map(int log_level)
     405{
     406    switch (log_level) {
     407    case AV_LOG_QUIET:
     408        return VMAF_LOG_LEVEL_NONE;
     409    case AV_LOG_ERROR:
     410        return VMAF_LOG_LEVEL_ERROR;
     411    case AV_LOG_WARNING:
     412        return VMAF_LOG_LEVEL_WARNING;
     413    case AV_LOG_INFO:
     414        return VMAF_LOG_LEVEL_INFO;
     415    case AV_LOG_DEBUG:
     416        return VMAF_LOG_LEVEL_DEBUG;
     417    default:
     418        return VMAF_LOG_LEVEL_INFO;
     419    }
     420}
     421
     422static int parse_deprecated_options(AVFilterContext *ctx)
     423{
     424    LIBVMAFContext *s = ctx->priv;
     425    VmafModel *model = NULL;
     426    VmafModelCollection *model_collection = NULL;
     427    enum VmafModelFlags flags = VMAF_MODEL_FLAGS_DEFAULT;
     428    int err = 0;
     429
     430    VmafModelConfig model_cfg = {
     431        .name = "vmaf",
     432        .flags = flags,
     433    };
     434
     435    if (s->enable_transform || s->phone_model)
     436        flags |= VMAF_MODEL_FLAG_ENABLE_TRANSFORM;
     437
     438    if (!s->model_path)
     439        goto extra_metrics_only;
     440
     441    if (s->enable_conf_interval) {
     442        err = vmaf_model_collection_load_from_path(&model, &model_collection,
     443                                                   &model_cfg, s->model_path);
     444        if (err) {
     445            av_log(ctx, AV_LOG_ERROR,
     446                   "problem loading model file: %s\n", s->model_path);
     447            goto exit;
     448        }
     449
     450        err = vmaf_use_features_from_model_collection(s->vmaf, model_collection);
     451        if (err) {
     452            av_log(ctx, AV_LOG_ERROR,
     453                   "problem loading feature extractors from model file: %s\n",
     454                   s->model_path);
     455            goto exit;
     456        }
     457    } else {
     458        err = vmaf_model_load_from_path(&model, &model_cfg, s->model_path);
     459        if (err) {
     460                av_log(ctx, AV_LOG_ERROR,
     461                      "problem loading model file: %s\n", s->model_path);
     462            goto exit;
     463        }
     464        err = vmaf_use_features_from_model(s->vmaf, model);
     465        if (err) {
     466            av_log(ctx, AV_LOG_ERROR,
     467                   "problem loading feature extractors from model file: %s\n",
     468                   s->model_path);
     469            goto exit;
     470        }
     471    }
     472
     473extra_metrics_only:
     474    if (s->psnr) {
     475        VmafFeatureDictionary *d = NULL;
     476        vmaf_feature_dictionary_set(&d, "enable_chroma", "false");
     477
     478        err = vmaf_use_feature(s->vmaf, "psnr", d);
     479        if (err) {
     480            av_log(ctx, AV_LOG_ERROR,
     481                   "problem loading feature extractor: psnr\n");
     482            goto exit;
     483        }
     484    }
     485
     486    if (s->ssim) {
     487        err = vmaf_use_feature(s->vmaf, "float_ssim", NULL);
     488        if (err) {
     489            av_log(ctx, AV_LOG_ERROR,
     490                   "problem loading feature extractor: ssim\n");
     491            goto exit;
     492        }
     493    }
     494
     495    if (s->ms_ssim) {
     496        err = vmaf_use_feature(s->vmaf, "float_ms_ssim", NULL);
     497        if (err) {
     498            av_log(ctx, AV_LOG_ERROR,
     499                   "problem loading feature extractor: ms_ssim\n");
     500            goto exit;
     501        }
     502    }
     503
     504exit:
     505    return err;
    230506}
    231507
    232508static av_cold int init(AVFilterContext *ctx)
    233509{
    234510    LIBVMAFContext *s = ctx->priv;
     511    int err = 0;
    235512
    236     s->gref = av_frame_alloc();
    237     s->gmain = av_frame_alloc();
    238     if (!s->gref || !s->gmain)
    239         return AVERROR(ENOMEM);
     513    VmafConfiguration cfg = {
     514        .log_level = log_level_map(av_log_get_level()),
     515        .n_subsample = s->n_subsample,
     516        .n_threads = s->n_threads,
     517    };
    240518
    241     s->error = 0;
     519    err = vmaf_init(&s->vmaf, cfg);
     520    if (err)
     521        return AVERROR(EINVAL);
    242522
    243     s->vmaf_thread_created = 0;
    244     pthread_mutex_init(&s->lock, NULL);
    245     pthread_cond_init (&s->cond, NULL);
     523    err = parse_deprecated_options(ctx);
     524    if (err)
     525        return err;
     526
     527    err = parse_models(ctx);
     528    if (err)
     529        return err;
     530
     531    err = parse_features(ctx);
     532    if (err)
     533        return err;
    246534
    247535    s->fs.on_event = do_vmaf;
    248536    return 0;
    … …  
    265553
    266554static int config_input_ref(AVFilterLink *inlink)
    267555{
    268     AVFilterContext *ctx  = inlink->dst;
     556    AVFilterContext *ctx = inlink->dst;
    269557    LIBVMAFContext *s = ctx->priv;
    270     int th;
     558    const AVPixFmtDescriptor *desc;
     559    int err = 0;
    271560
    272     if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
    273         ctx->inputs[0]->h != ctx->inputs[1]->h) {
    274         av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
    275         return AVERROR(EINVAL);
     561    if (ctx->inputs[0]->w != ctx->inputs[1]->w) {
     562        av_log(ctx, AV_LOG_ERROR, "input width must match.\n");
     563        err |= AVERROR(EINVAL);
    276564    }
    277     if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
    278         av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
    279         return AVERROR(EINVAL);
     565
     566    if (ctx->inputs[0]->h != ctx->inputs[1]->h) {
     567        av_log(ctx, AV_LOG_ERROR, "input height must match.\n");
     568        err |= AVERROR(EINVAL);
    280569    }
    281570
    282     s->desc = av_pix_fmt_desc_get(inlink->format);
    283     s->width = ctx->inputs[0]->w;
    284     s->height = ctx->inputs[0]->h;
    285 
    286     th = pthread_create(&s->vmaf_thread, NULL, call_vmaf, (void *) s);
    287     if (th) {
    288         av_log(ctx, AV_LOG_ERROR, "Thread creation failed.\n");
    289         return AVERROR(EINVAL);
     571    if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
     572        av_log(ctx, AV_LOG_ERROR, "input pix_fmt must match.\n");
     573        err |= AVERROR(EINVAL);
    290574    }
    291     s->vmaf_thread_created = 1;
     575
     576    if (err)
     577        return err;
     578
     579    desc = av_pix_fmt_desc_get(inlink->format);
     580    s->bpc = desc->comp[0].depth;
    292581
    293582    return 0;
    294583}
    … …  
    320609    return ff_framesync_activate(&s->fs);
    321610}
    322611
     612static enum VmafOutputFormat log_fmt_map(const char *log_fmt)
     613{
     614    if (log_fmt) {
     615        if (av_stristr(log_fmt, "xml"))
     616            return VMAF_OUTPUT_FORMAT_XML;
     617        if (av_stristr(log_fmt, "json"))
     618            return VMAF_OUTPUT_FORMAT_JSON;
     619        if (av_stristr(log_fmt, "csv"))
     620            return VMAF_OUTPUT_FORMAT_CSV;
     621        if (av_stristr(log_fmt, "sub"))
     622            return VMAF_OUTPUT_FORMAT_SUB;
     623    }
     624
     625    return VMAF_OUTPUT_FORMAT_XML;
     626}
     627
     628static enum VmafPoolingMethod pool_method_map(const char *pool_method)
     629{
     630    if (pool_method) {
     631        if (av_stristr(pool_method, "min"))
     632            return VMAF_POOL_METHOD_MIN;
     633        if (av_stristr(pool_method, "mean"))
     634            return VMAF_POOL_METHOD_MEAN;
     635        if (av_stristr(pool_method, "harmonic_mean"))
     636            return VMAF_POOL_METHOD_HARMONIC_MEAN;
     637    }
     638
     639    return VMAF_POOL_METHOD_MEAN;
     640}
     641
    323642static av_cold void uninit(AVFilterContext *ctx)
    324643{
    325644    LIBVMAFContext *s = ctx->priv;
     645    int err = 0;
    326646
    327647    ff_framesync_uninit(&s->fs);
    328648
    329     pthread_mutex_lock(&s->lock);
    330     s->eof = 1;
    331     pthread_cond_signal(&s->cond);
    332     pthread_mutex_unlock(&s->lock);
    333 
    334     if (s->vmaf_thread_created)
    335     {
    336         pthread_join(s->vmaf_thread, NULL);
    337         s->vmaf_thread_created = 0;
     649    if (!s->frame_cnt)
     650        goto clean_up;
     651
     652    err = vmaf_read_pictures(s->vmaf, NULL, NULL, 0);
     653    if (err) {
     654        av_log(ctx, AV_LOG_ERROR,
     655               "problem flushing libvmaf context.\n");
     656    }
     657
     658    for (unsigned i = 0; i < s->model_cnt; i++) {
     659        double vmaf_score;
     660        err = vmaf_score_pooled(s->vmaf, s->model[i], pool_method_map(s->pool),
     661                                &vmaf_score, 0, s->frame_cnt - 1);
     662        if (err) {
     663            av_log(ctx, AV_LOG_ERROR,
     664                   "problem getting pooled vmaf score.\n");
     665        }
     666
     667        av_log(ctx, AV_LOG_INFO, "VMAF score: %f\n", vmaf_score);
    338668    }
    339669
    340     av_frame_free(&s->gref);
    341     av_frame_free(&s->gmain);
     670    if (s->vmaf) {
     671        if (s->log_path && !err)
     672            vmaf_write_output(s->vmaf, s->log_path, log_fmt_map(s->log_fmt));
     673    }
     674
     675clean_up:
     676    if (s->model) {
     677        for (unsigned i = 0; i < s->model_cnt; i++) {
     678            if (s->model[i])
     679                vmaf_model_destroy(s->model[i]);
     680        }
     681        av_free(s->model);
     682    }
    342683
    343     pthread_mutex_destroy(&s->lock);
    344     pthread_cond_destroy(&s->cond);
     684    if (s->vmaf)
     685        vmaf_close(s->vmaf);
    345686}
    346687
    347688static const AVFilterPad libvmaf_inputs[] = {