]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_vif.c
avfilter/vf_vif.c: fix build warning for [-Wmain]
[ffmpeg] / libavfilter / vf_vif.c
1 /*
2  * Copyright (c) 2017 Ronald S. Bultje <rsbultje@gmail.com>
3  * Copyright (c) 2017 Ashish Pratap Singh <ashk43712@gmail.com>
4  * Copyright (c) 2021 Paul B Mahol
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Calculate VIF between two input videos.
26  */
27
28 #include <float.h>
29
30 #include "libavutil/avstring.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "avfilter.h"
34 #include "framesync.h"
35 #include "drawutils.h"
36 #include "formats.h"
37 #include "internal.h"
38 #include "vif.h"
39 #include "video.h"
40
41 typedef struct VIFContext {
42     const AVClass *class;
43     FFFrameSync fs;
44     const AVPixFmtDescriptor *desc;
45     int width;
46     int height;
47     int nb_threads;
48     float *data_buf[13];
49     float **temp;
50     float *ref_data;
51     float *main_data;
52     double vif_sum[4];
53     double vif_min[4];
54     double vif_max[4];
55     uint64_t nb_frames;
56 } VIFContext;
57
58 #define OFFSET(x) offsetof(VIFContext, x)
59
60 static const AVOption vif_options[] = {
61     { NULL }
62 };
63
64 AVFILTER_DEFINE_CLASS(vif);
65
66 static const uint8_t vif_filter1d_width1[4] = { 17, 9, 5, 3 };
67
68 static const float vif_filter1d_table[4][17] =
69 {
70     {
71         0.00745626912, 0.0142655009, 0.0250313189, 0.0402820669, 0.0594526194,
72         0.0804751068, 0.0999041125, 0.113746084, 0.118773937, 0.113746084,
73         0.0999041125, 0.0804751068, 0.0594526194, 0.0402820669, 0.0250313189,
74         0.0142655009, 0.00745626912
75     },
76     {
77         0.0189780835, 0.0558981746, 0.120920904, 0.192116052, 0.224173605,
78         0.192116052, 0.120920904, 0.0558981746, 0.0189780835
79     },
80     {
81         0.054488685, 0.244201347, 0.402619958, 0.244201347, 0.054488685
82     },
83     {
84         0.166378498, 0.667243004, 0.166378498
85     }
86 };
87
88 typedef struct ThreadData {
89     const float *filter;
90     const float *src;
91     float *dst;
92     int w, h;
93     int src_stride;
94     int dst_stride;
95     int filter_width;
96     float **temp;
97 } ThreadData;
98
99 static void vif_dec2(const float *src, float *dst, int w, int h,
100                      int src_stride, int dst_stride)
101 {
102     const int dst_px_stride = dst_stride / 2;
103
104     for (int i = 0; i < h / 2; i++) {
105         for (int j = 0; j < w / 2; j++)
106             dst[i * dst_px_stride + j] = src[(i * 2) * src_stride + (j * 2)];
107     }
108 }
109
110 static void vif_statistic(const float *mu1_sq, const float *mu2_sq,
111                           const float *mu1_mu2, const float *xx_filt,
112                           const float *yy_filt, const float *xy_filt,
113                           float *num, float *den, int w, int h)
114 {
115     static const float sigma_nsq = 2;
116     static const float sigma_max_inv = 4.0/(255.0*255.0);
117
118     float mu1_sq_val, mu2_sq_val, mu1_mu2_val, xx_filt_val, yy_filt_val, xy_filt_val;
119     float sigma1_sq, sigma2_sq, sigma12, g, sv_sq, eps = 1.0e-10f;
120     float gain_limit = 100.f;
121     float num_val, den_val;
122     float accum_num = 0.0f;
123     float accum_den = 0.0f;
124
125     for (int i = 0; i < h; i++) {
126         float accum_inner_num = 0.f;
127         float accum_inner_den = 0.f;
128
129         for (int j = 0; j < w; j++) {
130             mu1_sq_val  = mu1_sq[i * w + j];
131             mu2_sq_val  = mu2_sq[i * w + j];
132             mu1_mu2_val = mu1_mu2[i * w + j];
133             xx_filt_val = xx_filt[i * w + j];
134             yy_filt_val = yy_filt[i * w + j];
135             xy_filt_val = xy_filt[i * w + j];
136
137             sigma1_sq = xx_filt_val - mu1_sq_val;
138             sigma2_sq = yy_filt_val - mu2_sq_val;
139             sigma12   = xy_filt_val - mu1_mu2_val;
140
141             sigma1_sq = FFMAX(sigma1_sq, 0.0f);
142             sigma2_sq = FFMAX(sigma2_sq, 0.0f);
143             sigma12   = FFMAX(sigma12,   0.0f);
144
145             g = sigma12 / (sigma1_sq + eps);
146             sv_sq = sigma2_sq - g * sigma12;
147
148             if (sigma1_sq < eps) {
149                 g = 0.0f;
150                 sv_sq = sigma2_sq;
151                 sigma1_sq = 0.0f;
152             }
153
154             if (sigma2_sq < eps) {
155                 g = 0.0f;
156                 sv_sq = 0.0f;
157             }
158
159             if (g < 0.0f) {
160                 sv_sq = sigma2_sq;
161                 g = 0.0f;
162             }
163             sv_sq = FFMAX(sv_sq, eps);
164
165             g = FFMIN(g, gain_limit);
166
167             num_val = log2f(1.0f + g * g * sigma1_sq / (sv_sq + sigma_nsq));
168             den_val = log2f(1.0f + sigma1_sq / sigma_nsq);
169
170             if (sigma12 < 0.0f)
171                 num_val = 0.0f;
172
173             if (sigma1_sq < sigma_nsq) {
174                 num_val = 1.0f - sigma2_sq * sigma_max_inv;
175                 den_val = 1.0f;
176             }
177
178             accum_inner_num += num_val;
179             accum_inner_den += den_val;
180         }
181
182         accum_num += accum_inner_num;
183         accum_den += accum_inner_den;
184     }
185
186     num[0] = accum_num;
187     den[0] = accum_den;
188 }
189
190 static void vif_xx_yy_xy(const float *x, const float *y, float *xx, float *yy,
191                          float *xy, int w, int h)
192 {
193     for (int i = 0; i < h; i++) {
194         for (int j = 0; j < w; j++) {
195             float xval = x[j];
196             float yval = y[j];
197             float xxval = xval * xval;
198             float yyval = yval * yval;
199             float xyval = xval * yval;
200
201             xx[j] = xxval;
202             yy[j] = yyval;
203             xy[j] = xyval;
204         }
205
206         xx += w;
207         yy += w;
208         xy += w;
209         x  += w;
210         y  += w;
211     }
212 }
213
214 static int vif_filter1d(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
215 {
216     ThreadData *td = arg;
217     const float *filter = td->filter;
218     const float *src = td->src;
219     float *dst = td->dst;
220     int w = td->w;
221     int h = td->h;
222     int src_stride = td->src_stride;
223     int dst_stride = td->dst_stride;
224     int filt_w = td->filter_width;
225     float *temp = td->temp[jobnr];
226     const int slice_start = (h * jobnr) / nb_jobs;
227     const int slice_end = (h * (jobnr+1)) / nb_jobs;
228
229     for (int i = slice_start; i < slice_end; i++) {
230         /** Vertical pass. */
231         for (int j = 0; j < w; j++) {
232             float sum = 0.f;
233
234             if (i >= filt_w / 2 && i < h - filt_w / 2 - 1) {
235                 for (int filt_i = 0; filt_i < filt_w; filt_i++) {
236                     const float filt_coeff = filter[filt_i];
237                     float img_coeff;
238                     int ii = i - filt_w / 2 + filt_i;
239
240                     img_coeff = src[ii * src_stride + j];
241                     sum += filt_coeff * img_coeff;
242                 }
243             } else {
244                 for (int filt_i = 0; filt_i < filt_w; filt_i++) {
245                     const float filt_coeff = filter[filt_i];
246                     int ii = i - filt_w / 2 + filt_i;
247                     float img_coeff;
248
249                     ii = ii < 0 ? -ii : (ii >= h ? 2 * h - ii - 1 : ii);
250
251                     img_coeff = src[ii * src_stride + j];
252                     sum += filt_coeff * img_coeff;
253                 }
254             }
255
256             temp[j] = sum;
257         }
258
259         /** Horizontal pass. */
260         for (int j = 0; j < w; j++) {
261             float sum = 0.f;
262
263             if (j >= filt_w / 2 && j < w - filt_w / 2 - 1) {
264                 for (int filt_j = 0; filt_j < filt_w; filt_j++) {
265                     const float filt_coeff = filter[filt_j];
266                     int jj = j - filt_w / 2 + filt_j;
267                     float img_coeff;
268
269                     img_coeff = temp[jj];
270                     sum += filt_coeff * img_coeff;
271                 }
272             } else {
273                 for (int filt_j = 0; filt_j < filt_w; filt_j++) {
274                     const float filt_coeff = filter[filt_j];
275                     int jj = j - filt_w / 2 + filt_j;
276                     float img_coeff;
277
278                     jj = jj < 0 ? -jj : (jj >= w ? 2 * w - jj - 1 : jj);
279
280                     img_coeff = temp[jj];
281                     sum += filt_coeff * img_coeff;
282                 }
283             }
284
285             dst[i * dst_stride + j] = sum;
286         }
287     }
288
289     return 0;
290 }
291
292 int ff_compute_vif2(AVFilterContext *ctx,
293                     const float *ref, const float *main, int w, int h,
294                     int ref_stride, int main_stride, float *score,
295                     float *data_buf[14], float **temp,
296                     int gnb_threads)
297 {
298     ThreadData td;
299     float *ref_scale = data_buf[0];
300     float *main_scale = data_buf[1];
301     float *ref_sq = data_buf[2];
302     float *main_sq = data_buf[3];
303     float *ref_main = data_buf[4];
304     float *mu1 = data_buf[5];
305     float *mu2 = data_buf[6];
306     float *mu1_sq = data_buf[7];
307     float *mu2_sq = data_buf[8];
308     float *mu1_mu2 = data_buf[9];
309     float *ref_sq_filt = data_buf[10];
310     float *main_sq_filt = data_buf[11];
311     float *ref_main_filt = data_buf[12];
312
313     float *curr_ref_scale = (float *)ref;
314     float *curr_main_scale = (float *)main;
315     int curr_ref_stride = ref_stride;
316     int curr_main_stride = main_stride;
317
318     float num = 0.f;
319     float den = 0.f;
320
321     for (int scale = 0; scale < 4; scale++) {
322         const float *filter = vif_filter1d_table[scale];
323         int filter_width = vif_filter1d_width1[scale];
324         const int nb_threads = FFMIN(h, gnb_threads);
325         int buf_valid_w = w;
326         int buf_valid_h = h;
327
328         td.filter = filter;
329         td.filter_width = filter_width;
330
331         if (scale > 0) {
332             td.src = curr_ref_scale;
333             td.dst = mu1;
334             td.w = w;
335             td.h = h;
336             td.src_stride = curr_ref_stride;
337             td.dst_stride = w;
338             td.temp = temp;
339             ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
340
341             td.src = curr_main_scale;
342             td.dst = mu2;
343             td.src_stride = curr_main_stride;
344             ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
345
346             vif_dec2(mu1, ref_scale, buf_valid_w, buf_valid_h, w, w);
347             vif_dec2(mu2, main_scale, buf_valid_w, buf_valid_h, w, w);
348
349             w = buf_valid_w / 2;
350             h = buf_valid_h / 2;
351
352             buf_valid_w = w;
353             buf_valid_h = h;
354
355             curr_ref_scale = ref_scale;
356             curr_main_scale = main_scale;
357
358             curr_ref_stride = w;
359             curr_main_stride = w;
360         }
361
362         td.src = curr_ref_scale;
363         td.dst = mu1;
364         td.w = w;
365         td.h = h;
366         td.src_stride = curr_ref_stride;
367         td.dst_stride = w;
368         td.temp = temp;
369         ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
370
371         td.src = curr_main_scale;
372         td.dst = mu2;
373         td.src_stride = curr_main_stride;
374         ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
375
376         vif_xx_yy_xy(mu1, mu2, mu1_sq, mu2_sq, mu1_mu2, w, h);
377
378         vif_xx_yy_xy(curr_ref_scale, curr_main_scale, ref_sq, main_sq, ref_main, w, h);
379
380         td.src = ref_sq;
381         td.dst = ref_sq_filt;
382         td.src_stride = w;
383         ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
384
385         td.src = main_sq;
386         td.dst = main_sq_filt;
387         td.src_stride = w;
388         ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
389
390         td.src = ref_main;
391         td.dst = ref_main_filt;
392         ctx->internal->execute(ctx, vif_filter1d, &td, NULL, nb_threads);
393
394         vif_statistic(mu1_sq, mu2_sq, mu1_mu2, ref_sq_filt, main_sq_filt,
395                       ref_main_filt, &num, &den, w, h);
396
397         score[scale] = den <= FLT_EPSILON ? 1.f : num / den;
398     }
399
400     return 0;
401 }
402
403 #define offset_fn(type, bits)                            \
404 static void offset_##bits##bit(VIFContext *s,            \
405                                const AVFrame *ref,       \
406                                AVFrame *main, int stride)\
407 {                                                        \
408     int w = s->width;                                    \
409     int h = s->height;                                   \
410                                                          \
411     int ref_stride = ref->linesize[0];                   \
412     int main_stride = main->linesize[0];                 \
413                                                          \
414     const type *ref_ptr = (const type *) ref->data[0];   \
415     const type *main_ptr = (const type *) main->data[0]; \
416                                             \
417     float *ref_ptr_data = s->ref_data;      \
418     float *main_ptr_data = s->main_data;    \
419                                             \
420     for (int i = 0; i < h; i++) {           \
421         for (int j = 0; j < w; j++) {       \
422             ref_ptr_data[j] = ref_ptr[j] - 128.f;   \
423             main_ptr_data[j] = main_ptr[j] - 128.f; \
424         }                                   \
425         ref_ptr += ref_stride / sizeof(type);   \
426         ref_ptr_data += w;                      \
427         main_ptr += main_stride / sizeof(type); \
428         main_ptr_data += w;                     \
429     } \
430 }
431
432 offset_fn(uint8_t, 8)
433 offset_fn(uint16_t, 10)
434
435 static void set_meta(AVDictionary **metadata, const char *key, float d)
436 {
437     char value[257];
438     snprintf(value, sizeof(value), "%f", d);
439     av_dict_set(metadata, key, value, 0);
440 }
441
442 static AVFrame *do_vif(AVFilterContext *ctx, AVFrame *main, const AVFrame *ref)
443 {
444     VIFContext *s = ctx->priv;
445     AVDictionary **metadata = &main->metadata;
446     float score[4];
447
448     if (s->desc->comp[0].depth <= 8) {
449         offset_8bit(s, ref, main, s->width);
450     } else {
451         offset_10bit(s, ref, main, s->width);
452     }
453
454     ff_compute_vif2(ctx,
455                     s->ref_data, s->main_data, s->width,
456                     s->height, s->width, s->width,
457                     score, s->data_buf, s->temp,
458                     s->nb_threads);
459
460     set_meta(metadata, "lavfi.vif.scale.0", score[0]);
461     set_meta(metadata, "lavfi.vif.scale.1", score[1]);
462     set_meta(metadata, "lavfi.vif.scale.2", score[2]);
463     set_meta(metadata, "lavfi.vif.scale.3", score[3]);
464
465     for (int i = 0; i < 4; i++) {
466         s->vif_min[i]  = FFMIN(s->vif_min[i], score[i]);
467         s->vif_max[i]  = FFMAX(s->vif_max[i], score[i]);
468         s->vif_sum[i] += score[i];
469     }
470
471     s->nb_frames++;
472
473     return main;
474 }
475
476 static int query_formats(AVFilterContext *ctx)
477 {
478     static const enum AVPixelFormat pix_fmts[] = {
479         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV420P,
480         AV_PIX_FMT_YUV444P10LE, AV_PIX_FMT_YUV422P10LE, AV_PIX_FMT_YUV420P10LE,
481         AV_PIX_FMT_NONE
482     };
483
484     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
485     if (!fmts_list)
486         return AVERROR(ENOMEM);
487     return ff_set_common_formats(ctx, fmts_list);
488 }
489
490 static int config_input_ref(AVFilterLink *inlink)
491 {
492     AVFilterContext *ctx  = inlink->dst;
493     VIFContext *s = ctx->priv;
494
495     if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
496         ctx->inputs[0]->h != ctx->inputs[1]->h) {
497         av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
498         return AVERROR(EINVAL);
499     }
500     if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
501         av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
502         return AVERROR(EINVAL);
503     }
504
505     s->desc = av_pix_fmt_desc_get(inlink->format);
506     s->width = ctx->inputs[0]->w;
507     s->height = ctx->inputs[0]->h;
508     s->nb_threads = ff_filter_get_nb_threads(ctx);
509
510     for (int i = 0; i < 4; i++) {
511         s->vif_min[i] =  DBL_MAX;
512         s->vif_max[i] = -DBL_MAX;
513     }
514
515     for (int i = 0; i < 13; i++) {
516         if (!(s->data_buf[i] = av_calloc(s->width, s->height * sizeof(float))))
517             return AVERROR(ENOMEM);
518     }
519
520     if (!(s->ref_data = av_calloc(s->width, s->height * sizeof(float))))
521         return AVERROR(ENOMEM);
522
523     if (!(s->main_data = av_calloc(s->width, s->height * sizeof(float))))
524         return AVERROR(ENOMEM);
525
526     if (!(s->temp = av_calloc(s->nb_threads, sizeof(s->temp[0]))))
527         return AVERROR(ENOMEM);
528
529     for (int i = 0; i < s->nb_threads; i++) {
530         if (!(s->temp[i] = av_calloc(s->width, sizeof(float))))
531             return AVERROR(ENOMEM);
532     }
533
534     return 0;
535 }
536
537 static int process_frame(FFFrameSync *fs)
538 {
539     AVFilterContext *ctx = fs->parent;
540     VIFContext *s = fs->opaque;
541     AVFilterLink *outlink = ctx->outputs[0];
542     AVFrame *out_frame, *main_frame = NULL, *ref_frame = NULL;
543     int ret;
544
545     ret = ff_framesync_dualinput_get(fs, &main_frame, &ref_frame);
546     if (ret < 0)
547         return ret;
548
549     if (ctx->is_disabled || !ref_frame) {
550         out_frame = main_frame;
551     } else {
552         out_frame = do_vif(ctx, main_frame, ref_frame);
553     }
554
555     out_frame->pts = av_rescale_q(s->fs.pts, s->fs.time_base, outlink->time_base);
556
557     return ff_filter_frame(outlink, out_frame);
558 }
559
560
561 static int config_output(AVFilterLink *outlink)
562 {
563     AVFilterContext *ctx = outlink->src;
564     VIFContext *s = ctx->priv;
565     AVFilterLink *mainlink = ctx->inputs[0];
566     FFFrameSyncIn *in;
567     int ret;
568
569     outlink->w = mainlink->w;
570     outlink->h = mainlink->h;
571     outlink->time_base = mainlink->time_base;
572     outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
573     outlink->frame_rate = mainlink->frame_rate;
574     if ((ret = ff_framesync_init(&s->fs, ctx, 2)) < 0)
575         return ret;
576
577     in = s->fs.in;
578     in[0].time_base = mainlink->time_base;
579     in[1].time_base = ctx->inputs[1]->time_base;
580     in[0].sync   = 2;
581     in[0].before = EXT_STOP;
582     in[0].after  = EXT_STOP;
583     in[1].sync   = 1;
584     in[1].before = EXT_STOP;
585     in[1].after  = EXT_STOP;
586     s->fs.opaque   = s;
587     s->fs.on_event = process_frame;
588
589     return ff_framesync_configure(&s->fs);
590 }
591
592 static int activate(AVFilterContext *ctx)
593 {
594     VIFContext *s = ctx->priv;
595     return ff_framesync_activate(&s->fs);
596 }
597
598 static av_cold void uninit(AVFilterContext *ctx)
599 {
600     VIFContext *s = ctx->priv;
601
602     if (s->nb_frames > 0) {
603         for (int i = 0; i < 4; i++)
604             av_log(ctx, AV_LOG_INFO, "VIF scale=%d average:%f min:%f: max:%f\n",
605                    i, s->vif_sum[i] / s->nb_frames, s->vif_min[i], s->vif_max[i]);
606     }
607
608     for (int i = 0; i < 13; i++)
609         av_freep(&s->data_buf[i]);
610
611     av_freep(&s->ref_data);
612     av_freep(&s->main_data);
613
614     for (int i = 0; i < s->nb_threads && s->temp; i++)
615         av_freep(&s->temp[i]);
616
617     av_freep(&s->temp);
618
619     ff_framesync_uninit(&s->fs);
620 }
621
622 static const AVFilterPad vif_inputs[] = {
623     {
624         .name         = "main",
625         .type         = AVMEDIA_TYPE_VIDEO,
626     },{
627         .name         = "reference",
628         .type         = AVMEDIA_TYPE_VIDEO,
629         .config_props = config_input_ref,
630     },
631     { NULL }
632 };
633
634 static const AVFilterPad vif_outputs[] = {
635     {
636         .name          = "default",
637         .type          = AVMEDIA_TYPE_VIDEO,
638         .config_props  = config_output,
639     },
640     { NULL }
641 };
642
643 AVFilter ff_vf_vif = {
644     .name          = "vif",
645     .description   = NULL_IF_CONFIG_SMALL("Calculate the VIF between two video streams."),
646     .uninit        = uninit,
647     .query_formats = query_formats,
648     .priv_size     = sizeof(VIFContext),
649     .priv_class    = &vif_class,
650     .activate      = activate,
651     .inputs        = vif_inputs,
652     .outputs       = vif_outputs,
653     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
654 };