]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_tonemap.c
vf_tonemap: Fix logic for detecting the maximum peak of untagged sources
[ffmpeg] / libavfilter / vf_tonemap.c
1 /*
2  * Copyright (c) 2017 Vittorio Giovara <vittorio.giovara@gmail.com>
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * tonemap algorithms
24  */
25
26 #include <float.h>
27 #include <stdio.h>
28 #include <string.h>
29
30 #include "libavutil/imgutils.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/mastering_display_metadata.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/pixdesc.h"
36
37 #include "avfilter.h"
38 #include "formats.h"
39 #include "internal.h"
40 #include "video.h"
41
42 #define REFERENCE_WHITE 100.0f
43
44 enum TonemapAlgorithm {
45     TONEMAP_NONE,
46     TONEMAP_LINEAR,
47     TONEMAP_GAMMA,
48     TONEMAP_CLIP,
49     TONEMAP_REINHARD,
50     TONEMAP_HABLE,
51     TONEMAP_MOBIUS,
52     TONEMAP_MAX,
53 };
54
55 typedef struct LumaCoefficients {
56     double cr, cg, cb;
57 } LumaCoefficients;
58
59
60 static const struct LumaCoefficients luma_coefficients[AVCOL_SPC_NB] = {
61     [AVCOL_SPC_FCC]        = { 0.30,   0.59,   0.11   },
62     [AVCOL_SPC_BT470BG]    = { 0.299,  0.587,  0.114  },
63     [AVCOL_SPC_SMPTE170M]  = { 0.299,  0.587,  0.114  },
64     [AVCOL_SPC_BT709]      = { 0.2126, 0.7152, 0.0722 },
65     [AVCOL_SPC_SMPTE240M]  = { 0.212,  0.701,  0.087  },
66     [AVCOL_SPC_BT2020_NCL] = { 0.2627, 0.6780, 0.0593 },
67     [AVCOL_SPC_BT2020_CL]  = { 0.2627, 0.6780, 0.0593 },
68 };
69
70 typedef struct TonemapContext {
71     const AVClass *class;
72
73     enum TonemapAlgorithm tonemap;
74     double param;
75     double desat;
76     double peak;
77
78     const LumaCoefficients *coeffs;
79 } TonemapContext;
80
81 static const enum AVPixelFormat pix_fmts[] = {
82     AV_PIX_FMT_GBRPF32,
83     AV_PIX_FMT_GBRAPF32,
84     AV_PIX_FMT_NONE,
85 };
86
87 static int query_formats(AVFilterContext *ctx)
88 {
89     return ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
90 }
91
92 static av_cold int init(AVFilterContext *ctx)
93 {
94     TonemapContext *s = ctx->priv;
95
96     switch(s->tonemap) {
97     case TONEMAP_GAMMA:
98         if (isnan(s->param))
99             s->param = 1.8f;
100         break;
101     case TONEMAP_REINHARD:
102         if (!isnan(s->param))
103             s->param = (1.0f - s->param) / s->param;
104         break;
105     case TONEMAP_MOBIUS:
106         if (isnan(s->param))
107             s->param = 0.3f;
108         break;
109     }
110
111     if (isnan(s->param))
112         s->param = 1.0f;
113
114     return 0;
115 }
116
117 static double determine_signal_peak(AVFrame *in)
118 {
119     AVFrameSideData *sd = av_frame_get_side_data(in, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
120     double peak = 0;
121
122     if (sd) {
123         AVContentLightMetadata *clm = (AVContentLightMetadata *)sd->data;
124         peak = clm->MaxCLL / REFERENCE_WHITE;
125     }
126
127     sd = av_frame_get_side_data(in, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
128     if (!peak && sd) {
129         AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)sd->data;
130         if (metadata->has_luminance)
131             peak = av_q2d(metadata->max_luminance) / REFERENCE_WHITE;
132     }
133
134     // For untagged source, use peak of 10000 if SMPTE ST.2084
135     // otherwise assume HLG with reference display peak 1000.
136     if (!peak)
137         peak = in->color_trc == AVCOL_TRC_SMPTE2084 ? 100.0f : 10.0f;
138
139     return peak;
140 }
141
142 static float hable(float in)
143 {
144     float a = 0.15f, b = 0.50f, c = 0.10f, d = 0.20f, e = 0.02f, f = 0.30f;
145     return (in * (in * a + b * c) + d * e) / (in * (in * a + b) + d * f) - e / f;
146 }
147
148 static float mobius(float in, float j, double peak)
149 {
150     float a, b;
151
152     if (in <= j)
153         return in;
154
155     a = -j * j * (peak - 1.0f) / (j * j - 2.0f * j + peak);
156     b = (j * j - 2.0f * j * peak + peak) / FFMAX(peak - 1.0f, 1e-6);
157
158     return (b * b + 2.0f * b * j + j * j) / (b - a) * (in + a) / (in + b);
159 }
160
161 #define MIX(x,y,a) (x) * (1 - (a)) + (y) * (a)
162 static void tonemap(TonemapContext *s, AVFrame *out, const AVFrame *in,
163                     const AVPixFmtDescriptor *desc, int x, int y, double peak)
164 {
165     const float *r_in = (const float *)(in->data[0] + x * desc->comp[0].step + y * in->linesize[0]);
166     const float *b_in = (const float *)(in->data[1] + x * desc->comp[1].step + y * in->linesize[1]);
167     const float *g_in = (const float *)(in->data[2] + x * desc->comp[2].step + y * in->linesize[2]);
168     float *r_out = (float *)(out->data[0] + x * desc->comp[0].step + y * out->linesize[0]);
169     float *b_out = (float *)(out->data[1] + x * desc->comp[1].step + y * out->linesize[1]);
170     float *g_out = (float *)(out->data[2] + x * desc->comp[2].step + y * out->linesize[2]);
171     float sig, sig_orig;
172
173     /* load values */
174     *r_out = *r_in;
175     *b_out = *b_in;
176     *g_out = *g_in;
177
178     /* desaturate to prevent unnatural colors */
179     if (s->desat > 0) {
180         float luma = s->coeffs->cr * *r_in + s->coeffs->cg * *g_in + s->coeffs->cb * *b_in;
181         float overbright = FFMAX(luma - s->desat, 1e-6) / FFMAX(luma, 1e-6);
182         *r_out = MIX(*r_in, luma, overbright);
183         *g_out = MIX(*g_in, luma, overbright);
184         *b_out = MIX(*b_in, luma, overbright);
185     }
186
187     /* pick the brightest component, reducing the value range as necessary
188      * to keep the entire signal in range and preventing discoloration due to
189      * out-of-bounds clipping */
190     sig = FFMAX(FFMAX3(*r_out, *g_out, *b_out), 1e-6);
191     sig_orig = sig;
192
193     switch(s->tonemap) {
194     default:
195     case TONEMAP_NONE:
196         // do nothing
197         break;
198     case TONEMAP_LINEAR:
199         sig = sig * s->param / peak;
200         break;
201     case TONEMAP_GAMMA:
202         sig = sig > 0.05f ? pow(sig / peak, 1.0f / s->param)
203                           : sig * pow(0.05f / peak, 1.0f / s->param) / 0.05f;
204         break;
205     case TONEMAP_CLIP:
206         sig = av_clipf(sig * s->param, 0, 1.0f);
207         break;
208     case TONEMAP_HABLE:
209         sig = hable(sig) / hable(peak);
210         break;
211     case TONEMAP_REINHARD:
212         sig = sig / (sig + s->param) * (peak + s->param) / peak;
213         break;
214     case TONEMAP_MOBIUS:
215         sig = mobius(sig, s->param, peak);
216         break;
217     }
218
219     /* apply the computed scale factor to the color,
220      * linearly to prevent discoloration */
221     *r_out *= sig / sig_orig;
222     *g_out *= sig / sig_orig;
223     *b_out *= sig / sig_orig;
224 }
225
226 static int filter_frame(AVFilterLink *link, AVFrame *in)
227 {
228     TonemapContext *s = link->dst->priv;
229     AVFilterLink *outlink = link->dst->outputs[0];
230     AVFrame *out;
231     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
232     const AVPixFmtDescriptor *odesc = av_pix_fmt_desc_get(outlink->format);
233     int ret, x, y;
234     double peak = s->peak;
235
236     if (!desc || !odesc) {
237         av_frame_free(&in);
238         return AVERROR_BUG;
239     }
240
241     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
242     if (!out) {
243         av_frame_free(&in);
244         return AVERROR(ENOMEM);
245     }
246
247     ret = av_frame_copy_props(out, in);
248     if (ret < 0) {
249         av_frame_free(&in);
250         av_frame_free(&out);
251         return ret;
252     }
253
254     /* input and output transfer will be linear */
255     if (in->color_trc == AVCOL_TRC_UNSPECIFIED) {
256         av_log(s, AV_LOG_WARNING, "Untagged transfer, assuming linear light\n");
257         out->color_trc = AVCOL_TRC_LINEAR;
258     } else if (in->color_trc != AVCOL_TRC_LINEAR)
259         av_log(s, AV_LOG_WARNING, "Tonemapping works on linear light only\n");
260
261     /* read peak from side data if not passed in */
262     if (!peak) {
263         peak = determine_signal_peak(in);
264         av_log(s, AV_LOG_DEBUG, "Computed signal peak: %f\n", peak);
265     }
266
267     /* load original color space even if pixel format is RGB to compute overbrights */
268     s->coeffs = &luma_coefficients[in->colorspace];
269     if (s->desat > 0 && (in->colorspace == AVCOL_SPC_UNSPECIFIED || !s->coeffs)) {
270         if (in->colorspace == AVCOL_SPC_UNSPECIFIED)
271             av_log(s, AV_LOG_WARNING, "Missing color space information, ");
272         else if (!s->coeffs)
273             av_log(s, AV_LOG_WARNING, "Unsupported color space '%s', ",
274                    av_color_space_name(in->colorspace));
275         av_log(s, AV_LOG_WARNING, "desaturation is disabled\n");
276         s->desat = 0;
277     }
278
279     /* do the tone map */
280     for (y = 0; y < out->height; y++)
281         for (x = 0; x < out->width; x++)
282             tonemap(s, out, in, desc, x, y, peak);
283
284     /* copy/generate alpha if needed */
285     if (desc->flags & AV_PIX_FMT_FLAG_ALPHA && odesc->flags & AV_PIX_FMT_FLAG_ALPHA) {
286         av_image_copy_plane(out->data[3], out->linesize[3],
287                             in->data[3], in->linesize[3],
288                             out->linesize[3], outlink->h);
289     } else if (odesc->flags & AV_PIX_FMT_FLAG_ALPHA) {
290         for (y = 0; y < out->height; y++) {
291             for (x = 0; x < out->width; x++) {
292                 AV_WN32(out->data[3] + x * odesc->comp[3].step + y * out->linesize[3],
293                         av_float2int(1.0f));
294             }
295         }
296     }
297
298     av_frame_free(&in);
299
300     return ff_filter_frame(outlink, out);
301 }
302
303 #define OFFSET(x) offsetof(TonemapContext, x)
304 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
305 static const AVOption tonemap_options[] = {
306     { "tonemap",      "tonemap algorithm selection", OFFSET(tonemap), AV_OPT_TYPE_INT, {.i64 = TONEMAP_NONE}, TONEMAP_NONE, TONEMAP_MAX - 1, FLAGS, "tonemap" },
307     {     "none",     0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_NONE},              0, 0, FLAGS, "tonemap" },
308     {     "linear",   0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_LINEAR},            0, 0, FLAGS, "tonemap" },
309     {     "gamma",    0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_GAMMA},             0, 0, FLAGS, "tonemap" },
310     {     "clip",     0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_CLIP},              0, 0, FLAGS, "tonemap" },
311     {     "reinhard", 0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_REINHARD},          0, 0, FLAGS, "tonemap" },
312     {     "hable",    0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_HABLE},             0, 0, FLAGS, "tonemap" },
313     {     "mobius",   0, 0, AV_OPT_TYPE_CONST, {.i64 = TONEMAP_MOBIUS},            0, 0, FLAGS, "tonemap" },
314     { "param",        "tonemap parameter", OFFSET(param), AV_OPT_TYPE_DOUBLE, {.dbl = NAN}, DBL_MIN, DBL_MAX, FLAGS },
315     { "desat",        "desaturation strength", OFFSET(desat), AV_OPT_TYPE_DOUBLE, {.dbl = 2}, 0, DBL_MAX, FLAGS },
316     { "peak",         "signal peak override", OFFSET(peak), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, DBL_MAX, FLAGS },
317     { NULL }
318 };
319
320 static const AVClass tonemap_class = {
321     .class_name       = "tonemap",
322     .item_name        = av_default_item_name,
323     .option           = tonemap_options,
324     .version          = LIBAVUTIL_VERSION_INT,
325     .category         = AV_CLASS_CATEGORY_FILTER,
326 };
327
328 static const AVFilterPad tonemap_inputs[] = {
329     {
330         .name         = "default",
331         .type         = AVMEDIA_TYPE_VIDEO,
332         .filter_frame = filter_frame,
333     },
334     { NULL }
335 };
336
337 static const AVFilterPad tonemap_outputs[] = {
338     {
339         .name         = "default",
340         .type         = AVMEDIA_TYPE_VIDEO,
341     },
342     { NULL }
343 };
344
345 AVFilter ff_vf_tonemap = {
346     .name            = "tonemap",
347     .description     = NULL_IF_CONFIG_SMALL("Conversion to/from different dynamic ranges."),
348     .init            = init,
349     .query_formats   = query_formats,
350     .priv_size       = sizeof(TonemapContext),
351     .priv_class      = &tonemap_class,
352     .inputs          = tonemap_inputs,
353     .outputs         = tonemap_outputs,
354 };