]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_colorspace.c
avfilter/vf_colorspace: fix range for output colorspace option
[ffmpeg] / libavfilter / vf_colorspace.c
1 /*
2  * Copyright (c) 2016 Ronald S. Bultje <rsbultje@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  * Convert between colorspaces.
24  */
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/pixfmt.h"
30
31 #include "avfilter.h"
32 #include "colorspacedsp.h"
33 #include "formats.h"
34 #include "internal.h"
35 #include "video.h"
36
37 enum DitherMode {
38     DITHER_NONE,
39     DITHER_FSB,
40     DITHER_NB,
41 };
42
43 enum Colorspace {
44     CS_UNSPECIFIED,
45     CS_BT470M,
46     CS_BT470BG,
47     CS_BT601_6_525,
48     CS_BT601_6_625,
49     CS_BT709,
50     CS_SMPTE170M,
51     CS_SMPTE240M,
52     CS_BT2020,
53     CS_NB,
54 };
55
56 enum Whitepoint {
57     WP_D65,
58     WP_C,
59     WP_NB,
60 };
61
62 enum WhitepointAdaptation {
63     WP_ADAPT_BRADFORD,
64     WP_ADAPT_VON_KRIES,
65     NB_WP_ADAPT_NON_IDENTITY,
66     WP_ADAPT_IDENTITY = NB_WP_ADAPT_NON_IDENTITY,
67     NB_WP_ADAPT,
68 };
69
70 static const enum AVColorTransferCharacteristic default_trc[CS_NB + 1] = {
71     [CS_UNSPECIFIED] = AVCOL_TRC_UNSPECIFIED,
72     [CS_BT470M]      = AVCOL_TRC_GAMMA22,
73     [CS_BT470BG]     = AVCOL_TRC_GAMMA28,
74     [CS_BT601_6_525] = AVCOL_TRC_SMPTE170M,
75     [CS_BT601_6_625] = AVCOL_TRC_SMPTE170M,
76     [CS_BT709]       = AVCOL_TRC_BT709,
77     [CS_SMPTE170M]   = AVCOL_TRC_SMPTE170M,
78     [CS_SMPTE240M]   = AVCOL_TRC_SMPTE240M,
79     [CS_BT2020]      = AVCOL_TRC_BT2020_10,
80     [CS_NB]          = AVCOL_TRC_UNSPECIFIED,
81 };
82
83 static const enum AVColorPrimaries default_prm[CS_NB + 1] = {
84     [CS_UNSPECIFIED] = AVCOL_PRI_UNSPECIFIED,
85     [CS_BT470M]      = AVCOL_PRI_BT470M,
86     [CS_BT470BG]     = AVCOL_PRI_BT470BG,
87     [CS_BT601_6_525] = AVCOL_PRI_SMPTE170M,
88     [CS_BT601_6_625] = AVCOL_PRI_BT470BG,
89     [CS_BT709]       = AVCOL_PRI_BT709,
90     [CS_SMPTE170M]   = AVCOL_PRI_SMPTE170M,
91     [CS_SMPTE240M]   = AVCOL_PRI_SMPTE240M,
92     [CS_BT2020]      = AVCOL_PRI_BT2020,
93     [CS_NB]          = AVCOL_PRI_UNSPECIFIED,
94 };
95
96 static const enum AVColorSpace default_csp[CS_NB + 1] = {
97     [CS_UNSPECIFIED] = AVCOL_SPC_UNSPECIFIED,
98     [CS_BT470M]      = AVCOL_SPC_SMPTE170M,
99     [CS_BT470BG]     = AVCOL_SPC_BT470BG,
100     [CS_BT601_6_525] = AVCOL_SPC_SMPTE170M,
101     [CS_BT601_6_625] = AVCOL_SPC_BT470BG,
102     [CS_BT709]       = AVCOL_SPC_BT709,
103     [CS_SMPTE170M]   = AVCOL_SPC_SMPTE170M,
104     [CS_SMPTE240M]   = AVCOL_SPC_SMPTE240M,
105     [CS_BT2020]      = AVCOL_SPC_BT2020_NCL,
106     [CS_NB]          = AVCOL_SPC_UNSPECIFIED,
107 };
108
109 struct ColorPrimaries {
110     enum Whitepoint wp;
111     double xr, yr, xg, yg, xb, yb;
112 };
113
114 struct TransferCharacteristics {
115     double alpha, beta, gamma, delta;
116 };
117
118 struct LumaCoefficients {
119     double cr, cg, cb;
120 };
121
122 struct WhitepointCoefficients {
123     double xw, yw;
124 };
125
126 typedef struct ColorSpaceContext {
127     const AVClass *class;
128
129     ColorSpaceDSPContext dsp;
130
131     enum Colorspace user_all, user_iall;
132     enum AVColorSpace in_csp, out_csp, user_csp, user_icsp;
133     enum AVColorRange in_rng, out_rng, user_rng, user_irng;
134     enum AVColorTransferCharacteristic in_trc, out_trc, user_trc, user_itrc;
135     enum AVColorPrimaries in_prm, out_prm, user_prm, user_iprm;
136     enum AVPixelFormat in_format, user_format;
137     int fast_mode;
138     enum DitherMode dither;
139     enum WhitepointAdaptation wp_adapt;
140
141     int16_t *rgb[3];
142     ptrdiff_t rgb_stride;
143     unsigned rgb_sz;
144     int *dither_scratch[3][2], *dither_scratch_base[3][2];
145
146     const struct ColorPrimaries *in_primaries, *out_primaries;
147     int lrgb2lrgb_passthrough;
148     DECLARE_ALIGNED(16, int16_t, lrgb2lrgb_coeffs)[3][3][8];
149
150     const struct TransferCharacteristics *in_txchr, *out_txchr;
151     int rgb2rgb_passthrough;
152     int16_t *lin_lut, *delin_lut;
153
154     const struct LumaCoefficients *in_lumacoef, *out_lumacoef;
155     int yuv2yuv_passthrough, yuv2yuv_fastmode;
156     DECLARE_ALIGNED(16, int16_t, yuv2rgb_coeffs)[3][3][8];
157     DECLARE_ALIGNED(16, int16_t, rgb2yuv_coeffs)[3][3][8];
158     DECLARE_ALIGNED(16, int16_t, yuv2yuv_coeffs)[3][3][8];
159     DECLARE_ALIGNED(16, int16_t, yuv_offset)[2 /* in, out */][8];
160     yuv2rgb_fn yuv2rgb;
161     rgb2yuv_fn rgb2yuv;
162     rgb2yuv_fsb_fn rgb2yuv_fsb;
163     yuv2yuv_fn yuv2yuv;
164     double yuv2rgb_dbl_coeffs[3][3], rgb2yuv_dbl_coeffs[3][3];
165     int in_y_rng, in_uv_rng, out_y_rng, out_uv_rng;
166 } ColorSpaceContext;
167
168 // FIXME deal with odd width/heights (or just forbid it)
169 // FIXME faster linearize/delinearize implementation (integer pow)
170 // FIXME bt2020cl support (linearization between yuv/rgb step instead of between rgb/xyz)
171 // FIXME test that the values in (de)lin_lut don't exceed their container storage
172 // type size (only useful if we keep the LUT and don't move to fast integer pow)
173 // FIXME dithering if bitdepth goes down?
174 // FIXME bitexact for fate integration?
175
176 /*
177  * All constants explained in e.g. https://linuxtv.org/downloads/v4l-dvb-apis/ch02s06.html
178  * The older ones (bt470bg/m) are also explained in their respective ITU docs
179  * (e.g. https://www.itu.int/dms_pubrec/itu-r/rec/bt/R-REC-BT.470-5-199802-S!!PDF-E.pdf)
180  * whereas the newer ones can typically be copied directly from wikipedia :)
181  */
182 static const struct LumaCoefficients luma_coefficients[AVCOL_SPC_NB] = {
183     [AVCOL_SPC_FCC]        = { 0.30,   0.59,   0.11   },
184     [AVCOL_SPC_BT470BG]    = { 0.299,  0.587,  0.114  },
185     [AVCOL_SPC_SMPTE170M]  = { 0.299,  0.587,  0.114  },
186     [AVCOL_SPC_BT709]      = { 0.2126, 0.7152, 0.0722 },
187     [AVCOL_SPC_SMPTE240M]  = { 0.212,  0.701,  0.087  },
188     [AVCOL_SPC_BT2020_NCL] = { 0.2627, 0.6780, 0.0593 },
189     [AVCOL_SPC_BT2020_CL]  = { 0.2627, 0.6780, 0.0593 },
190 };
191
192 static const struct LumaCoefficients *get_luma_coefficients(enum AVColorSpace csp)
193 {
194     const struct LumaCoefficients *coeffs;
195
196     if (csp >= AVCOL_SPC_NB)
197         return NULL;
198     coeffs = &luma_coefficients[csp];
199     if (!coeffs->cr)
200         return NULL;
201
202     return coeffs;
203 }
204
205 static void fill_rgb2yuv_table(const struct LumaCoefficients *coeffs,
206                                double rgb2yuv[3][3])
207 {
208     double bscale, rscale;
209
210     rgb2yuv[0][0] = coeffs->cr;
211     rgb2yuv[0][1] = coeffs->cg;
212     rgb2yuv[0][2] = coeffs->cb;
213     bscale = 0.5 / (coeffs->cb - 1.0);
214     rscale = 0.5 / (coeffs->cr - 1.0);
215     rgb2yuv[1][0] = bscale * coeffs->cr;
216     rgb2yuv[1][1] = bscale * coeffs->cg;
217     rgb2yuv[1][2] = 0.5;
218     rgb2yuv[2][0] = 0.5;
219     rgb2yuv[2][1] = rscale * coeffs->cg;
220     rgb2yuv[2][2] = rscale * coeffs->cb;
221 }
222
223 // FIXME I'm pretty sure gamma22/28 also have a linear toe slope, but I can't
224 // find any actual tables that document their real values...
225 // See http://www.13thmonkey.org/~boris/gammacorrection/ first graph why it matters
226 static const struct TransferCharacteristics transfer_characteristics[AVCOL_TRC_NB] = {
227     [AVCOL_TRC_BT709]     = { 1.099,  0.018,  0.45, 4.5 },
228     [AVCOL_TRC_GAMMA22]   = { 1.0,    0.0,    1.0 / 2.2, 0.0 },
229     [AVCOL_TRC_GAMMA28]   = { 1.0,    0.0,    1.0 / 2.8, 0.0 },
230     [AVCOL_TRC_SMPTE170M] = { 1.099,  0.018,  0.45, 4.5 },
231     [AVCOL_TRC_SMPTE240M] = { 1.1115, 0.0228, 0.45, 4.0 },
232     [AVCOL_TRC_BT2020_10] = { 1.099,  0.018,  0.45, 4.5 },
233     [AVCOL_TRC_BT2020_12] = { 1.0993, 0.0181, 0.45, 4.5 },
234 };
235
236 static const struct TransferCharacteristics *
237     get_transfer_characteristics(enum AVColorTransferCharacteristic trc)
238 {
239     const struct TransferCharacteristics *coeffs;
240
241     if (trc >= AVCOL_TRC_NB)
242         return NULL;
243     coeffs = &transfer_characteristics[trc];
244     if (!coeffs->alpha)
245         return NULL;
246
247     return coeffs;
248 }
249
250 static const struct WhitepointCoefficients whitepoint_coefficients[WP_NB] = {
251     [WP_D65] = { 0.3127, 0.3290 },
252     [WP_C]   = { 0.3100, 0.3160 },
253 };
254
255 static const struct ColorPrimaries color_primaries[AVCOL_PRI_NB] = {
256     [AVCOL_PRI_BT709]     = { WP_D65, 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 },
257     [AVCOL_PRI_BT470M]    = { WP_C,   0.670, 0.330, 0.210, 0.710, 0.140, 0.080 },
258     [AVCOL_PRI_BT470BG]   = { WP_D65, 0.640, 0.330, 0.290, 0.600, 0.150, 0.060,},
259     [AVCOL_PRI_SMPTE170M] = { WP_D65, 0.630, 0.340, 0.310, 0.595, 0.155, 0.070 },
260     [AVCOL_PRI_SMPTE240M] = { WP_D65, 0.630, 0.340, 0.310, 0.595, 0.155, 0.070 },
261     [AVCOL_PRI_BT2020]    = { WP_D65, 0.708, 0.292, 0.170, 0.797, 0.131, 0.046 },
262 };
263
264 static const struct ColorPrimaries *get_color_primaries(enum AVColorPrimaries prm)
265 {
266     const struct ColorPrimaries *coeffs;
267
268     if (prm >= AVCOL_PRI_NB)
269         return NULL;
270     coeffs = &color_primaries[prm];
271     if (!coeffs->xr)
272         return NULL;
273
274     return coeffs;
275 }
276
277 static void invert_matrix3x3(const double in[3][3], double out[3][3])
278 {
279     double m00 = in[0][0], m01 = in[0][1], m02 = in[0][2],
280            m10 = in[1][0], m11 = in[1][1], m12 = in[1][2],
281            m20 = in[2][0], m21 = in[2][1], m22 = in[2][2];
282     int i, j;
283     double det;
284
285     out[0][0] =  (m11 * m22 - m21 * m12);
286     out[0][1] = -(m01 * m22 - m21 * m02);
287     out[0][2] =  (m01 * m12 - m11 * m02);
288     out[1][0] = -(m10 * m22 - m20 * m12);
289     out[1][1] =  (m00 * m22 - m20 * m02);
290     out[1][2] = -(m00 * m12 - m10 * m02);
291     out[2][0] =  (m10 * m21 - m20 * m11);
292     out[2][1] = -(m00 * m21 - m20 * m01);
293     out[2][2] =  (m00 * m11 - m10 * m01);
294
295     det = m00 * out[0][0] + m10 * out[0][1] + m20 * out[0][2];
296     det = 1.0 / det;
297
298     for (i = 0; i < 3; i++) {
299         for (j = 0; j < 3; j++)
300             out[i][j] *= det;
301     }
302 }
303
304 static int fill_gamma_table(ColorSpaceContext *s)
305 {
306     int n;
307     double in_alpha = s->in_txchr->alpha, in_beta = s->in_txchr->beta;
308     double in_gamma = s->in_txchr->gamma, in_delta = s->in_txchr->delta;
309     double in_ialpha = 1.0 / in_alpha, in_igamma = 1.0 / in_gamma, in_idelta = 1.0 / in_delta;
310     double out_alpha = s->out_txchr->alpha, out_beta = s->out_txchr->beta;
311     double out_gamma = s->out_txchr->gamma, out_delta = s->out_txchr->delta;
312
313     s->lin_lut = av_malloc(sizeof(*s->lin_lut) * 32768 * 2);
314     if (!s->lin_lut)
315         return AVERROR(ENOMEM);
316     s->delin_lut = &s->lin_lut[32768];
317     for (n = 0; n < 32768; n++) {
318         double v = (n - 2048.0) / 28672.0, d, l;
319
320         // delinearize
321         if (v <= -out_beta) {
322             d = -out_alpha * pow(-v, out_gamma) + (out_alpha - 1.0);
323         } else if (v < out_beta) {
324             d = out_delta * v;
325         } else {
326             d = out_alpha * pow(v, out_gamma) - (out_alpha - 1.0);
327         }
328         s->delin_lut[n] = av_clip_int16(lrint(d * 28672.0));
329
330         // linearize
331         if (v <= -in_beta) {
332             l = -pow((1.0 - in_alpha - v) * in_ialpha, in_igamma);
333         } else if (v < in_beta) {
334             l = v * in_idelta;
335         } else {
336             l = pow((v + in_alpha - 1.0) * in_ialpha, in_igamma);
337         }
338         s->lin_lut[n] = av_clip_int16(lrint(l * 28672.0));
339     }
340
341     return 0;
342 }
343
344 /*
345  * see e.g. http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
346  */
347 static void fill_rgb2xyz_table(const struct ColorPrimaries *coeffs,
348                                double rgb2xyz[3][3])
349 {
350     const struct WhitepointCoefficients *wp = &whitepoint_coefficients[coeffs->wp];
351     double i[3][3], sr, sg, sb, zw;
352
353     rgb2xyz[0][0] = coeffs->xr / coeffs->yr;
354     rgb2xyz[0][1] = coeffs->xg / coeffs->yg;
355     rgb2xyz[0][2] = coeffs->xb / coeffs->yb;
356     rgb2xyz[1][0] = rgb2xyz[1][1] = rgb2xyz[1][2] = 1.0;
357     rgb2xyz[2][0] = (1.0 - coeffs->xr - coeffs->yr) / coeffs->yr;
358     rgb2xyz[2][1] = (1.0 - coeffs->xg - coeffs->yg) / coeffs->yg;
359     rgb2xyz[2][2] = (1.0 - coeffs->xb - coeffs->yb) / coeffs->yb;
360     invert_matrix3x3(rgb2xyz, i);
361     zw = 1.0 - wp->xw - wp->yw;
362     sr = i[0][0] * wp->xw + i[0][1] * wp->yw + i[0][2] * zw;
363     sg = i[1][0] * wp->xw + i[1][1] * wp->yw + i[1][2] * zw;
364     sb = i[2][0] * wp->xw + i[2][1] * wp->yw + i[2][2] * zw;
365     rgb2xyz[0][0] *= sr;
366     rgb2xyz[0][1] *= sg;
367     rgb2xyz[0][2] *= sb;
368     rgb2xyz[1][0] *= sr;
369     rgb2xyz[1][1] *= sg;
370     rgb2xyz[1][2] *= sb;
371     rgb2xyz[2][0] *= sr;
372     rgb2xyz[2][1] *= sg;
373     rgb2xyz[2][2] *= sb;
374 }
375
376 static void mul3x3(double dst[3][3], const double src1[3][3], const double src2[3][3])
377 {
378     int m, n;
379
380     for (m = 0; m < 3; m++)
381         for (n = 0; n < 3; n++)
382             dst[m][n] = src2[m][0] * src1[0][n] +
383                         src2[m][1] * src1[1][n] +
384                         src2[m][2] * src1[2][n];
385 }
386
387 /*
388  * See http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
389  * This function uses the Bradford mechanism.
390  */
391 static void fill_whitepoint_conv_table(double out[3][3], enum WhitepointAdaptation wp_adapt,
392                                        enum Whitepoint src, enum Whitepoint dst)
393 {
394     static const double ma_tbl[NB_WP_ADAPT_NON_IDENTITY][3][3] = {
395         [WP_ADAPT_BRADFORD] = {
396             {  0.8951,  0.2664, -0.1614 },
397             { -0.7502,  1.7135,  0.0367 },
398             {  0.0389, -0.0685,  1.0296 },
399         }, [WP_ADAPT_VON_KRIES] = {
400             {  0.40024,  0.70760, -0.08081 },
401             { -0.22630,  1.16532,  0.04570 },
402             {  0.00000,  0.00000,  0.91822 },
403         },
404     };
405     const double (*ma)[3] = ma_tbl[wp_adapt];
406     const struct WhitepointCoefficients *wp_src = &whitepoint_coefficients[src];
407     double zw_src = 1.0 - wp_src->xw - wp_src->yw;
408     const struct WhitepointCoefficients *wp_dst = &whitepoint_coefficients[dst];
409     double zw_dst = 1.0 - wp_dst->xw - wp_dst->yw;
410     double mai[3][3], fac[3][3], tmp[3][3];
411     double rs, gs, bs, rd, gd, bd;
412
413     invert_matrix3x3(ma, mai);
414     rs = ma[0][0] * wp_src->xw + ma[0][1] * wp_src->yw + ma[0][2] * zw_src;
415     gs = ma[1][0] * wp_src->xw + ma[1][1] * wp_src->yw + ma[1][2] * zw_src;
416     bs = ma[2][0] * wp_src->xw + ma[2][1] * wp_src->yw + ma[2][2] * zw_src;
417     rd = ma[0][0] * wp_dst->xw + ma[0][1] * wp_dst->yw + ma[0][2] * zw_dst;
418     gd = ma[1][0] * wp_dst->xw + ma[1][1] * wp_dst->yw + ma[1][2] * zw_dst;
419     bd = ma[2][0] * wp_dst->xw + ma[2][1] * wp_dst->yw + ma[2][2] * zw_dst;
420     fac[0][0] = rd / rs;
421     fac[1][1] = gd / gs;
422     fac[2][2] = bd / bs;
423     fac[0][1] = fac[0][2] = fac[1][0] = fac[1][2] = fac[2][0] = fac[2][1] = 0.0;
424     mul3x3(tmp, ma, fac);
425     mul3x3(out, tmp, mai);
426 }
427
428 static void apply_lut(int16_t *buf[3], ptrdiff_t stride,
429                       int w, int h, const int16_t *lut)
430 {
431     int y, x, n;
432
433     for (n = 0; n < 3; n++) {
434         int16_t *data = buf[n];
435
436         for (y = 0; y < h; y++) {
437             for (x = 0; x < w; x++)
438                 data[x] = lut[av_clip_uintp2(2048 + data[x], 15)];
439
440             data += stride;
441         }
442     }
443 }
444
445 struct ThreadData {
446     AVFrame *in, *out;
447     ptrdiff_t in_linesize[3], out_linesize[3];
448     int in_ss_h, out_ss_h;
449 };
450
451 static int convert(AVFilterContext *ctx, void *data, int job_nr, int n_jobs)
452 {
453     struct ThreadData *td = data;
454     ColorSpaceContext *s = ctx->priv;
455     uint8_t *in_data[3], *out_data[3];
456     int16_t *rgb[3];
457     int h_in = (td->in->height + 1) >> 1;
458     int h1 = 2 * (job_nr * h_in / n_jobs), h2 = 2 * ((job_nr + 1) * h_in / n_jobs);
459     int w = td->in->width, h = h2 - h1;
460
461     in_data[0]  = td->in->data[0]  + td->in_linesize[0]  *  h1;
462     in_data[1]  = td->in->data[1]  + td->in_linesize[1]  * (h1 >> td->in_ss_h);
463     in_data[2]  = td->in->data[2]  + td->in_linesize[2]  * (h1 >> td->in_ss_h);
464     out_data[0] = td->out->data[0] + td->out_linesize[0] *  h1;
465     out_data[1] = td->out->data[1] + td->out_linesize[1] * (h1 >> td->out_ss_h);
466     out_data[2] = td->out->data[2] + td->out_linesize[2] * (h1 >> td->out_ss_h);
467     rgb[0]      = s->rgb[0]        + s->rgb_stride       *  h1;
468     rgb[1]      = s->rgb[1]        + s->rgb_stride       *  h1;
469     rgb[2]      = s->rgb[2]        + s->rgb_stride       *  h1;
470
471     // FIXME for simd, also make sure we do pictures with negative stride
472     // top-down so we don't overwrite lines with padding of data before it
473     // in the same buffer (same as swscale)
474
475     if (s->yuv2yuv_fastmode) {
476         // FIXME possibly use a fast mode in case only the y range changes?
477         // since in that case, only the diagonal entries in yuv2yuv_coeffs[]
478         // are non-zero
479         s->yuv2yuv(out_data, td->out_linesize, in_data, td->in_linesize, w, h,
480                    s->yuv2yuv_coeffs, s->yuv_offset);
481     } else {
482         // FIXME maybe (for caching effciency) do pipeline per-line instead of
483         // full buffer per function? (Or, since yuv2rgb requires 2 lines: per
484         // 2 lines, for yuv420.)
485         /*
486          * General design:
487          * - yuv2rgb converts from whatever range the input was ([16-235/240] or
488          *   [0,255] or the 10/12bpp equivalents thereof) to an integer version
489          *   of RGB in psuedo-restricted 15+sign bits. That means that the float
490          *   range [0.0,1.0] is in [0,28762], and the remainder of the int16_t
491          *   range is used for overflow/underflow outside the representable
492          *   range of this RGB type. rgb2yuv is the exact opposite.
493          * - gamma correction is done using a LUT since that appears to work
494          *   fairly fast.
495          * - If the input is chroma-subsampled (420/422), the yuv2rgb conversion
496          *   (or rgb2yuv conversion) uses nearest-neighbour sampling to read
497          *   read chroma pixels at luma resolution. If you want some more fancy
498          *   filter, you can use swscale to convert to yuv444p.
499          * - all coefficients are 14bit (so in the [-2.0,2.0] range).
500          */
501         s->yuv2rgb(rgb, s->rgb_stride, in_data, td->in_linesize, w, h,
502                    s->yuv2rgb_coeffs, s->yuv_offset[0]);
503         if (!s->rgb2rgb_passthrough) {
504             apply_lut(rgb, s->rgb_stride, w, h, s->lin_lut);
505             if (!s->lrgb2lrgb_passthrough)
506                 s->dsp.multiply3x3(rgb, s->rgb_stride, w, h, s->lrgb2lrgb_coeffs);
507             apply_lut(rgb, s->rgb_stride, w, h, s->delin_lut);
508         }
509         if (s->dither == DITHER_FSB) {
510             s->rgb2yuv_fsb(out_data, td->out_linesize, rgb, s->rgb_stride, w, h,
511                            s->rgb2yuv_coeffs, s->yuv_offset[1], s->dither_scratch);
512         } else {
513             s->rgb2yuv(out_data, td->out_linesize, rgb, s->rgb_stride, w, h,
514                        s->rgb2yuv_coeffs, s->yuv_offset[1]);
515         }
516     }
517
518     return 0;
519 }
520
521 static int get_range_off(AVFilterContext *ctx, int *off,
522                          int *y_rng, int *uv_rng,
523                          enum AVColorRange rng, int depth)
524 {
525     switch (rng) {
526     case AVCOL_RANGE_UNSPECIFIED:
527         av_log(ctx, AV_LOG_WARNING, "Input range not set, assuming tv/mpeg\n");
528         // fall-through
529     case AVCOL_RANGE_MPEG:
530         *off = 16 << (depth - 8);
531         *y_rng = 219 << (depth - 8);
532         *uv_rng = 224 << (depth - 8);
533         break;
534     case AVCOL_RANGE_JPEG:
535         *off = 0;
536         *y_rng = *uv_rng = (256 << (depth - 8)) - 1;
537         break;
538     default:
539         return AVERROR(EINVAL);
540     }
541
542     return 0;
543 }
544
545 static int create_filtergraph(AVFilterContext *ctx,
546                               const AVFrame *in, const AVFrame *out)
547 {
548     ColorSpaceContext *s = ctx->priv;
549     const AVPixFmtDescriptor *in_desc  = av_pix_fmt_desc_get(in->format);
550     const AVPixFmtDescriptor *out_desc = av_pix_fmt_desc_get(out->format);
551     int emms = 0, m, n, o, res, fmt_identical, redo_yuv2rgb = 0, redo_rgb2yuv = 0;
552
553 #define supported_depth(d) ((d) == 8 || (d) == 10 || (d) == 12)
554 #define supported_subsampling(lcw, lch) \
555     (((lcw) == 0 && (lch) == 0) || ((lcw) == 1 && (lch) == 0) || ((lcw) == 1 && (lch) == 1))
556 #define supported_format(d) \
557     ((d) != NULL && (d)->nb_components == 3 && \
558      !((d)->flags & AV_PIX_FMT_FLAG_RGB) && \
559      supported_depth((d)->comp[0].depth) && \
560      supported_subsampling((d)->log2_chroma_w, (d)->log2_chroma_h))
561
562     if (!supported_format(in_desc)) {
563         av_log(ctx, AV_LOG_ERROR,
564                "Unsupported input format %d (%s) or bitdepth (%d)\n",
565                in->format, av_get_pix_fmt_name(in->format),
566                in_desc ? in_desc->comp[0].depth : -1);
567         return AVERROR(EINVAL);
568     }
569     if (!supported_format(out_desc)) {
570         av_log(ctx, AV_LOG_ERROR,
571                "Unsupported output format %d (%s) or bitdepth (%d)\n",
572                out->format, av_get_pix_fmt_name(out->format),
573                out_desc ? out_desc->comp[0].depth : -1);
574         return AVERROR(EINVAL);
575     }
576
577     if (in->color_primaries  != s->in_prm)  s->in_primaries  = NULL;
578     if (out->color_primaries != s->out_prm) s->out_primaries = NULL;
579     if (in->color_trc        != s->in_trc)  s->in_txchr      = NULL;
580     if (out->color_trc       != s->out_trc) s->out_txchr     = NULL;
581     if (in->colorspace       != s->in_csp ||
582         in->color_range      != s->in_rng)  s->in_lumacoef   = NULL;
583     if (out->colorspace      != s->out_csp ||
584         out->color_range     != s->out_rng) s->out_lumacoef  = NULL;
585
586     if (!s->out_primaries || !s->in_primaries) {
587         s->in_prm = in->color_primaries;
588         if (s->user_iall != CS_UNSPECIFIED)
589             s->in_prm = default_prm[FFMIN(s->user_iall, CS_NB)];
590         if (s->user_iprm != AVCOL_PRI_UNSPECIFIED)
591             s->in_prm = s->user_iprm;
592         s->in_primaries = get_color_primaries(s->in_prm);
593         if (!s->in_primaries) {
594             av_log(ctx, AV_LOG_ERROR,
595                    "Unsupported input primaries %d (%s)\n",
596                    s->in_prm, av_color_primaries_name(s->in_prm));
597             return AVERROR(EINVAL);
598         }
599         s->out_prm = out->color_primaries;
600         s->out_primaries = get_color_primaries(s->out_prm);
601         if (!s->out_primaries) {
602             if (s->out_prm == AVCOL_PRI_UNSPECIFIED) {
603                 if (s->user_all == CS_UNSPECIFIED) {
604                     av_log(ctx, AV_LOG_ERROR, "Please specify output primaries\n");
605                 } else {
606                     av_log(ctx, AV_LOG_ERROR,
607                            "Unsupported output color property %d\n", s->user_all);
608                 }
609             } else {
610                 av_log(ctx, AV_LOG_ERROR,
611                        "Unsupported output primaries %d (%s)\n",
612                        s->out_prm, av_color_primaries_name(s->out_prm));
613             }
614             return AVERROR(EINVAL);
615         }
616         s->lrgb2lrgb_passthrough = !memcmp(s->in_primaries, s->out_primaries,
617                                            sizeof(*s->in_primaries));
618         if (!s->lrgb2lrgb_passthrough) {
619             double rgb2xyz[3][3], xyz2rgb[3][3], rgb2rgb[3][3];
620
621             fill_rgb2xyz_table(s->out_primaries, rgb2xyz);
622             invert_matrix3x3(rgb2xyz, xyz2rgb);
623             fill_rgb2xyz_table(s->in_primaries, rgb2xyz);
624             if (s->out_primaries->wp != s->in_primaries->wp &&
625                 s->wp_adapt != WP_ADAPT_IDENTITY) {
626                 double wpconv[3][3], tmp[3][3];
627
628                 fill_whitepoint_conv_table(wpconv, s->wp_adapt, s->in_primaries->wp,
629                                            s->out_primaries->wp);
630                 mul3x3(tmp, rgb2xyz, wpconv);
631                 mul3x3(rgb2rgb, tmp, xyz2rgb);
632             } else {
633                 mul3x3(rgb2rgb, rgb2xyz, xyz2rgb);
634             }
635             for (m = 0; m < 3; m++)
636                 for (n = 0; n < 3; n++) {
637                     s->lrgb2lrgb_coeffs[m][n][0] = lrint(16384.0 * rgb2rgb[m][n]);
638                     for (o = 1; o < 8; o++)
639                         s->lrgb2lrgb_coeffs[m][n][o] = s->lrgb2lrgb_coeffs[m][n][0];
640                 }
641
642             emms = 1;
643         }
644     }
645
646     if (!s->in_txchr) {
647         av_freep(&s->lin_lut);
648         s->in_trc = in->color_trc;
649         if (s->user_iall != CS_UNSPECIFIED)
650             s->in_trc = default_trc[FFMIN(s->user_iall, CS_NB)];
651         if (s->user_itrc != AVCOL_TRC_UNSPECIFIED)
652             s->in_trc = s->user_itrc;
653         s->in_txchr = get_transfer_characteristics(s->in_trc);
654         if (!s->in_txchr) {
655             av_log(ctx, AV_LOG_ERROR,
656                    "Unsupported input transfer characteristics %d (%s)\n",
657                    s->in_trc, av_color_transfer_name(s->in_trc));
658             return AVERROR(EINVAL);
659         }
660     }
661
662     if (!s->out_txchr) {
663         av_freep(&s->lin_lut);
664         s->out_trc = out->color_trc;
665         s->out_txchr = get_transfer_characteristics(s->out_trc);
666         if (!s->out_txchr) {
667             if (s->out_trc == AVCOL_TRC_UNSPECIFIED) {
668                 if (s->user_all == CS_UNSPECIFIED) {
669                     av_log(ctx, AV_LOG_ERROR,
670                            "Please specify output transfer characteristics\n");
671                 } else {
672                     av_log(ctx, AV_LOG_ERROR,
673                            "Unsupported output color property %d\n", s->user_all);
674                 }
675             } else {
676                 av_log(ctx, AV_LOG_ERROR,
677                        "Unsupported output transfer characteristics %d (%s)\n",
678                        s->out_trc, av_color_transfer_name(s->out_trc));
679             }
680             return AVERROR(EINVAL);
681         }
682     }
683
684     s->rgb2rgb_passthrough = s->fast_mode || (s->lrgb2lrgb_passthrough &&
685                              !memcmp(s->in_txchr, s->out_txchr, sizeof(*s->in_txchr)));
686     if (!s->rgb2rgb_passthrough && !s->lin_lut) {
687         res = fill_gamma_table(s);
688         if (res < 0)
689             return res;
690         emms = 1;
691     }
692
693     if (!s->in_lumacoef) {
694         s->in_csp = in->colorspace;
695         if (s->user_iall != CS_UNSPECIFIED)
696             s->in_csp = default_csp[FFMIN(s->user_iall, CS_NB)];
697         if (s->user_icsp != AVCOL_SPC_UNSPECIFIED)
698             s->in_csp = s->user_icsp;
699         s->in_rng = in->color_range;
700         if (s->user_irng != AVCOL_RANGE_UNSPECIFIED)
701             s->in_rng = s->user_irng;
702         s->in_lumacoef = get_luma_coefficients(s->in_csp);
703         if (!s->in_lumacoef) {
704             av_log(ctx, AV_LOG_ERROR,
705                    "Unsupported input colorspace %d (%s)\n",
706                    s->in_csp, av_color_space_name(s->in_csp));
707             return AVERROR(EINVAL);
708         }
709         redo_yuv2rgb = 1;
710     }
711
712     if (!s->out_lumacoef) {
713         s->out_csp = out->colorspace;
714         s->out_rng = out->color_range;
715         s->out_lumacoef = get_luma_coefficients(s->out_csp);
716         if (!s->out_lumacoef) {
717             if (s->out_csp == AVCOL_SPC_UNSPECIFIED) {
718                 if (s->user_all == CS_UNSPECIFIED) {
719                     av_log(ctx, AV_LOG_ERROR,
720                            "Please specify output transfer characteristics\n");
721                 } else {
722                     av_log(ctx, AV_LOG_ERROR,
723                            "Unsupported output color property %d\n", s->user_all);
724                 }
725             } else {
726                 av_log(ctx, AV_LOG_ERROR,
727                        "Unsupported output transfer characteristics %d (%s)\n",
728                        s->out_csp, av_color_space_name(s->out_csp));
729             }
730             return AVERROR(EINVAL);
731         }
732         redo_rgb2yuv = 1;
733     }
734
735     fmt_identical = in_desc->log2_chroma_h == out_desc->log2_chroma_h &&
736                     in_desc->log2_chroma_w == out_desc->log2_chroma_w;
737     s->yuv2yuv_fastmode = s->rgb2rgb_passthrough && fmt_identical;
738     s->yuv2yuv_passthrough = s->yuv2yuv_fastmode && s->in_rng == s->out_rng &&
739                              !memcmp(s->in_lumacoef, s->out_lumacoef,
740                                      sizeof(*s->in_lumacoef)) &&
741                              in_desc->comp[0].depth == out_desc->comp[0].depth;
742     if (!s->yuv2yuv_passthrough) {
743         if (redo_yuv2rgb) {
744             double rgb2yuv[3][3], (*yuv2rgb)[3] = s->yuv2rgb_dbl_coeffs;
745             int off, bits, in_rng;
746
747             res = get_range_off(ctx, &off, &s->in_y_rng, &s->in_uv_rng,
748                                 s->in_rng, in_desc->comp[0].depth);
749             if (res < 0) {
750                 av_log(ctx, AV_LOG_ERROR,
751                        "Unsupported input color range %d (%s)\n",
752                        s->in_rng, av_color_range_name(s->in_rng));
753                 return res;
754             }
755             for (n = 0; n < 8; n++)
756                 s->yuv_offset[0][n] = off;
757             fill_rgb2yuv_table(s->in_lumacoef, rgb2yuv);
758             invert_matrix3x3(rgb2yuv, yuv2rgb);
759             bits = 1 << (in_desc->comp[0].depth - 1);
760             for (n = 0; n < 3; n++) {
761                 for (in_rng = s->in_y_rng, m = 0; m < 3; m++, in_rng = s->in_uv_rng) {
762                     s->yuv2rgb_coeffs[n][m][0] = lrint(28672 * bits * yuv2rgb[n][m] / in_rng);
763                     for (o = 1; o < 8; o++)
764                         s->yuv2rgb_coeffs[n][m][o] = s->yuv2rgb_coeffs[n][m][0];
765                 }
766             }
767             av_assert2(s->yuv2rgb_coeffs[0][1][0] == 0);
768             av_assert2(s->yuv2rgb_coeffs[2][2][0] == 0);
769             av_assert2(s->yuv2rgb_coeffs[0][0][0] == s->yuv2rgb_coeffs[1][0][0]);
770             av_assert2(s->yuv2rgb_coeffs[0][0][0] == s->yuv2rgb_coeffs[2][0][0]);
771             s->yuv2rgb = s->dsp.yuv2rgb[(in_desc->comp[0].depth - 8) >> 1]
772                                        [in_desc->log2_chroma_h + in_desc->log2_chroma_w];
773             emms = 1;
774         }
775
776         if (redo_rgb2yuv) {
777             double (*rgb2yuv)[3] = s->rgb2yuv_dbl_coeffs;
778             int off, out_rng, bits;
779
780             res = get_range_off(ctx, &off, &s->out_y_rng, &s->out_uv_rng,
781                                 s->out_rng, out_desc->comp[0].depth);
782             if (res < 0) {
783                 av_log(ctx, AV_LOG_ERROR,
784                        "Unsupported output color range %d (%s)\n",
785                        s->out_rng, av_color_range_name(s->out_rng));
786                 return res;
787             }
788             for (n = 0; n < 8; n++)
789                 s->yuv_offset[1][n] = off;
790             fill_rgb2yuv_table(s->out_lumacoef, rgb2yuv);
791             bits = 1 << (29 - out_desc->comp[0].depth);
792             for (out_rng = s->out_y_rng, n = 0; n < 3; n++, out_rng = s->out_uv_rng) {
793                 for (m = 0; m < 3; m++) {
794                     s->rgb2yuv_coeffs[n][m][0] = lrint(bits * out_rng * rgb2yuv[n][m] / 28672);
795                     for (o = 1; o < 8; o++)
796                         s->rgb2yuv_coeffs[n][m][o] = s->rgb2yuv_coeffs[n][m][0];
797                 }
798             }
799             av_assert2(s->rgb2yuv_coeffs[1][2][0] == s->rgb2yuv_coeffs[2][0][0]);
800             s->rgb2yuv = s->dsp.rgb2yuv[(out_desc->comp[0].depth - 8) >> 1]
801                                        [out_desc->log2_chroma_h + out_desc->log2_chroma_w];
802             s->rgb2yuv_fsb = s->dsp.rgb2yuv_fsb[(out_desc->comp[0].depth - 8) >> 1]
803                                        [out_desc->log2_chroma_h + out_desc->log2_chroma_w];
804             emms = 1;
805         }
806
807         if (s->yuv2yuv_fastmode && (redo_yuv2rgb || redo_rgb2yuv)) {
808             int idepth = in_desc->comp[0].depth, odepth = out_desc->comp[0].depth;
809             double (*rgb2yuv)[3] = s->rgb2yuv_dbl_coeffs;
810             double (*yuv2rgb)[3] = s->yuv2rgb_dbl_coeffs;
811             double yuv2yuv[3][3];
812             int in_rng, out_rng;
813
814             mul3x3(yuv2yuv, yuv2rgb, rgb2yuv);
815             for (out_rng = s->out_y_rng, m = 0; m < 3; m++, out_rng = s->out_uv_rng) {
816                 for (in_rng = s->in_y_rng, n = 0; n < 3; n++, in_rng = s->in_uv_rng) {
817                     s->yuv2yuv_coeffs[m][n][0] =
818                         lrint(16384 * yuv2yuv[m][n] * out_rng * (1 << idepth) /
819                               (in_rng * (1 << odepth)));
820                     for (o = 1; o < 8; o++)
821                         s->yuv2yuv_coeffs[m][n][o] = s->yuv2yuv_coeffs[m][n][0];
822                 }
823             }
824             av_assert2(s->yuv2yuv_coeffs[1][0][0] == 0);
825             av_assert2(s->yuv2yuv_coeffs[2][0][0] == 0);
826             s->yuv2yuv = s->dsp.yuv2yuv[(idepth - 8) >> 1][(odepth - 8) >> 1]
827                                        [in_desc->log2_chroma_h + in_desc->log2_chroma_w];
828         }
829     }
830
831     if (emms)
832         emms_c();
833
834     return 0;
835 }
836
837 static int init(AVFilterContext *ctx)
838 {
839     ColorSpaceContext *s = ctx->priv;
840
841     ff_colorspacedsp_init(&s->dsp);
842
843     return 0;
844 }
845
846 static void uninit(AVFilterContext *ctx)
847 {
848     ColorSpaceContext *s = ctx->priv;
849
850     av_freep(&s->rgb[0]);
851     av_freep(&s->rgb[1]);
852     av_freep(&s->rgb[2]);
853     s->rgb_sz = 0;
854     av_freep(&s->dither_scratch_base[0][0]);
855     av_freep(&s->dither_scratch_base[0][1]);
856     av_freep(&s->dither_scratch_base[1][0]);
857     av_freep(&s->dither_scratch_base[1][1]);
858     av_freep(&s->dither_scratch_base[2][0]);
859     av_freep(&s->dither_scratch_base[2][1]);
860
861     av_freep(&s->lin_lut);
862 }
863
864 static int filter_frame(AVFilterLink *link, AVFrame *in)
865 {
866     AVFilterContext *ctx = link->dst;
867     AVFilterLink *outlink = ctx->outputs[0];
868     ColorSpaceContext *s = ctx->priv;
869     // FIXME if yuv2yuv_passthrough, don't get a new buffer but use the
870     // input one if it is writable *OR* the actual literal values of in_*
871     // and out_* are identical (not just their respective properties)
872     AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
873     int res;
874     ptrdiff_t rgb_stride = FFALIGN(in->width * sizeof(int16_t), 32);
875     unsigned rgb_sz = rgb_stride * in->height;
876     struct ThreadData td;
877
878     if (!out) {
879         av_frame_free(&in);
880         return AVERROR(ENOMEM);
881     }
882     res = av_frame_copy_props(out, in);
883     if (res < 0) {
884         av_frame_free(&in);
885         return res;
886     }
887
888     out->color_primaries = s->user_prm == AVCOL_PRI_UNSPECIFIED ?
889                            default_prm[FFMIN(s->user_all, CS_NB)] : s->user_prm;
890     if (s->user_trc == AVCOL_TRC_UNSPECIFIED) {
891         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);
892
893         out->color_trc   = default_trc[FFMIN(s->user_all, CS_NB)];
894         if (out->color_trc == AVCOL_TRC_BT2020_10 && desc && desc->comp[0].depth >= 12)
895             out->color_trc = AVCOL_TRC_BT2020_12;
896     } else {
897         out->color_trc   = s->user_trc;
898     }
899     out->colorspace      = s->user_csp == AVCOL_SPC_UNSPECIFIED ?
900                            default_csp[FFMIN(s->user_all, CS_NB)] : s->user_csp;
901     out->color_range     = s->user_rng == AVCOL_RANGE_UNSPECIFIED ?
902                            in->color_range : s->user_rng;
903     if (rgb_sz != s->rgb_sz) {
904         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);
905         int uvw = in->width >> desc->log2_chroma_w;
906
907         av_freep(&s->rgb[0]);
908         av_freep(&s->rgb[1]);
909         av_freep(&s->rgb[2]);
910         s->rgb_sz = 0;
911         av_freep(&s->dither_scratch_base[0][0]);
912         av_freep(&s->dither_scratch_base[0][1]);
913         av_freep(&s->dither_scratch_base[1][0]);
914         av_freep(&s->dither_scratch_base[1][1]);
915         av_freep(&s->dither_scratch_base[2][0]);
916         av_freep(&s->dither_scratch_base[2][1]);
917
918         s->rgb[0] = av_malloc(rgb_sz);
919         s->rgb[1] = av_malloc(rgb_sz);
920         s->rgb[2] = av_malloc(rgb_sz);
921         s->dither_scratch_base[0][0] =
922             av_malloc(sizeof(*s->dither_scratch_base[0][0]) * (in->width + 4));
923         s->dither_scratch_base[0][1] =
924             av_malloc(sizeof(*s->dither_scratch_base[0][1]) * (in->width + 4));
925         s->dither_scratch_base[1][0] =
926             av_malloc(sizeof(*s->dither_scratch_base[1][0]) * (uvw + 4));
927         s->dither_scratch_base[1][1] =
928             av_malloc(sizeof(*s->dither_scratch_base[1][1]) * (uvw + 4));
929         s->dither_scratch_base[2][0] =
930             av_malloc(sizeof(*s->dither_scratch_base[2][0]) * (uvw + 4));
931         s->dither_scratch_base[2][1] =
932             av_malloc(sizeof(*s->dither_scratch_base[2][1]) * (uvw + 4));
933         s->dither_scratch[0][0] = &s->dither_scratch_base[0][0][1];
934         s->dither_scratch[0][1] = &s->dither_scratch_base[0][1][1];
935         s->dither_scratch[1][0] = &s->dither_scratch_base[1][0][1];
936         s->dither_scratch[1][1] = &s->dither_scratch_base[1][1][1];
937         s->dither_scratch[2][0] = &s->dither_scratch_base[2][0][1];
938         s->dither_scratch[2][1] = &s->dither_scratch_base[2][1][1];
939         if (!s->rgb[0] || !s->rgb[1] || !s->rgb[2] ||
940             !s->dither_scratch_base[0][0] || !s->dither_scratch_base[0][1] ||
941             !s->dither_scratch_base[1][0] || !s->dither_scratch_base[1][1] ||
942             !s->dither_scratch_base[2][0] || !s->dither_scratch_base[2][1]) {
943             uninit(ctx);
944             return AVERROR(ENOMEM);
945         }
946         s->rgb_sz = rgb_sz;
947     }
948     res = create_filtergraph(ctx, in, out);
949     if (res < 0)
950         return res;
951     s->rgb_stride = rgb_stride / sizeof(int16_t);
952     td.in = in;
953     td.out = out;
954     td.in_linesize[0] = in->linesize[0];
955     td.in_linesize[1] = in->linesize[1];
956     td.in_linesize[2] = in->linesize[2];
957     td.out_linesize[0] = out->linesize[0];
958     td.out_linesize[1] = out->linesize[1];
959     td.out_linesize[2] = out->linesize[2];
960     td.in_ss_h = av_pix_fmt_desc_get(in->format)->log2_chroma_h;
961     td.out_ss_h = av_pix_fmt_desc_get(out->format)->log2_chroma_h;
962     if (s->yuv2yuv_passthrough) {
963         res = av_frame_copy(out, in);
964         if (res < 0)
965             return res;
966     } else {
967         ctx->internal->execute(ctx, convert, &td, NULL,
968                                FFMIN((in->height + 1) >> 1, ff_filter_get_nb_threads(ctx)));
969     }
970     av_frame_free(&in);
971
972     return ff_filter_frame(outlink, out);
973 }
974
975 static int query_formats(AVFilterContext *ctx)
976 {
977     static const enum AVPixelFormat pix_fmts[] = {
978         AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV444P,
979         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
980         AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
981         AV_PIX_FMT_YUVJ420P,  AV_PIX_FMT_YUVJ422P,  AV_PIX_FMT_YUVJ444P,
982         AV_PIX_FMT_NONE
983     };
984     int res;
985     ColorSpaceContext *s = ctx->priv;
986     AVFilterFormats *formats = ff_make_format_list(pix_fmts);
987
988     if (!formats)
989         return AVERROR(ENOMEM);
990     if (s->user_format == AV_PIX_FMT_NONE)
991         return ff_set_common_formats(ctx, formats);
992     res = ff_formats_ref(formats, &ctx->inputs[0]->out_formats);
993     if (res < 0)
994         return res;
995     formats = NULL;
996     res = ff_add_format(&formats, s->user_format);
997     if (res < 0)
998         return res;
999
1000     return ff_formats_ref(formats, &ctx->outputs[0]->in_formats);
1001 }
1002
1003 static int config_props(AVFilterLink *outlink)
1004 {
1005     AVFilterLink *inlink = outlink->src->inputs[0];
1006
1007     outlink->w = inlink->w;
1008     outlink->h = inlink->h;
1009     outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
1010     outlink->time_base = inlink->time_base;
1011
1012     return 0;
1013 }
1014
1015 #define OFFSET(x) offsetof(ColorSpaceContext, x)
1016 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
1017 #define ENUM(x, y, z) { x, "", 0, AV_OPT_TYPE_CONST, { .i64 = y }, INT_MIN, INT_MAX, FLAGS, z }
1018
1019 static const AVOption colorspace_options[] = {
1020     { "all",        "Set all color properties together",
1021       OFFSET(user_all),   AV_OPT_TYPE_INT, { .i64 = CS_UNSPECIFIED },
1022       CS_UNSPECIFIED, CS_NB - 1, FLAGS, "all" },
1023     ENUM("bt470m",      CS_BT470M,             "all"),
1024     ENUM("bt470bg",     CS_BT470BG,            "all"),
1025     ENUM("bt601-6-525", CS_BT601_6_525,        "all"),
1026     ENUM("bt601-6-625", CS_BT601_6_625,        "all"),
1027     ENUM("bt709",       CS_BT709,              "all"),
1028     ENUM("smpte170m",   CS_SMPTE170M,          "all"),
1029     ENUM("smpte240m",   CS_SMPTE240M,          "all"),
1030     ENUM("bt2020",      CS_BT2020,             "all"),
1031
1032     { "space",      "Output colorspace",
1033       OFFSET(user_csp),   AV_OPT_TYPE_INT, { .i64 = AVCOL_SPC_UNSPECIFIED },
1034       AVCOL_SPC_RGB, AVCOL_SPC_NB - 1, FLAGS,  "csp"},
1035     ENUM("bt709",       AVCOL_SPC_BT709,       "csp"),
1036     ENUM("fcc",         AVCOL_SPC_FCC,         "csp"),
1037     ENUM("bt470bg",     AVCOL_SPC_BT470BG,     "csp"),
1038     ENUM("smpte170m",   AVCOL_SPC_SMPTE170M,   "csp"),
1039     ENUM("smpte240m",   AVCOL_SPC_SMPTE240M,   "csp"),
1040     ENUM("bt2020ncl",   AVCOL_SPC_BT2020_NCL,  "csp"),
1041
1042     { "range",      "Output color range",
1043       OFFSET(user_rng),   AV_OPT_TYPE_INT, { .i64 = AVCOL_RANGE_UNSPECIFIED },
1044       AVCOL_RANGE_UNSPECIFIED, AVCOL_RANGE_NB - 1, FLAGS, "rng" },
1045     ENUM("tv",          AVCOL_RANGE_MPEG,      "rng"),
1046     ENUM("mpeg",        AVCOL_RANGE_MPEG,      "rng"),
1047     ENUM("pc",          AVCOL_RANGE_JPEG,      "rng"),
1048     ENUM("jpeg",        AVCOL_RANGE_JPEG,      "rng"),
1049
1050     { "primaries",  "Output color primaries",
1051       OFFSET(user_prm),   AV_OPT_TYPE_INT, { .i64 = AVCOL_PRI_UNSPECIFIED },
1052       AVCOL_PRI_RESERVED0, AVCOL_PRI_NB - 1, FLAGS, "prm" },
1053     ENUM("bt709",        AVCOL_PRI_BT709,      "prm"),
1054     ENUM("bt470m",       AVCOL_PRI_BT470M,     "prm"),
1055     ENUM("bt470bg",      AVCOL_PRI_BT470BG,    "prm"),
1056     ENUM("smpte170m",    AVCOL_PRI_SMPTE170M,  "prm"),
1057     ENUM("smpte240m",    AVCOL_PRI_SMPTE240M,  "prm"),
1058     ENUM("bt2020",       AVCOL_PRI_BT2020,     "prm"),
1059
1060     { "trc",        "Output transfer characteristics",
1061       OFFSET(user_trc),   AV_OPT_TYPE_INT, { .i64 = AVCOL_TRC_UNSPECIFIED },
1062       AVCOL_TRC_RESERVED0, AVCOL_TRC_NB - 1, FLAGS, "trc" },
1063     ENUM("bt709",        AVCOL_TRC_BT709,        "trc"),
1064     ENUM("bt470m",       AVCOL_TRC_GAMMA22,      "trc"),
1065     ENUM("gamma22",      AVCOL_TRC_GAMMA22,      "trc"),
1066     ENUM("bt470bg",      AVCOL_TRC_GAMMA28,      "trc"),
1067     ENUM("gamma28",      AVCOL_TRC_GAMMA28,      "trc"),
1068     ENUM("smpte170m",    AVCOL_TRC_SMPTE170M,    "trc"),
1069     ENUM("smpte240m",    AVCOL_TRC_SMPTE240M,    "trc"),
1070     ENUM("bt2020-10",    AVCOL_TRC_BT2020_10,    "trc"),
1071     ENUM("bt2020-12",    AVCOL_TRC_BT2020_12,    "trc"),
1072
1073     { "format",   "Output pixel format",
1074       OFFSET(user_format), AV_OPT_TYPE_INT,  { .i64 = AV_PIX_FMT_NONE },
1075       AV_PIX_FMT_NONE, AV_PIX_FMT_GBRAP12LE, FLAGS, "fmt" },
1076     ENUM("yuv420p",   AV_PIX_FMT_YUV420P,   "fmt"),
1077     ENUM("yuv420p10", AV_PIX_FMT_YUV420P10, "fmt"),
1078     ENUM("yuv420p12", AV_PIX_FMT_YUV420P12, "fmt"),
1079     ENUM("yuv422p",   AV_PIX_FMT_YUV422P,   "fmt"),
1080     ENUM("yuv422p10", AV_PIX_FMT_YUV422P10, "fmt"),
1081     ENUM("yuv422p12", AV_PIX_FMT_YUV422P12, "fmt"),
1082     ENUM("yuv444p",   AV_PIX_FMT_YUV444P,   "fmt"),
1083     ENUM("yuv444p10", AV_PIX_FMT_YUV444P10, "fmt"),
1084     ENUM("yuv444p12", AV_PIX_FMT_YUV444P12, "fmt"),
1085
1086     { "fast",     "Ignore primary chromaticity and gamma correction",
1087       OFFSET(fast_mode), AV_OPT_TYPE_BOOL,  { .i64 = 0    },
1088       0, 1, FLAGS },
1089
1090     { "dither",   "Dithering mode",
1091       OFFSET(dither), AV_OPT_TYPE_INT, { .i64 = DITHER_NONE },
1092       DITHER_NONE, DITHER_NB - 1, FLAGS, "dither" },
1093     ENUM("none", DITHER_NONE, "dither"),
1094     ENUM("fsb",  DITHER_FSB,  "dither"),
1095
1096     { "wpadapt", "Whitepoint adaptation method",
1097       OFFSET(wp_adapt), AV_OPT_TYPE_INT, { .i64 = WP_ADAPT_BRADFORD },
1098       WP_ADAPT_BRADFORD, NB_WP_ADAPT - 1, FLAGS, "wpadapt" },
1099     ENUM("bradford", WP_ADAPT_BRADFORD, "wpadapt"),
1100     ENUM("vonkries", WP_ADAPT_VON_KRIES, "wpadapt"),
1101     ENUM("identity", WP_ADAPT_IDENTITY, "wpadapt"),
1102
1103     { "iall",       "Set all input color properties together",
1104       OFFSET(user_iall),   AV_OPT_TYPE_INT, { .i64 = CS_UNSPECIFIED },
1105       CS_UNSPECIFIED, CS_NB - 1, FLAGS, "all" },
1106     { "ispace",     "Input colorspace",
1107       OFFSET(user_icsp),  AV_OPT_TYPE_INT, { .i64 = AVCOL_SPC_UNSPECIFIED },
1108       AVCOL_PRI_RESERVED0, AVCOL_PRI_NB - 1, FLAGS, "csp" },
1109     { "irange",     "Input color range",
1110       OFFSET(user_irng),  AV_OPT_TYPE_INT, { .i64 = AVCOL_RANGE_UNSPECIFIED },
1111       AVCOL_RANGE_UNSPECIFIED, AVCOL_RANGE_NB - 1, FLAGS, "rng" },
1112     { "iprimaries", "Input color primaries",
1113       OFFSET(user_iprm),  AV_OPT_TYPE_INT, { .i64 = AVCOL_PRI_UNSPECIFIED },
1114       AVCOL_PRI_RESERVED0, AVCOL_PRI_NB - 1, FLAGS, "prm" },
1115     { "itrc",       "Input transfer characteristics",
1116       OFFSET(user_itrc),  AV_OPT_TYPE_INT, { .i64 = AVCOL_TRC_UNSPECIFIED },
1117       AVCOL_TRC_RESERVED0, AVCOL_TRC_NB - 1, FLAGS, "trc" },
1118
1119     { NULL }
1120 };
1121
1122 AVFILTER_DEFINE_CLASS(colorspace);
1123
1124 static const AVFilterPad inputs[] = {
1125     {
1126         .name         = "default",
1127         .type         = AVMEDIA_TYPE_VIDEO,
1128         .filter_frame = filter_frame,
1129     },
1130     { NULL }
1131 };
1132
1133 static const AVFilterPad outputs[] = {
1134     {
1135         .name         = "default",
1136         .type         = AVMEDIA_TYPE_VIDEO,
1137         .config_props = config_props,
1138     },
1139     { NULL }
1140 };
1141
1142 AVFilter ff_vf_colorspace = {
1143     .name            = "colorspace",
1144     .description     = NULL_IF_CONFIG_SMALL("Convert between colorspaces."),
1145     .init            = init,
1146     .uninit          = uninit,
1147     .query_formats   = query_formats,
1148     .priv_size       = sizeof(ColorSpaceContext),
1149     .priv_class      = &colorspace_class,
1150     .inputs          = inputs,
1151     .outputs         = outputs,
1152     .flags           = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
1153 };