]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_selectivecolor.c
Merge commit '85b8403c6fd11e1c570caa970c7f435ac5f9583e'
[ffmpeg] / libavfilter / vf_selectivecolor.c
1 /*
2  * Copyright (c) 2015 Clément Bœsch <u pkh me>
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  * @todo
23  * - use integers so it can be made bitexact and a FATE test can be added
24  * - >8 bit support
25  */
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/file.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/opt.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "video.h"
35
36 enum color_range {
37     // WARNING: do NOT reorder (see parse_psfile())
38     RANGE_REDS,
39     RANGE_YELLOWS,
40     RANGE_GREENS,
41     RANGE_CYANS,
42     RANGE_BLUES,
43     RANGE_MAGENTAS,
44     RANGE_WHITES,
45     RANGE_NEUTRALS,
46     RANGE_BLACKS,
47     NB_RANGES
48 };
49
50 enum correction_method {
51     CORRECTION_METHOD_ABSOLUTE,
52     CORRECTION_METHOD_RELATIVE,
53     NB_CORRECTION_METHODS,
54 };
55
56 static const char *color_names[NB_RANGES] = {
57     "red", "yellow", "green", "cyan", "blue", "magenta", "white", "neutral", "black"
58 };
59
60 typedef int (*get_adjust_range_func)(int r, int g, int b, int min_val, int max_val);
61
62 struct process_range {
63     int range_id;
64     uint32_t mask;
65     get_adjust_range_func get_adjust_range;
66 };
67
68 typedef struct ThreadData {
69     AVFrame *in, *out;
70 } ThreadData;
71
72 typedef struct {
73     const AVClass *class;
74     int correction_method;
75     char *opt_cmyk_adjust[NB_RANGES];
76     float cmyk_adjust[NB_RANGES][4];
77     struct process_range process_ranges[NB_RANGES]; // color ranges to process
78     int nb_process_ranges;
79     char *psfile;
80 } SelectiveColorContext;
81
82 #define OFFSET(x) offsetof(SelectiveColorContext, x)
83 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
84 #define RANGE_OPTION(color_name, range) \
85     { color_name"s", "adjust "color_name" regions", OFFSET(opt_cmyk_adjust[range]), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS }
86
87 static const AVOption selectivecolor_options[] = {
88     { "correction_method", "select correction method", OFFSET(correction_method), AV_OPT_TYPE_INT, {.i64 = CORRECTION_METHOD_ABSOLUTE}, 0, NB_CORRECTION_METHODS-1, FLAGS, "correction_method" },
89         { "absolute", NULL, 0, AV_OPT_TYPE_CONST, {.i64=CORRECTION_METHOD_ABSOLUTE}, INT_MIN, INT_MAX, FLAGS, "correction_method" },
90         { "relative", NULL, 0, AV_OPT_TYPE_CONST, {.i64=CORRECTION_METHOD_RELATIVE}, INT_MIN, INT_MAX, FLAGS, "correction_method" },
91     RANGE_OPTION("red",     RANGE_REDS),
92     RANGE_OPTION("yellow",  RANGE_YELLOWS),
93     RANGE_OPTION("green",   RANGE_GREENS),
94     RANGE_OPTION("cyan",    RANGE_CYANS),
95     RANGE_OPTION("blue",    RANGE_BLUES),
96     RANGE_OPTION("magenta", RANGE_MAGENTAS),
97     RANGE_OPTION("white",   RANGE_WHITES),
98     RANGE_OPTION("neutral", RANGE_NEUTRALS),
99     RANGE_OPTION("black",   RANGE_BLACKS),
100     { "psfile", "set Photoshop selectivecolor file name", OFFSET(psfile), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
101     { NULL }
102 };
103
104 AVFILTER_DEFINE_CLASS(selectivecolor);
105
106 static inline int get_mid_val(int r, int g, int b)
107 {
108     if ((r < g && r > b) || (r < b && r > g)) return r;
109     if ((g < r && g > b) || (g < b && g > r)) return g;
110     if ((b < r && b > g) || (b < g && b > r)) return b;
111     return -1;
112 }
113
114 static int get_rgb_adjust_range(int r, int g, int b, int min_val, int max_val)
115 {
116     // max - mid
117     const int mid_val = get_mid_val(r, g, b);
118     if (mid_val == -1) {
119         // XXX: can be simplified
120         if ((r != min_val && g == min_val && b == min_val) ||
121             (r == min_val && g != min_val && b == min_val) ||
122             (r == min_val && g == min_val && b != min_val))
123             return max_val - min_val;
124         return 0;
125     }
126     return max_val - mid_val;
127 }
128
129 static int get_cmy_adjust_range(int r, int g, int b, int min_val, int max_val)
130 {
131     // mid - min
132     const int mid_val = get_mid_val(r, g, b);
133     if (mid_val == -1) {
134         // XXX: refactor with rgb
135         if ((r != max_val && g == max_val && b == max_val) ||
136             (r == max_val && g != max_val && b == max_val) ||
137             (r == max_val && g == max_val && b != max_val))
138             return max_val - min_val;
139         return 0;
140     }
141     return mid_val - min_val;
142 }
143
144 static int get_neutrals_adjust_range(int r, int g, int b, int min_val, int max_val)
145 {
146     // 1 - (|max-0.5| + |min-0.5|)
147     return (255*2 - (abs((max_val<<1) - 255) + abs((min_val<<1) - 255)) + 1) >> 1;
148 }
149
150 static int get_whites_adjust_range(int r, int g, int b, int min_val, int max_val)
151 {
152     // (min - 0.5) * 2
153     return (min_val<<1) - 255;
154 }
155
156 static int get_blacks_adjust_range(int r, int g, int b, int min_val, int max_val)
157 {
158     // (0.5 - max) * 2
159     return 255 - (max_val<<1);
160 }
161
162 static int register_range(SelectiveColorContext *s, int range_id)
163 {
164     const float *cmyk = s->cmyk_adjust[range_id];
165
166     /* If the color range has user settings, register the color range
167      * as "to be processed" */
168     if (cmyk[0] || cmyk[1] || cmyk[2] || cmyk[3]) {
169         struct process_range *pr = &s->process_ranges[s->nb_process_ranges++];
170
171         if (cmyk[0] < -1.0 || cmyk[0] > 1.0 ||
172             cmyk[1] < -1.0 || cmyk[1] > 1.0 ||
173             cmyk[2] < -1.0 || cmyk[2] > 1.0 ||
174             cmyk[3] < -1.0 || cmyk[3] > 1.0) {
175             av_log(s, AV_LOG_ERROR, "Invalid %s adjustments (%g %g %g %g). "
176                    "Settings must be set in [-1;1] range\n",
177                    color_names[range_id], cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
178             return AVERROR(EINVAL);
179         }
180
181         pr->range_id = range_id;
182         pr->mask = 1 << range_id;
183         if      (pr->mask & (1<<RANGE_REDS  | 1<<RANGE_GREENS   | 1<<RANGE_BLUES))   pr->get_adjust_range = get_rgb_adjust_range;
184         else if (pr->mask & (1<<RANGE_CYANS | 1<<RANGE_MAGENTAS | 1<<RANGE_YELLOWS)) pr->get_adjust_range = get_cmy_adjust_range;
185         else if (pr->mask & 1<<RANGE_WHITES)                                         pr->get_adjust_range = get_whites_adjust_range;
186         else if (pr->mask & 1<<RANGE_NEUTRALS)                                       pr->get_adjust_range = get_neutrals_adjust_range;
187         else if (pr->mask & 1<<RANGE_BLACKS)                                         pr->get_adjust_range = get_blacks_adjust_range;
188         else
189             av_assert0(0);
190     }
191     return 0;
192 }
193
194 static int parse_psfile(AVFilterContext *ctx, const char *fname)
195 {
196     int16_t val;
197     int ret, i, version;
198     uint8_t *buf;
199     size_t size;
200     SelectiveColorContext *s = ctx->priv;
201
202     ret = av_file_map(fname, &buf, &size, 0, NULL);
203     if (ret < 0)
204         return ret;
205
206 #define READ16(dst) do {                \
207     if (size < 2) {                     \
208         ret = AVERROR_INVALIDDATA;      \
209         goto end;                       \
210     }                                   \
211     dst = AV_RB16(buf);                 \
212     buf  += 2;                          \
213     size -= 2;                          \
214 } while (0)
215
216     READ16(version);
217     if (version != 1)
218         av_log(s, AV_LOG_WARNING, "Unsupported selective color file version %d, "
219                "the settings might not be loaded properly\n", version);
220
221     READ16(s->correction_method);
222
223     // 1st CMYK entry is reserved/unused
224     for (i = 0; i < FF_ARRAY_ELEMS(s->cmyk_adjust[0]); i++) {
225         READ16(val);
226         if (val)
227             av_log(s, AV_LOG_WARNING, "%c value of first CMYK entry is not 0 "
228                    "but %d\n", "CMYK"[i], val);
229     }
230
231     for (i = 0; i < FF_ARRAY_ELEMS(s->cmyk_adjust); i++) {
232         int k;
233         for (k = 0; k < FF_ARRAY_ELEMS(s->cmyk_adjust[0]); k++) {
234             READ16(val);
235             s->cmyk_adjust[i][k] = val / 100.;
236         }
237         ret = register_range(s, i);
238         if (ret < 0)
239             goto end;
240     }
241
242 end:
243     av_file_unmap(buf, size);
244     return ret;
245 }
246
247 static av_cold int init(AVFilterContext *ctx)
248 {
249     int i, ret;
250     SelectiveColorContext *s = ctx->priv;
251
252     /* If the following conditions are not met, it will cause trouble while
253      * parsing the PS file */
254     av_assert0(FF_ARRAY_ELEMS(s->cmyk_adjust) == 10 - 1);
255     av_assert0(FF_ARRAY_ELEMS(s->cmyk_adjust[0]) == 4);
256
257     if (s->psfile) {
258         ret = parse_psfile(ctx, s->psfile);
259         if (ret < 0)
260             return ret;
261     } else {
262         for (i = 0; i < FF_ARRAY_ELEMS(s->opt_cmyk_adjust); i++) {
263             const char *opt_cmyk_adjust = s->opt_cmyk_adjust[i];
264
265             if (opt_cmyk_adjust) {
266                 float *cmyk = s->cmyk_adjust[i];
267
268                 sscanf(s->opt_cmyk_adjust[i], "%f %f %f %f", cmyk, cmyk+1, cmyk+2, cmyk+3);
269                 ret = register_range(s, i);
270                 if (ret < 0)
271                     return ret;
272             }
273         }
274     }
275
276     av_log(s, AV_LOG_VERBOSE, "Adjustments:%s\n", s->nb_process_ranges ? "" : " none");
277     for (i = 0; i < s->nb_process_ranges; i++) {
278         const struct process_range *pr = &s->process_ranges[i];
279         const float *cmyk = s->cmyk_adjust[pr->range_id];
280
281         av_log(s, AV_LOG_VERBOSE, "%8ss: C=%6g M=%6g Y=%6g K=%6g\n",
282                color_names[pr->range_id], cmyk[0], cmyk[1], cmyk[2], cmyk[3]);
283     }
284
285     return 0;
286 }
287
288 static int query_formats(AVFilterContext *ctx)
289 {
290     static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_0RGB32, AV_PIX_FMT_NONE};
291     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
292     if (!fmts_list)
293         return AVERROR(ENOMEM);
294     return ff_set_common_formats(ctx, fmts_list);
295 }
296
297 static inline int comp_adjust(int adjust_range, float value, float adjust, float k, int correction_method)
298 {
299     const float min = -value;
300     const float max = 1. - value;
301     float res = (-1. - adjust) * k - adjust;
302     if (correction_method == CORRECTION_METHOD_RELATIVE)
303         res *= max;
304     return lrint(av_clipf(res, min, max) * adjust_range);
305 }
306
307 static inline int selective_color(AVFilterContext *ctx, ThreadData *td,
308                                   int jobnr, int nb_jobs, int direct, int correction_method)
309 {
310     int i, x, y;
311     const AVFrame *in = td->in;
312     AVFrame *out = td->out;
313     const SelectiveColorContext *s = ctx->priv;
314     const int height = in->height;
315     const int width  = in->width;
316     const int slice_start = (height *  jobnr   ) / nb_jobs;
317     const int slice_end   = (height * (jobnr+1)) / nb_jobs;
318     const int dst_linesize = out->linesize[0];
319     const int src_linesize =  in->linesize[0];
320     uint8_t       *dst = out->data[0] + slice_start * dst_linesize;
321     const uint8_t *src =  in->data[0] + slice_start * src_linesize;
322
323     for (y = slice_start; y < slice_end; y++) {
324         const uint32_t *src32 = (const uint32_t *)src;
325         uint32_t       *dst32 = (uint32_t *)dst;
326
327         for (x = 0; x < width; x++) {
328             const uint32_t color = *src32++;
329             const int r = color >> 16 & 0xff;
330             const int g = color >>  8 & 0xff;
331             const int b = color       & 0xff;
332             const int min_color = FFMIN3(r, g, b);
333             const int max_color = FFMAX3(r, g, b);
334             const uint32_t range_flag = (r == max_color) << RANGE_REDS
335                                       | (r == min_color) << RANGE_CYANS
336                                       | (g == max_color) << RANGE_GREENS
337                                       | (g == min_color) << RANGE_MAGENTAS
338                                       | (b == max_color) << RANGE_BLUES
339                                       | (b == min_color) << RANGE_YELLOWS
340                                       | (r > 128 && g > 128 && b > 128) << RANGE_WHITES
341                                       | (color && (color & 0xffffff) != 0xffffff) << RANGE_NEUTRALS
342                                       | (r < 128 && g < 128 && b < 128) << RANGE_BLACKS;
343
344             const float rnorm = r / 255.;
345             const float gnorm = g / 255.;
346             const float bnorm = b / 255.;
347             int adjust_r = 0, adjust_g = 0, adjust_b = 0;
348
349             for (i = 0; i < s->nb_process_ranges; i++) {
350                 const struct process_range *pr = &s->process_ranges[i];
351
352                 if (range_flag & pr->mask) {
353                     const int adjust_range = pr->get_adjust_range(r, g, b, min_color, max_color);
354
355                     if (adjust_range > 0) {
356                         const float *cmyk_adjust = s->cmyk_adjust[pr->range_id];
357                         const float adj_c = cmyk_adjust[0];
358                         const float adj_m = cmyk_adjust[1];
359                         const float adj_y = cmyk_adjust[2];
360                         const float k = cmyk_adjust[3];
361
362                         adjust_r += comp_adjust(adjust_range, rnorm, adj_c, k, correction_method);
363                         adjust_g += comp_adjust(adjust_range, gnorm, adj_m, k, correction_method);
364                         adjust_b += comp_adjust(adjust_range, bnorm, adj_y, k, correction_method);
365                     }
366                 }
367             }
368
369             if (!direct || adjust_r || adjust_g || adjust_b)
370                 *dst32 = (color & 0xff000000)
371                        | av_clip_uint8(r + adjust_r) << 16
372                        | av_clip_uint8(g + adjust_g) <<  8
373                        | av_clip_uint8(b + adjust_b);
374             dst32++;
375         }
376         src += src_linesize;
377         dst += dst_linesize;
378     }
379     return 0;
380 }
381
382 #define DEF_SELECTIVE_COLOR_FUNC(name, direct, correction_method)                           \
383 static int selective_color_##name(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)  \
384 {                                                                                           \
385     return selective_color(ctx, arg, jobnr, nb_jobs, direct, correction_method);            \
386 }
387
388 DEF_SELECTIVE_COLOR_FUNC(indirect_absolute, 0, CORRECTION_METHOD_ABSOLUTE)
389 DEF_SELECTIVE_COLOR_FUNC(indirect_relative, 0, CORRECTION_METHOD_RELATIVE)
390 DEF_SELECTIVE_COLOR_FUNC(  direct_absolute, 1, CORRECTION_METHOD_ABSOLUTE)
391 DEF_SELECTIVE_COLOR_FUNC(  direct_relative, 1, CORRECTION_METHOD_RELATIVE)
392
393 typedef int (*selective_color_func_type)(AVFilterContext *ctx, void *td, int jobnr, int nb_jobs);
394
395 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
396 {
397     AVFilterContext *ctx = inlink->dst;
398     AVFilterLink *outlink = ctx->outputs[0];
399     int direct;
400     AVFrame *out;
401     ThreadData td;
402     const SelectiveColorContext *s = ctx->priv;
403     static const selective_color_func_type funcs[2][2] = {
404         {selective_color_indirect_absolute, selective_color_indirect_relative},
405         {selective_color_direct_absolute,   selective_color_direct_relative},
406     };
407
408     if (av_frame_is_writable(in)) {
409         direct = 1;
410         out = in;
411     } else {
412         direct = 0;
413         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
414         if (!out) {
415             av_frame_free(&in);
416             return AVERROR(ENOMEM);
417         }
418         av_frame_copy_props(out, in);
419     }
420
421     td.in = in;
422     td.out = out;
423     ctx->internal->execute(ctx, funcs[direct][s->correction_method], &td, NULL,
424                            FFMIN(inlink->h, ctx->graph->nb_threads));
425
426     if (!direct)
427         av_frame_free(&in);
428     return ff_filter_frame(outlink, out);
429 }
430
431 static const AVFilterPad selectivecolor_inputs[] = {
432     {
433         .name         = "default",
434         .type         = AVMEDIA_TYPE_VIDEO,
435         .filter_frame = filter_frame,
436     },
437     { NULL }
438 };
439
440 static const AVFilterPad selectivecolor_outputs[] = {
441     {
442         .name = "default",
443         .type = AVMEDIA_TYPE_VIDEO,
444     },
445     { NULL }
446 };
447
448 AVFilter ff_vf_selectivecolor = {
449     .name          = "selectivecolor",
450     .description   = NULL_IF_CONFIG_SMALL("Apply CMYK adjustments to specific color ranges."),
451     .priv_size     = sizeof(SelectiveColorContext),
452     .init          = init,
453     .query_formats = query_formats,
454     .inputs        = selectivecolor_inputs,
455     .outputs       = selectivecolor_outputs,
456     .priv_class    = &selectivecolor_class,
457     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
458 };