]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_psnr.c
Merge commit 'a9a2f3613040c4f90bf15cbd76f8671252ecc043'
[ffmpeg] / libavfilter / vf_psnr.c
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  * Caculate 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 "dualinput.h"
33 #include "drawutils.h"
34 #include "formats.h"
35 #include "internal.h"
36 #include "video.h"
37
38 typedef struct PSNRContext {
39     const AVClass *class;
40     FFDualInputContext dinput;
41     double mse, min_mse, max_mse, mse_comp[4];
42     uint64_t nb_frames;
43     FILE *stats_file;
44     char *stats_file_str;
45     int max[4], average_max;
46     int is_rgb;
47     uint8_t rgba_map[4];
48     char comps[4];
49     int nb_components;
50     int planewidth[4];
51     int planeheight[4];
52     double planeweight[4];
53
54     void (*compute_mse)(struct PSNRContext *s,
55                         const uint8_t *m[4], const int ml[4],
56                         const uint8_t *r[4], const int rl[4],
57                         int w, int h, double mse[4]);
58 } PSNRContext;
59
60 #define OFFSET(x) offsetof(PSNRContext, x)
61 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
62
63 static const AVOption psnr_options[] = {
64     {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
65     {"f",          "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
66     { NULL }
67 };
68
69 AVFILTER_DEFINE_CLASS(psnr);
70
71 static inline unsigned pow2(unsigned base)
72 {
73     return base*base;
74 }
75
76 static inline double get_psnr(double mse, uint64_t nb_frames, int max)
77 {
78     return 10.0 * log(pow2(max) / (mse / nb_frames)) / log(10.0);
79 }
80
81 static inline
82 void compute_images_mse(PSNRContext *s,
83                         const uint8_t *main_data[4], const int main_linesizes[4],
84                         const uint8_t *ref_data[4], const int ref_linesizes[4],
85                         int w, int h, double mse[4])
86 {
87     int i, c, j;
88
89     for (c = 0; c < s->nb_components; c++) {
90         const int outw = s->planewidth[c];
91         const int outh = s->planeheight[c];
92         const uint8_t *main_line = main_data[c];
93         const uint8_t *ref_line = ref_data[c];
94         const int ref_linesize = ref_linesizes[c];
95         const int main_linesize = main_linesizes[c];
96         uint64_t m = 0;
97
98         for (i = 0; i < outh; i++) {
99             int m2 = 0;
100             for (j = 0; j < outw; j++)
101                 m2 += pow2(main_line[j] - ref_line[j]);
102             m += m2;
103             ref_line += ref_linesize;
104             main_line += main_linesize;
105         }
106         mse[c] = m / (double)(outw * outh);
107     }
108 }
109
110 static inline
111 void compute_images_mse_16bit(PSNRContext *s,
112                         const uint8_t *main_data[4], const int main_linesizes[4],
113                         const uint8_t *ref_data[4], const int ref_linesizes[4],
114                         int w, int h, double mse[4])
115 {
116     int i, c, j;
117
118     for (c = 0; c < s->nb_components; c++) {
119         const int outw = s->planewidth[c];
120         const int outh = s->planeheight[c];
121         const uint16_t *main_line = (uint16_t *)main_data[c];
122         const uint16_t *ref_line = (uint16_t *)ref_data[c];
123         const int ref_linesize = ref_linesizes[c] / 2;
124         const int main_linesize = main_linesizes[c] / 2;
125         uint64_t m = 0;
126
127         for (i = 0; i < outh; i++) {
128             for (j = 0; j < outw; j++)
129                 m += pow2(main_line[j] - ref_line[j]);
130             ref_line += ref_linesize;
131             main_line += main_linesize;
132         }
133         mse[c] = m / (double)(outw * outh);
134     }
135 }
136
137 static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
138 {
139     char value[128];
140     snprintf(value, sizeof(value), "%0.2f", d);
141     if (comp) {
142         char key2[128];
143         snprintf(key2, sizeof(key2), "%s%c", key, comp);
144         av_dict_set(metadata, key2, value, 0);
145     } else {
146         av_dict_set(metadata, key, value, 0);
147     }
148 }
149
150 static AVFrame *do_psnr(AVFilterContext *ctx, AVFrame *main,
151                         const AVFrame *ref)
152 {
153     PSNRContext *s = ctx->priv;
154     double comp_mse[4], mse = 0;
155     int j, c;
156     AVDictionary **metadata = avpriv_frame_get_metadatap(main);
157
158     s->compute_mse(s, (const uint8_t **)main->data, main->linesize,
159                       (const uint8_t **)ref->data, ref->linesize,
160                        main->width, main->height, comp_mse);
161
162     for (j = 0; j < s->nb_components; j++)
163         mse += comp_mse[j] * s->planeweight[j];
164
165     s->min_mse = FFMIN(s->min_mse, mse);
166     s->max_mse = FFMAX(s->max_mse, mse);
167
168     s->mse += mse;
169     for (j = 0; j < s->nb_components; j++)
170         s->mse_comp[j] += comp_mse[j];
171     s->nb_frames++;
172
173     for (j = 0; j < s->nb_components; j++) {
174         c = s->is_rgb ? s->rgba_map[j] : j;
175         set_meta(metadata, "lavfi.psnr.mse.", s->comps[j], comp_mse[c]);
176         set_meta(metadata, "lavfi.psnr.psnr.", s->comps[j], get_psnr(comp_mse[c], 1, s->max[c]));
177     }
178     set_meta(metadata, "lavfi.psnr.mse_avg", 0, mse);
179     set_meta(metadata, "lavfi.psnr.psnr_avg", 0, get_psnr(mse, 1, s->average_max));
180
181     if (s->stats_file) {
182         fprintf(s->stats_file, "n:%"PRId64" mse_avg:%0.2f ", s->nb_frames, mse);
183         for (j = 0; j < s->nb_components; j++) {
184             c = s->is_rgb ? s->rgba_map[j] : j;
185             fprintf(s->stats_file, "mse_%c:%0.2f ", s->comps[j], comp_mse[c]);
186         }
187         for (j = 0; j < s->nb_components; j++) {
188             c = s->is_rgb ? s->rgba_map[j] : j;
189             fprintf(s->stats_file, "psnr_%c:%0.2f ", s->comps[j],
190                     get_psnr(comp_mse[c], 1, s->max[c]));
191         }
192         fprintf(s->stats_file, "\n");
193     }
194
195     return main;
196 }
197
198 static av_cold int init(AVFilterContext *ctx)
199 {
200     PSNRContext *s = ctx->priv;
201
202     s->min_mse = +INFINITY;
203     s->max_mse = -INFINITY;
204
205     if (s->stats_file_str) {
206         s->stats_file = fopen(s->stats_file_str, "w");
207         if (!s->stats_file) {
208             int err = AVERROR(errno);
209             char buf[128];
210             av_strerror(err, buf, sizeof(buf));
211             av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
212                    s->stats_file_str, buf);
213             return err;
214         }
215     }
216
217     s->dinput.process = do_psnr;
218     return 0;
219 }
220
221 static int query_formats(AVFilterContext *ctx)
222 {
223     static const enum AVPixelFormat pix_fmts[] = {
224         AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
225 #define PF_NOALPHA(suf) AV_PIX_FMT_YUV420##suf,  AV_PIX_FMT_YUV422##suf,  AV_PIX_FMT_YUV444##suf
226 #define PF_ALPHA(suf)   AV_PIX_FMT_YUVA420##suf, AV_PIX_FMT_YUVA422##suf, AV_PIX_FMT_YUVA444##suf
227 #define PF(suf)         PF_NOALPHA(suf), PF_ALPHA(suf)
228         PF(P), PF(P9), PF(P10), PF_NOALPHA(P12), PF_NOALPHA(P14), PF(P16),
229         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
230         AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
231         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
232         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
233         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
234         AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP16,
235         AV_PIX_FMT_NONE
236     };
237
238     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
239     if (!fmts_list)
240         return AVERROR(ENOMEM);
241     return ff_set_common_formats(ctx, fmts_list);
242 }
243
244 static int config_input_ref(AVFilterLink *inlink)
245 {
246     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
247     AVFilterContext *ctx  = inlink->dst;
248     PSNRContext *s = ctx->priv;
249     unsigned sum;
250     int j;
251
252     s->nb_components = desc->nb_components;
253     if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
254         ctx->inputs[0]->h != ctx->inputs[1]->h) {
255         av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
256         return AVERROR(EINVAL);
257     }
258     if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
259         av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
260         return AVERROR(EINVAL);
261     }
262
263     s->max[0] = (1 << (desc->comp[0].depth_minus1 + 1)) - 1;
264     s->max[1] = (1 << (desc->comp[1].depth_minus1 + 1)) - 1;
265     s->max[2] = (1 << (desc->comp[2].depth_minus1 + 1)) - 1;
266     s->max[3] = (1 << (desc->comp[3].depth_minus1 + 1)) - 1;
267
268     s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
269     s->comps[0] = s->is_rgb ? 'r' : 'y' ;
270     s->comps[1] = s->is_rgb ? 'g' : 'u' ;
271     s->comps[2] = s->is_rgb ? 'b' : 'v' ;
272     s->comps[3] = 'a';
273
274     s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
275     s->planeheight[0] = s->planeheight[3] = inlink->h;
276     s->planewidth[1]  = s->planewidth[2]  = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
277     s->planewidth[0]  = s->planewidth[3]  = inlink->w;
278     sum = 0;
279     for (j = 0; j < s->nb_components; j++)
280         sum += s->planeheight[j] * s->planewidth[j];
281     for (j = 0; j < s->nb_components; j++) {
282         s->planeweight[j] = (double) s->planeheight[j] * s->planewidth[j] / sum;
283         s->average_max += s->max[j] * s->planeweight[j];
284     }
285
286     s->compute_mse = desc->comp[0].depth_minus1 > 7 ? compute_images_mse_16bit : compute_images_mse;
287
288     return 0;
289 }
290
291 static int config_output(AVFilterLink *outlink)
292 {
293     AVFilterContext *ctx = outlink->src;
294     PSNRContext *s = ctx->priv;
295     AVFilterLink *mainlink = ctx->inputs[0];
296     int ret;
297
298     outlink->w = mainlink->w;
299     outlink->h = mainlink->h;
300     outlink->time_base = mainlink->time_base;
301     outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
302     outlink->frame_rate = mainlink->frame_rate;
303     if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
304         return ret;
305
306     return 0;
307 }
308
309 static int filter_frame(AVFilterLink *inlink, AVFrame *inpicref)
310 {
311     PSNRContext *s = inlink->dst->priv;
312     return ff_dualinput_filter_frame(&s->dinput, inlink, inpicref);
313 }
314
315 static int request_frame(AVFilterLink *outlink)
316 {
317     PSNRContext *s = outlink->src->priv;
318     return ff_dualinput_request_frame(&s->dinput, outlink);
319 }
320
321 static av_cold void uninit(AVFilterContext *ctx)
322 {
323     PSNRContext *s = ctx->priv;
324
325     if (s->nb_frames > 0) {
326         int j;
327         char buf[256];
328
329         buf[0] = 0;
330         for (j = 0; j < s->nb_components; j++) {
331             int c = s->is_rgb ? s->rgba_map[j] : j;
332             av_strlcatf(buf, sizeof(buf), " %c:%0.2f", s->comps[j],
333                         get_psnr(s->mse_comp[c], s->nb_frames, s->max[c]));
334         }
335         av_log(ctx, AV_LOG_INFO, "PSNR%s average:%0.2f min:%0.2f max:%0.2f\n",
336                buf,
337                get_psnr(s->mse, s->nb_frames, s->average_max),
338                get_psnr(s->max_mse, 1, s->average_max),
339                get_psnr(s->min_mse, 1, s->average_max));
340     }
341
342     ff_dualinput_uninit(&s->dinput);
343
344     if (s->stats_file)
345         fclose(s->stats_file);
346 }
347
348 static const AVFilterPad psnr_inputs[] = {
349     {
350         .name         = "main",
351         .type         = AVMEDIA_TYPE_VIDEO,
352         .filter_frame = filter_frame,
353     },{
354         .name         = "reference",
355         .type         = AVMEDIA_TYPE_VIDEO,
356         .filter_frame = filter_frame,
357         .config_props = config_input_ref,
358     },
359     { NULL }
360 };
361
362 static const AVFilterPad psnr_outputs[] = {
363     {
364         .name          = "default",
365         .type          = AVMEDIA_TYPE_VIDEO,
366         .config_props  = config_output,
367         .request_frame = request_frame,
368     },
369     { NULL }
370 };
371
372 AVFilter ff_vf_psnr = {
373     .name          = "psnr",
374     .description   = NULL_IF_CONFIG_SMALL("Calculate the PSNR between two video streams."),
375     .init          = init,
376     .uninit        = uninit,
377     .query_formats = query_formats,
378     .priv_size     = sizeof(PSNRContext),
379     .priv_class    = &psnr_class,
380     .inputs        = psnr_inputs,
381     .outputs       = psnr_outputs,
382 };