]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_hue.c
Merge commit '54cb096ee4558b3bfc28c2fcd6418ce82dc39fe1'
[ffmpeg] / libavfilter / vf_hue.c
1 /*
2  * Copyright (c) 2003 Michael Niedermayer
3  * Copyright (c) 2012 Jeremy Tran
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 /**
23  * @file
24  * Apply a hue/saturation filter to the input video
25  * Ported from MPlayer libmpcodecs/vf_hue.c.
26  */
27
28 #include <float.h>
29 #include "libavutil/eval.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33
34 #include "avfilter.h"
35 #include "formats.h"
36 #include "internal.h"
37 #include "video.h"
38
39 #define HUE_DEFAULT_VAL 0
40 #define SAT_DEFAULT_VAL 1
41
42 #define HUE_DEFAULT_VAL_STRING AV_STRINGIFY(HUE_DEFAULT_VAL)
43 #define SAT_DEFAULT_VAL_STRING AV_STRINGIFY(SAT_DEFAULT_VAL)
44
45 #define SAT_MIN_VAL -10
46 #define SAT_MAX_VAL 10
47
48 static const char *const var_names[] = {
49     "n",   // frame count
50     "pts", // presentation timestamp expressed in AV_TIME_BASE units
51     "r",   // frame rate
52     "t",   // timestamp expressed in seconds
53     "tb",  // timebase
54     NULL
55 };
56
57 enum var_name {
58     VAR_N,
59     VAR_PTS,
60     VAR_R,
61     VAR_T,
62     VAR_TB,
63     VAR_NB
64 };
65
66 typedef struct {
67     const    AVClass *class;
68     float    hue_deg; /* hue expressed in degrees */
69     float    hue; /* hue expressed in radians */
70     char     *hue_deg_expr;
71     char     *hue_expr;
72     AVExpr   *hue_deg_pexpr;
73     AVExpr   *hue_pexpr;
74     float    saturation;
75     char     *saturation_expr;
76     AVExpr   *saturation_pexpr;
77     int      hsub;
78     int      vsub;
79     int32_t hue_sin;
80     int32_t hue_cos;
81     int      flat_syntax;
82     double   var_values[VAR_NB];
83 } HueContext;
84
85 #define OFFSET(x) offsetof(HueContext, x)
86 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
87 static const AVOption hue_options[] = {
88     { "h", "set the hue angle degrees expression", OFFSET(hue_deg_expr), AV_OPT_TYPE_STRING,
89       { .str = NULL }, .flags = FLAGS },
90     { "H", "set the hue angle radians expression", OFFSET(hue_expr), AV_OPT_TYPE_STRING,
91       { .str = NULL }, .flags = FLAGS },
92     { "s", "set the saturation expression", OFFSET(saturation_expr), AV_OPT_TYPE_STRING,
93       { .str = NULL }, .flags = FLAGS },
94     { NULL }
95 };
96
97 AVFILTER_DEFINE_CLASS(hue);
98
99 static inline void compute_sin_and_cos(HueContext *hue)
100 {
101     /*
102      * Scale the value to the norm of the resulting (U,V) vector, that is
103      * the saturation.
104      * This will be useful in the process_chrominance function.
105      */
106     hue->hue_sin = rint(sin(hue->hue) * (1 << 16) * hue->saturation);
107     hue->hue_cos = rint(cos(hue->hue) * (1 << 16) * hue->saturation);
108 }
109
110 #define SET_EXPRESSION(attr, name) do {                                           \
111     if (hue->attr##_expr) {                                                       \
112         if ((ret = av_expr_parse(&hue->attr##_pexpr, hue->attr##_expr, var_names, \
113                                  NULL, NULL, NULL, NULL, 0, ctx)) < 0) {          \
114             av_log(ctx, AV_LOG_ERROR,                                             \
115                    "Parsing failed for expression " #name "='%s'",                \
116                    hue->attr##_expr);                                             \
117             hue->attr##_expr  = old_##attr##_expr;                                \
118             hue->attr##_pexpr = old_##attr##_pexpr;                               \
119             return AVERROR(EINVAL);                                               \
120         } else if (old_##attr##_pexpr) {                                          \
121             av_freep(&old_##attr##_expr);                                         \
122             av_expr_free(old_##attr##_pexpr);                                     \
123             old_##attr##_pexpr = NULL;                                            \
124         }                                                                         \
125     } else {                                                                      \
126         hue->attr##_expr = old_##attr##_expr;                                     \
127     }                                                                             \
128 } while (0)
129
130 static inline int set_options(AVFilterContext *ctx, const char *args)
131 {
132     HueContext *hue = ctx->priv;
133     int n, ret;
134     char c1 = 0, c2 = 0;
135     char   *old_hue_expr,  *old_hue_deg_expr,  *old_saturation_expr;
136     AVExpr *old_hue_pexpr, *old_hue_deg_pexpr, *old_saturation_pexpr;
137
138     if (args) {
139         /* named options syntax */
140         if (strchr(args, '=')) {
141             old_hue_expr        = hue->hue_expr;
142             old_hue_deg_expr    = hue->hue_deg_expr;
143             old_saturation_expr = hue->saturation_expr;
144
145             old_hue_pexpr        = hue->hue_pexpr;
146             old_hue_deg_pexpr    = hue->hue_deg_pexpr;
147             old_saturation_pexpr = hue->saturation_pexpr;
148
149             hue->hue_expr     = NULL;
150             hue->hue_deg_expr = NULL;
151             hue->saturation_expr = NULL;
152
153             if ((ret = av_set_options_string(hue, args, "=", ":")) < 0)
154                 return ret;
155             if (hue->hue_expr && hue->hue_deg_expr) {
156                 av_log(ctx, AV_LOG_ERROR,
157                        "H and h options are incompatible and cannot be specified "
158                        "at the same time\n");
159                 hue->hue_expr     = old_hue_expr;
160                 hue->hue_deg_expr = old_hue_deg_expr;
161
162                 return AVERROR(EINVAL);
163             }
164
165             SET_EXPRESSION(hue_deg, h);
166             SET_EXPRESSION(hue, H);
167             SET_EXPRESSION(saturation, s);
168
169             hue->flat_syntax = 0;
170
171             av_log(ctx, AV_LOG_VERBOSE,
172                    "H_expr:%s h_deg_expr:%s s_expr:%s\n",
173                    hue->hue_expr, hue->hue_deg_expr, hue->saturation_expr);
174
175         /* compatibility h:s syntax */
176         } else {
177             n = sscanf(args, "%f%c%f%c", &hue->hue_deg, &c1, &hue->saturation, &c2);
178             if (n != 1 && (n != 3 || c1 != ':')) {
179                 av_log(ctx, AV_LOG_ERROR,
180                        "Invalid syntax for argument '%s': "
181                        "must be in the form 'hue[:saturation]'\n", args);
182                 return AVERROR(EINVAL);
183             }
184
185             if (hue->saturation < SAT_MIN_VAL || hue->saturation > SAT_MAX_VAL) {
186                 av_log(ctx, AV_LOG_ERROR,
187                        "Invalid value for saturation %0.1f: "
188                        "must be included between range %d and +%d\n",
189                        hue->saturation, SAT_MIN_VAL, SAT_MAX_VAL);
190                 return AVERROR(EINVAL);
191             }
192
193             hue->hue = hue->hue_deg * M_PI / 180;
194             hue->flat_syntax = 1;
195
196             av_log(ctx, AV_LOG_VERBOSE,
197                    "H:%0.1f h:%0.1f s:%0.1f\n",
198                    hue->hue, hue->hue_deg, hue->saturation);
199         }
200     }
201
202     compute_sin_and_cos(hue);
203
204     return 0;
205 }
206
207 static av_cold int init(AVFilterContext *ctx, const char *args)
208 {
209     HueContext *hue = ctx->priv;
210
211     hue->class = &hue_class;
212     av_opt_set_defaults(hue);
213
214     hue->saturation    = SAT_DEFAULT_VAL;
215     hue->hue           = HUE_DEFAULT_VAL;
216     hue->hue_deg_pexpr = NULL;
217     hue->hue_pexpr     = NULL;
218     hue->flat_syntax   = 1;
219
220     return set_options(ctx, args);
221 }
222
223 static av_cold void uninit(AVFilterContext *ctx)
224 {
225     HueContext *hue = ctx->priv;
226
227     av_opt_free(hue);
228
229     av_free(hue->hue_deg_expr);
230     av_expr_free(hue->hue_deg_pexpr);
231     av_free(hue->hue_expr);
232     av_expr_free(hue->hue_pexpr);
233     av_free(hue->saturation_expr);
234     av_expr_free(hue->saturation_pexpr);
235 }
236
237 static int query_formats(AVFilterContext *ctx)
238 {
239     static const enum AVPixelFormat pix_fmts[] = {
240         AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
241         AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
242         AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
243         AV_PIX_FMT_YUVA420P,
244         AV_PIX_FMT_NONE
245     };
246
247     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
248
249     return 0;
250 }
251
252 static int config_props(AVFilterLink *inlink)
253 {
254     HueContext *hue = inlink->dst->priv;
255     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
256
257     hue->hsub = desc->log2_chroma_w;
258     hue->vsub = desc->log2_chroma_h;
259
260     hue->var_values[VAR_N]  = 0;
261     hue->var_values[VAR_TB] = av_q2d(inlink->time_base);
262     hue->var_values[VAR_R]  = inlink->frame_rate.num == 0 || inlink->frame_rate.den == 0 ?
263         NAN : av_q2d(inlink->frame_rate);
264
265     return 0;
266 }
267
268 static void process_chrominance(uint8_t *udst, uint8_t *vdst, const int dst_linesize,
269                                 uint8_t *usrc, uint8_t *vsrc, const int src_linesize,
270                                 int w, int h,
271                                 const int32_t c, const int32_t s)
272 {
273     int32_t u, v, new_u, new_v;
274     int i;
275
276     /*
277      * If we consider U and V as the components of a 2D vector then its angle
278      * is the hue and the norm is the saturation
279      */
280     while (h--) {
281         for (i = 0; i < w; i++) {
282             /* Normalize the components from range [16;140] to [-112;112] */
283             u = usrc[i] - 128;
284             v = vsrc[i] - 128;
285             /*
286              * Apply the rotation of the vector : (c * u) - (s * v)
287              *                                    (s * u) + (c * v)
288              * De-normalize the components (without forgetting to scale 128
289              * by << 16)
290              * Finally scale back the result by >> 16
291              */
292             new_u = ((c * u) - (s * v) + (1 << 15) + (128 << 16)) >> 16;
293             new_v = ((s * u) + (c * v) + (1 << 15) + (128 << 16)) >> 16;
294
295             /* Prevent a potential overflow */
296             udst[i] = av_clip_uint8_c(new_u);
297             vdst[i] = av_clip_uint8_c(new_v);
298         }
299
300         usrc += src_linesize;
301         vsrc += src_linesize;
302         udst += dst_linesize;
303         vdst += dst_linesize;
304     }
305 }
306
307 #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
308 #define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts) * av_q2d(tb))
309
310 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpic)
311 {
312     HueContext *hue = inlink->dst->priv;
313     AVFilterLink *outlink = inlink->dst->outputs[0];
314     AVFilterBufferRef *outpic;
315
316     outpic = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
317     if (!outpic) {
318         avfilter_unref_bufferp(&inpic);
319         return AVERROR(ENOMEM);
320     }
321     avfilter_copy_buffer_ref_props(outpic, inpic);
322
323     if (!hue->flat_syntax) {
324         hue->var_values[VAR_T]   = TS2T(inpic->pts, inlink->time_base);
325         hue->var_values[VAR_PTS] = TS2D(inpic->pts);
326
327         if (hue->saturation_expr) {
328             hue->saturation = av_expr_eval(hue->saturation_pexpr, hue->var_values, NULL);
329
330             if (hue->saturation < SAT_MIN_VAL || hue->saturation > SAT_MAX_VAL) {
331                 hue->saturation = av_clip(hue->saturation, SAT_MIN_VAL, SAT_MAX_VAL);
332                 av_log(inlink->dst, AV_LOG_WARNING,
333                        "Saturation value not in range [%d,%d]: clipping value to %0.1f\n",
334                        SAT_MIN_VAL, SAT_MAX_VAL, hue->saturation);
335             }
336         }
337
338         if (hue->hue_deg_expr) {
339             hue->hue_deg = av_expr_eval(hue->hue_deg_pexpr, hue->var_values, NULL);
340             hue->hue = hue->hue_deg * M_PI / 180;
341         } else if (hue->hue_expr) {
342             hue->hue = av_expr_eval(hue->hue_pexpr, hue->var_values, NULL);
343         }
344
345         av_log(inlink->dst, AV_LOG_DEBUG,
346                "H:%0.1f s:%0.f t:%0.1f n:%d\n",
347                hue->hue, hue->saturation,
348                hue->var_values[VAR_T], (int)hue->var_values[VAR_N]);
349
350         compute_sin_and_cos(hue);
351     }
352
353     hue->var_values[VAR_N] += 1;
354
355     av_image_copy_plane(outpic->data[0], outpic->linesize[0],
356                         inpic->data[0],  inpic->linesize[0],
357                         inlink->w, inlink->h);
358
359     process_chrominance(outpic->data[1], outpic->data[2], outpic->linesize[1],
360                         inpic->data[1],  inpic->data[2],  inpic->linesize[1],
361                         inlink->w >> hue->hsub, inlink->h >> hue->vsub,
362                         hue->hue_cos, hue->hue_sin);
363
364     avfilter_unref_bufferp(&inpic);
365     return ff_filter_frame(outlink, outpic);
366 }
367
368 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
369                            char *res, int res_len, int flags)
370 {
371     if (!strcmp(cmd, "reinit"))
372         return set_options(ctx, args);
373     else
374         return AVERROR(ENOSYS);
375 }
376
377 static const AVFilterPad hue_inputs[] = {
378     {
379         .name         = "default",
380         .type         = AVMEDIA_TYPE_VIDEO,
381         .filter_frame = filter_frame,
382         .config_props = config_props,
383         .min_perms    = AV_PERM_READ,
384     },
385     { NULL }
386 };
387
388 static const AVFilterPad hue_outputs[] = {
389     {
390         .name = "default",
391         .type = AVMEDIA_TYPE_VIDEO,
392     },
393     { NULL }
394 };
395
396 AVFilter avfilter_vf_hue = {
397     .name        = "hue",
398     .description = NULL_IF_CONFIG_SMALL("Adjust the hue and saturation of the input video."),
399
400     .priv_size = sizeof(HueContext),
401
402     .init          = init,
403     .uninit        = uninit,
404     .query_formats = query_formats,
405     .process_command = process_command,
406     .inputs          = hue_inputs,
407     .outputs         = hue_outputs,
408     .priv_class      = &hue_class,
409 };