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