• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2011 Roger Pau Monné <roger.pau@entel.upc.edu>
3  * Copyright (c) 2011 Stefano Sabatini
4  * Copyright (c) 2013 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 the PSNR between two input videos.
26  */
27 
28 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32 #include "drawutils.h"
33 #include "formats.h"
34 #include "framesync.h"
35 #include "internal.h"
36 #include "psnr.h"
37 #include "video.h"
38 
39 typedef struct PSNRContext {
40     const AVClass *class;
41     FFFrameSync fs;
42     double mse, min_mse, max_mse, mse_comp[4];
43     uint64_t nb_frames;
44     FILE *stats_file;
45     char *stats_file_str;
46     int stats_version;
47     int stats_header_written;
48     int stats_add_max;
49     int max[4], average_max;
50     int is_rgb;
51     uint8_t rgba_map[4];
52     char comps[4];
53     int nb_components;
54     int nb_threads;
55     int planewidth[4];
56     int planeheight[4];
57     double planeweight[4];
58     uint64_t **score;
59     PSNRDSPContext dsp;
60 } PSNRContext;
61 
62 #define OFFSET(x) offsetof(PSNRContext, x)
63 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
64 
65 static const AVOption psnr_options[] = {
66     {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
67     {"f",          "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
68     {"stats_version", "Set the format version for the stats file.",               OFFSET(stats_version),  AV_OPT_TYPE_INT,    {.i64=1},    1, 2, FLAGS },
69     {"output_max",  "Add raw stats (max values) to the output log.",            OFFSET(stats_add_max), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
70     { NULL }
71 };
72 
73 FRAMESYNC_DEFINE_CLASS(psnr, PSNRContext, fs);
74 
pow_2(unsigned base)75 static inline unsigned pow_2(unsigned base)
76 {
77     return base*base;
78 }
79 
get_psnr(double mse,uint64_t nb_frames,int max)80 static inline double get_psnr(double mse, uint64_t nb_frames, int max)
81 {
82     return 10.0 * log10(pow_2(max) / (mse / nb_frames));
83 }
84 
sse_line_8bit(const uint8_t * main_line,const uint8_t * ref_line,int outw)85 static uint64_t sse_line_8bit(const uint8_t *main_line,  const uint8_t *ref_line, int outw)
86 {
87     int j;
88     unsigned m2 = 0;
89 
90     for (j = 0; j < outw; j++)
91         m2 += pow_2(main_line[j] - ref_line[j]);
92 
93     return m2;
94 }
95 
sse_line_16bit(const uint8_t * _main_line,const uint8_t * _ref_line,int outw)96 static uint64_t sse_line_16bit(const uint8_t *_main_line, const uint8_t *_ref_line, int outw)
97 {
98     int j;
99     uint64_t m2 = 0;
100     const uint16_t *main_line = (const uint16_t *) _main_line;
101     const uint16_t *ref_line = (const uint16_t *) _ref_line;
102 
103     for (j = 0; j < outw; j++)
104         m2 += pow_2(main_line[j] - ref_line[j]);
105 
106     return m2;
107 }
108 
109 typedef struct ThreadData {
110     const uint8_t *main_data[4];
111     const uint8_t *ref_data[4];
112     int main_linesize[4];
113     int ref_linesize[4];
114     int planewidth[4];
115     int planeheight[4];
116     uint64_t **score;
117     int nb_components;
118     PSNRDSPContext *dsp;
119 } ThreadData;
120 
121 static
compute_images_mse(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)122 int compute_images_mse(AVFilterContext *ctx, void *arg,
123                        int jobnr, int nb_jobs)
124 {
125     ThreadData *td = arg;
126     uint64_t *score = td->score[jobnr];
127 
128     for (int c = 0; c < td->nb_components; c++) {
129         const int outw = td->planewidth[c];
130         const int outh = td->planeheight[c];
131         const int slice_start = (outh * jobnr) / nb_jobs;
132         const int slice_end = (outh * (jobnr+1)) / nb_jobs;
133         const int ref_linesize = td->ref_linesize[c];
134         const int main_linesize = td->main_linesize[c];
135         const uint8_t *main_line = td->main_data[c] + main_linesize * slice_start;
136         const uint8_t *ref_line = td->ref_data[c] + ref_linesize * slice_start;
137         uint64_t m = 0;
138         for (int i = slice_start; i < slice_end; i++) {
139             m += td->dsp->sse_line(main_line, ref_line, outw);
140             ref_line += ref_linesize;
141             main_line += main_linesize;
142         }
143         score[c] = m;
144     }
145 
146     return 0;
147 }
148 
set_meta(AVDictionary ** metadata,const char * key,char comp,float d)149 static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
150 {
151     char value[128];
152     snprintf(value, sizeof(value), "%f", d);
153     if (comp) {
154         char key2[128];
155         snprintf(key2, sizeof(key2), "%s%c", key, comp);
156         av_dict_set(metadata, key2, value, 0);
157     } else {
158         av_dict_set(metadata, key, value, 0);
159     }
160 }
161 
do_psnr(FFFrameSync * fs)162 static int do_psnr(FFFrameSync *fs)
163 {
164     AVFilterContext *ctx = fs->parent;
165     PSNRContext *s = ctx->priv;
166     AVFrame *master, *ref;
167     double comp_mse[4], mse = 0.;
168     uint64_t comp_sum[4] = { 0 };
169     AVDictionary **metadata;
170     ThreadData td;
171     int ret;
172 
173     ret = ff_framesync_dualinput_get(fs, &master, &ref);
174     if (ret < 0)
175         return ret;
176     if (ctx->is_disabled || !ref)
177         return ff_filter_frame(ctx->outputs[0], master);
178     metadata = &master->metadata;
179 
180     td.nb_components = s->nb_components;
181     td.dsp = &s->dsp;
182     td.score = s->score;
183     for (int c = 0; c < s->nb_components; c++) {
184         td.main_data[c] = master->data[c];
185         td.ref_data[c] = ref->data[c];
186         td.main_linesize[c] = master->linesize[c];
187         td.ref_linesize[c] = ref->linesize[c];
188         td.planewidth[c] = s->planewidth[c];
189         td.planeheight[c] = s->planeheight[c];
190     }
191 
192     ff_filter_execute(ctx, compute_images_mse, &td, NULL,
193                       FFMIN(s->planeheight[1], s->nb_threads));
194 
195     for (int j = 0; j < s->nb_threads; j++) {
196         for (int c = 0; c < s->nb_components; c++)
197             comp_sum[c] += s->score[j][c];
198     }
199 
200     for (int c = 0; c < s->nb_components; c++)
201         comp_mse[c] = comp_sum[c] / ((double)s->planewidth[c] * s->planeheight[c]);
202 
203     for (int c = 0; c < s->nb_components; c++)
204         mse += comp_mse[c] * s->planeweight[c];
205 
206     s->min_mse = FFMIN(s->min_mse, mse);
207     s->max_mse = FFMAX(s->max_mse, mse);
208 
209     s->mse += mse;
210 
211     for (int j = 0; j < s->nb_components; j++)
212         s->mse_comp[j] += comp_mse[j];
213     s->nb_frames++;
214 
215     for (int j = 0; j < s->nb_components; j++) {
216         int c = s->is_rgb ? s->rgba_map[j] : j;
217         set_meta(metadata, "lavfi.psnr.mse.", s->comps[j], comp_mse[c]);
218         set_meta(metadata, "lavfi.psnr.psnr.", s->comps[j], get_psnr(comp_mse[c], 1, s->max[c]));
219     }
220     set_meta(metadata, "lavfi.psnr.mse_avg", 0, mse);
221     set_meta(metadata, "lavfi.psnr.psnr_avg", 0, get_psnr(mse, 1, s->average_max));
222 
223     if (s->stats_file) {
224         if (s->stats_version == 2 && !s->stats_header_written) {
225             fprintf(s->stats_file, "psnr_log_version:2 fields:n");
226             fprintf(s->stats_file, ",mse_avg");
227             for (int j = 0; j < s->nb_components; j++) {
228                 fprintf(s->stats_file, ",mse_%c", s->comps[j]);
229             }
230             fprintf(s->stats_file, ",psnr_avg");
231             for (int j = 0; j < s->nb_components; j++) {
232                 fprintf(s->stats_file, ",psnr_%c", s->comps[j]);
233             }
234             if (s->stats_add_max) {
235                 fprintf(s->stats_file, ",max_avg");
236                 for (int j = 0; j < s->nb_components; j++) {
237                     fprintf(s->stats_file, ",max_%c", s->comps[j]);
238                 }
239             }
240             fprintf(s->stats_file, "\n");
241             s->stats_header_written = 1;
242         }
243         fprintf(s->stats_file, "n:%"PRId64" mse_avg:%0.2f ", s->nb_frames, mse);
244         for (int j = 0; j < s->nb_components; j++) {
245             int c = s->is_rgb ? s->rgba_map[j] : j;
246             fprintf(s->stats_file, "mse_%c:%0.2f ", s->comps[j], comp_mse[c]);
247         }
248         fprintf(s->stats_file, "psnr_avg:%0.2f ", get_psnr(mse, 1, s->average_max));
249         for (int j = 0; j < s->nb_components; j++) {
250             int c = s->is_rgb ? s->rgba_map[j] : j;
251             fprintf(s->stats_file, "psnr_%c:%0.2f ", s->comps[j],
252                     get_psnr(comp_mse[c], 1, s->max[c]));
253         }
254         if (s->stats_version == 2 && s->stats_add_max) {
255             fprintf(s->stats_file, "max_avg:%d ", s->average_max);
256             for (int j = 0; j < s->nb_components; j++) {
257                 int c = s->is_rgb ? s->rgba_map[j] : j;
258                 fprintf(s->stats_file, "max_%c:%d ", s->comps[j], s->max[c]);
259             }
260         }
261         fprintf(s->stats_file, "\n");
262     }
263 
264     return ff_filter_frame(ctx->outputs[0], master);
265 }
266 
init(AVFilterContext * ctx)267 static av_cold int init(AVFilterContext *ctx)
268 {
269     PSNRContext *s = ctx->priv;
270 
271     s->min_mse = +INFINITY;
272     s->max_mse = -INFINITY;
273 
274     if (s->stats_file_str) {
275         if (s->stats_version < 2 && s->stats_add_max) {
276             av_log(ctx, AV_LOG_ERROR,
277                 "stats_add_max was specified but stats_version < 2.\n" );
278             return AVERROR(EINVAL);
279         }
280         if (!strcmp(s->stats_file_str, "-")) {
281             s->stats_file = stdout;
282         } else {
283             s->stats_file = avpriv_fopen_utf8(s->stats_file_str, "w");
284             if (!s->stats_file) {
285                 int err = AVERROR(errno);
286                 char buf[128];
287                 av_strerror(err, buf, sizeof(buf));
288                 av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
289                        s->stats_file_str, buf);
290                 return err;
291             }
292         }
293     }
294 
295     s->fs.on_event = do_psnr;
296     return 0;
297 }
298 
299 static const enum AVPixelFormat pix_fmts[] = {
300     AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
301 #define PF_NOALPHA(suf) AV_PIX_FMT_YUV420##suf,  AV_PIX_FMT_YUV422##suf,  AV_PIX_FMT_YUV444##suf
302 #define PF_ALPHA(suf)   AV_PIX_FMT_YUVA420##suf, AV_PIX_FMT_YUVA422##suf, AV_PIX_FMT_YUVA444##suf
303 #define PF(suf)         PF_NOALPHA(suf), PF_ALPHA(suf)
304     PF(P), PF(P9), PF(P10), PF_NOALPHA(P12), PF_NOALPHA(P14), PF(P16),
305     AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
306     AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
307     AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
308     AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
309     AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
310     AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
311     AV_PIX_FMT_NONE
312 };
313 
config_input_ref(AVFilterLink * inlink)314 static int config_input_ref(AVFilterLink *inlink)
315 {
316     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
317     AVFilterContext *ctx  = inlink->dst;
318     PSNRContext *s = ctx->priv;
319     double average_max;
320     unsigned sum;
321     int j;
322 
323     s->nb_threads = ff_filter_get_nb_threads(ctx);
324     s->nb_components = desc->nb_components;
325     if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
326         ctx->inputs[0]->h != ctx->inputs[1]->h) {
327         av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
328         return AVERROR(EINVAL);
329     }
330 
331     s->max[0] = (1 << desc->comp[0].depth) - 1;
332     s->max[1] = (1 << desc->comp[1].depth) - 1;
333     s->max[2] = (1 << desc->comp[2].depth) - 1;
334     s->max[3] = (1 << desc->comp[3].depth) - 1;
335 
336     s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
337     s->comps[0] = s->is_rgb ? 'r' : 'y' ;
338     s->comps[1] = s->is_rgb ? 'g' : 'u' ;
339     s->comps[2] = s->is_rgb ? 'b' : 'v' ;
340     s->comps[3] = 'a';
341 
342     s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
343     s->planeheight[0] = s->planeheight[3] = inlink->h;
344     s->planewidth[1]  = s->planewidth[2]  = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
345     s->planewidth[0]  = s->planewidth[3]  = inlink->w;
346     sum = 0;
347     for (j = 0; j < s->nb_components; j++)
348         sum += s->planeheight[j] * s->planewidth[j];
349     average_max = 0;
350     for (j = 0; j < s->nb_components; j++) {
351         s->planeweight[j] = (double) s->planeheight[j] * s->planewidth[j] / sum;
352         average_max += s->max[j] * s->planeweight[j];
353     }
354     s->average_max = lrint(average_max);
355 
356     s->dsp.sse_line = desc->comp[0].depth > 8 ? sse_line_16bit : sse_line_8bit;
357 #if ARCH_X86
358     ff_psnr_init_x86(&s->dsp, desc->comp[0].depth);
359 #endif
360 
361     s->score = av_calloc(s->nb_threads, sizeof(*s->score));
362     if (!s->score)
363         return AVERROR(ENOMEM);
364 
365     for (int t = 0; t < s->nb_threads; t++) {
366         s->score[t] = av_calloc(s->nb_components, sizeof(*s->score[0]));
367         if (!s->score[t])
368             return AVERROR(ENOMEM);
369     }
370 
371     return 0;
372 }
373 
config_output(AVFilterLink * outlink)374 static int config_output(AVFilterLink *outlink)
375 {
376     AVFilterContext *ctx = outlink->src;
377     PSNRContext *s = ctx->priv;
378     AVFilterLink *mainlink = ctx->inputs[0];
379     int ret;
380 
381     ret = ff_framesync_init_dualinput(&s->fs, ctx);
382     if (ret < 0)
383         return ret;
384     outlink->w = mainlink->w;
385     outlink->h = mainlink->h;
386     outlink->time_base = mainlink->time_base;
387     outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
388     outlink->frame_rate = mainlink->frame_rate;
389     if ((ret = ff_framesync_configure(&s->fs)) < 0)
390         return ret;
391 
392     outlink->time_base = s->fs.time_base;
393 
394     if (av_cmp_q(mainlink->time_base, outlink->time_base) ||
395         av_cmp_q(ctx->inputs[1]->time_base, outlink->time_base))
396         av_log(ctx, AV_LOG_WARNING, "not matching timebases found between first input: %d/%d and second input %d/%d, results may be incorrect!\n",
397                mainlink->time_base.num, mainlink->time_base.den,
398                ctx->inputs[1]->time_base.num, ctx->inputs[1]->time_base.den);
399 
400     return 0;
401 }
402 
activate(AVFilterContext * ctx)403 static int activate(AVFilterContext *ctx)
404 {
405     PSNRContext *s = ctx->priv;
406     return ff_framesync_activate(&s->fs);
407 }
408 
uninit(AVFilterContext * ctx)409 static av_cold void uninit(AVFilterContext *ctx)
410 {
411     PSNRContext *s = ctx->priv;
412 
413     if (s->nb_frames > 0) {
414         int j;
415         char buf[256];
416 
417         buf[0] = 0;
418         for (j = 0; j < s->nb_components; j++) {
419             int c = s->is_rgb ? s->rgba_map[j] : j;
420             av_strlcatf(buf, sizeof(buf), " %c:%f", s->comps[j],
421                         get_psnr(s->mse_comp[c], s->nb_frames, s->max[c]));
422         }
423         av_log(ctx, AV_LOG_INFO, "PSNR%s average:%f min:%f max:%f\n",
424                buf,
425                get_psnr(s->mse, s->nb_frames, s->average_max),
426                get_psnr(s->max_mse, 1, s->average_max),
427                get_psnr(s->min_mse, 1, s->average_max));
428     }
429 
430     ff_framesync_uninit(&s->fs);
431     for (int t = 0; t < s->nb_threads && s->score; t++)
432         av_freep(&s->score[t]);
433     av_freep(&s->score);
434 
435     if (s->stats_file && s->stats_file != stdout)
436         fclose(s->stats_file);
437 }
438 
439 static const AVFilterPad psnr_inputs[] = {
440     {
441         .name         = "main",
442         .type         = AVMEDIA_TYPE_VIDEO,
443     },{
444         .name         = "reference",
445         .type         = AVMEDIA_TYPE_VIDEO,
446         .config_props = config_input_ref,
447     },
448 };
449 
450 static const AVFilterPad psnr_outputs[] = {
451     {
452         .name          = "default",
453         .type          = AVMEDIA_TYPE_VIDEO,
454         .config_props  = config_output,
455     },
456 };
457 
458 const AVFilter ff_vf_psnr = {
459     .name          = "psnr",
460     .description   = NULL_IF_CONFIG_SMALL("Calculate the PSNR between two video streams."),
461     .preinit       = psnr_framesync_preinit,
462     .init          = init,
463     .uninit        = uninit,
464     .activate      = activate,
465     .priv_size     = sizeof(PSNRContext),
466     .priv_class    = &psnr_class,
467     FILTER_INPUTS(psnr_inputs),
468     FILTER_OUTPUTS(psnr_outputs),
469     FILTER_PIXFMTS_ARRAY(pix_fmts),
470     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
471                      AVFILTER_FLAG_SLICE_THREADS             |
472                      AVFILTER_FLAG_METADATA_ONLY,
473 };
474