]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_v360.c
avfilter/vf_v360: fix setting default height for stereographic
[ffmpeg] / libavfilter / vf_v360.c
1 /*
2  * Copyright (c) 2019 Eugene Lyapustin
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  * 360 video conversion filter.
24  * Principle of operation:
25  *
26  * (for each pixel in output frame)
27  * 1) Calculate OpenGL-like coordinates (x, y, z) for pixel position (i, j)
28  * 2) Apply 360 operations (rotation, mirror) to (x, y, z)
29  * 3) Calculate pixel position (u, v) in input frame
30  * 4) Calculate interpolation window and weight for each pixel
31  *
32  * (for each frame)
33  * 5) Remap input frame to output frame using precalculated data
34  */
35
36 #include <math.h>
37
38 #include "libavutil/avassert.h"
39 #include "libavutil/imgutils.h"
40 #include "libavutil/pixdesc.h"
41 #include "libavutil/opt.h"
42 #include "avfilter.h"
43 #include "formats.h"
44 #include "internal.h"
45 #include "video.h"
46 #include "v360.h"
47
48 typedef struct ThreadData {
49     AVFrame *in;
50     AVFrame *out;
51 } ThreadData;
52
53 #define OFFSET(x) offsetof(V360Context, x)
54 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
55
56 static const AVOption v360_options[] = {
57     {     "input", "set input projection",              OFFSET(in), AV_OPT_TYPE_INT,    {.i64=EQUIRECTANGULAR}, 0,    NB_PROJECTIONS-1, FLAGS, "in" },
58     {         "e", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "in" },
59     {  "equirect", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "in" },
60     {      "c3x2", "cubemap 3x2",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_3_2},     0,                   0, FLAGS, "in" },
61     {      "c6x1", "cubemap 6x1",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_6_1},     0,                   0, FLAGS, "in" },
62     {       "eac", "equi-angular cubemap",                       0, AV_OPT_TYPE_CONST,  {.i64=EQUIANGULAR},     0,                   0, FLAGS, "in" },
63     {  "dfisheye", "dual fisheye",                               0, AV_OPT_TYPE_CONST,  {.i64=DUAL_FISHEYE},    0,                   0, FLAGS, "in" },
64     {    "barrel", "barrel facebook's 360 format",               0, AV_OPT_TYPE_CONST,  {.i64=BARREL},          0,                   0, FLAGS, "in" },
65     {        "fb", "barrel facebook's 360 format",               0, AV_OPT_TYPE_CONST,  {.i64=BARREL},          0,                   0, FLAGS, "in" },
66     {      "c1x6", "cubemap 1x6",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_1_6},     0,                   0, FLAGS, "in" },
67     {        "sg", "stereographic",                              0, AV_OPT_TYPE_CONST,  {.i64=STEREOGRAPHIC},   0,                   0, FLAGS, "in" },
68     {    "output", "set output projection",            OFFSET(out), AV_OPT_TYPE_INT,    {.i64=CUBEMAP_3_2},     0,    NB_PROJECTIONS-1, FLAGS, "out" },
69     {         "e", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "out" },
70     {  "equirect", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "out" },
71     {      "c3x2", "cubemap 3x2",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_3_2},     0,                   0, FLAGS, "out" },
72     {      "c6x1", "cubemap 6x1",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_6_1},     0,                   0, FLAGS, "out" },
73     {       "eac", "equi-angular cubemap",                       0, AV_OPT_TYPE_CONST,  {.i64=EQUIANGULAR},     0,                   0, FLAGS, "out" },
74     {      "flat", "regular video",                              0, AV_OPT_TYPE_CONST,  {.i64=FLAT},            0,                   0, FLAGS, "out" },
75     {"rectilinear", "regular video",                             0, AV_OPT_TYPE_CONST,  {.i64=FLAT},            0,                   0, FLAGS, "out" },
76     {  "gnomonic", "regular video",                              0, AV_OPT_TYPE_CONST,  {.i64=FLAT},            0,                   0, FLAGS, "out" },
77     {    "barrel", "barrel facebook's 360 format",               0, AV_OPT_TYPE_CONST,  {.i64=BARREL},          0,                   0, FLAGS, "out" },
78     {        "fb", "barrel facebook's 360 format",               0, AV_OPT_TYPE_CONST,  {.i64=BARREL},          0,                   0, FLAGS, "out" },
79     {      "c1x6", "cubemap 1x6",                                0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_1_6},     0,                   0, FLAGS, "out" },
80     {        "sg", "stereographic",                              0, AV_OPT_TYPE_CONST,  {.i64=STEREOGRAPHIC},   0,                   0, FLAGS, "out" },
81     {    "interp", "set interpolation method",      OFFSET(interp), AV_OPT_TYPE_INT,    {.i64=BILINEAR},        0, NB_INTERP_METHODS-1, FLAGS, "interp" },
82     {      "near", "nearest neighbour",                          0, AV_OPT_TYPE_CONST,  {.i64=NEAREST},         0,                   0, FLAGS, "interp" },
83     {   "nearest", "nearest neighbour",                          0, AV_OPT_TYPE_CONST,  {.i64=NEAREST},         0,                   0, FLAGS, "interp" },
84     {      "line", "bilinear interpolation",                     0, AV_OPT_TYPE_CONST,  {.i64=BILINEAR},        0,                   0, FLAGS, "interp" },
85     {    "linear", "bilinear interpolation",                     0, AV_OPT_TYPE_CONST,  {.i64=BILINEAR},        0,                   0, FLAGS, "interp" },
86     {      "cube", "bicubic interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=BICUBIC},         0,                   0, FLAGS, "interp" },
87     {     "cubic", "bicubic interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=BICUBIC},         0,                   0, FLAGS, "interp" },
88     {      "lanc", "lanczos interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=LANCZOS},         0,                   0, FLAGS, "interp" },
89     {   "lanczos", "lanczos interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=LANCZOS},         0,                   0, FLAGS, "interp" },
90     {         "w", "output width",                   OFFSET(width), AV_OPT_TYPE_INT,    {.i64=0},               0,           INT16_MAX, FLAGS, "w"},
91     {         "h", "output height",                 OFFSET(height), AV_OPT_TYPE_INT,    {.i64=0},               0,           INT16_MAX, FLAGS, "h"},
92     { "in_forder", "input cubemap face order",   OFFSET(in_forder), AV_OPT_TYPE_STRING, {.str="rludfb"},        0,     NB_DIRECTIONS-1, FLAGS, "in_forder"},
93     {"out_forder", "output cubemap face order", OFFSET(out_forder), AV_OPT_TYPE_STRING, {.str="rludfb"},        0,     NB_DIRECTIONS-1, FLAGS, "out_forder"},
94     {   "in_frot", "input cubemap face rotation",  OFFSET(in_frot), AV_OPT_TYPE_STRING, {.str="000000"},        0,     NB_DIRECTIONS-1, FLAGS, "in_frot"},
95     {  "out_frot", "output cubemap face rotation",OFFSET(out_frot), AV_OPT_TYPE_STRING, {.str="000000"},        0,     NB_DIRECTIONS-1, FLAGS, "out_frot"},
96     {    "in_pad", "input cubemap pads",            OFFSET(in_pad), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},           0.f,                 1.f, FLAGS, "in_pad"},
97     {   "out_pad", "output cubemap pads",          OFFSET(out_pad), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},           0.f,                 1.f, FLAGS, "out_pad"},
98     {       "yaw", "yaw rotation",                     OFFSET(yaw), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "yaw"},
99     {     "pitch", "pitch rotation",                 OFFSET(pitch), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "pitch"},
100     {      "roll", "roll rotation",                   OFFSET(roll), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "roll"},
101     {    "rorder", "rotation order",                OFFSET(rorder), AV_OPT_TYPE_STRING, {.str="ypr"},           0,                   0, FLAGS, "rorder"},
102     {     "h_fov", "horizontal field of view",       OFFSET(h_fov), AV_OPT_TYPE_FLOAT,  {.dbl=90.f},     0.00001f,               360.f, FLAGS, "h_fov"},
103     {     "v_fov", "vertical field of view",         OFFSET(v_fov), AV_OPT_TYPE_FLOAT,  {.dbl=45.f},     0.00001f,               360.f, FLAGS, "v_fov"},
104     {    "h_flip", "flip out video horizontally",   OFFSET(h_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "h_flip"},
105     {    "v_flip", "flip out video vertically",     OFFSET(v_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "v_flip"},
106     {    "d_flip", "flip out video indepth",        OFFSET(d_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "d_flip"},
107     {   "ih_flip", "flip in video horizontally",   OFFSET(ih_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "ih_flip"},
108     {   "iv_flip", "flip in video vertically",     OFFSET(iv_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "iv_flip"},
109     {  "in_trans", "transpose video input",   OFFSET(in_transpose), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "in_transpose"},
110     { "out_trans", "transpose video output", OFFSET(out_transpose), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "out_transpose"},
111     { NULL }
112 };
113
114 AVFILTER_DEFINE_CLASS(v360);
115
116 static int query_formats(AVFilterContext *ctx)
117 {
118     static const enum AVPixelFormat pix_fmts[] = {
119         // YUVA444
120         AV_PIX_FMT_YUVA444P,   AV_PIX_FMT_YUVA444P9,
121         AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12,
122         AV_PIX_FMT_YUVA444P16,
123
124         // YUVA422
125         AV_PIX_FMT_YUVA422P,   AV_PIX_FMT_YUVA422P9,
126         AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12,
127         AV_PIX_FMT_YUVA422P16,
128
129         // YUVA420
130         AV_PIX_FMT_YUVA420P,   AV_PIX_FMT_YUVA420P9,
131         AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
132
133         // YUVJ
134         AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
135         AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
136         AV_PIX_FMT_YUVJ411P,
137
138         // YUV444
139         AV_PIX_FMT_YUV444P,   AV_PIX_FMT_YUV444P9,
140         AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12,
141         AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV444P16,
142
143         // YUV440
144         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV440P10,
145         AV_PIX_FMT_YUV440P12,
146
147         // YUV422
148         AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV422P9,
149         AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12,
150         AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV422P16,
151
152         // YUV420
153         AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV420P9,
154         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12,
155         AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV420P16,
156
157         // YUV411
158         AV_PIX_FMT_YUV411P,
159
160         // YUV410
161         AV_PIX_FMT_YUV410P,
162
163         // GBR
164         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRP9,
165         AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12,
166         AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
167
168         // GBRA
169         AV_PIX_FMT_GBRAP,   AV_PIX_FMT_GBRAP10,
170         AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
171
172         // GRAY
173         AV_PIX_FMT_GRAY8,  AV_PIX_FMT_GRAY9,
174         AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12,
175         AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
176
177         AV_PIX_FMT_NONE
178     };
179
180     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
181     if (!fmts_list)
182         return AVERROR(ENOMEM);
183     return ff_set_common_formats(ctx, fmts_list);
184 }
185
186 #define DEFINE_REMAP1_LINE(bits, div)                                                           \
187 static void remap1_##bits##bit_line_c(uint8_t *dst, int width, const uint8_t *src,              \
188                                       ptrdiff_t in_linesize,                                    \
189                                       const uint16_t *u, const uint16_t *v, const int16_t *ker) \
190 {                                                                                               \
191     const uint##bits##_t *s = (const uint##bits##_t *)src;                                      \
192     uint##bits##_t *d = (uint##bits##_t *)dst;                                                  \
193                                                                                                 \
194     in_linesize /= div;                                                                         \
195                                                                                                 \
196     for (int x = 0; x < width; x++)                                                             \
197         d[x] = s[v[x] * in_linesize + u[x]];                                                    \
198 }
199
200 DEFINE_REMAP1_LINE( 8, 1)
201 DEFINE_REMAP1_LINE(16, 2)
202
203 typedef struct XYRemap {
204     uint16_t u[4][4];
205     uint16_t v[4][4];
206     float ker[4][4];
207 } XYRemap;
208
209 /**
210  * Generate remapping function with a given window size and pixel depth.
211  *
212  * @param ws size of interpolation window
213  * @param bits number of bits per pixel
214  */
215 #define DEFINE_REMAP(ws, bits)                                                                             \
216 static int remap##ws##_##bits##bit_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)          \
217 {                                                                                                          \
218     ThreadData *td = (ThreadData*)arg;                                                                     \
219     const V360Context *s = ctx->priv;                                                                      \
220     const AVFrame *in = td->in;                                                                            \
221     AVFrame *out = td->out;                                                                                \
222                                                                                                            \
223     for (int plane = 0; plane < s->nb_planes; plane++) {                                                   \
224         const int in_linesize  = in->linesize[plane];                                                      \
225         const int out_linesize = out->linesize[plane];                                                     \
226         const int uv_linesize = s->uv_linesize[plane];                                                     \
227         const uint8_t *src = in->data[plane];                                                              \
228         uint8_t *dst = out->data[plane];                                                                   \
229         const int width = s->planewidth[plane];                                                            \
230         const int height = s->planeheight[plane];                                                          \
231                                                                                                            \
232         const int slice_start = (height *  jobnr     ) / nb_jobs;                                          \
233         const int slice_end   = (height * (jobnr + 1)) / nb_jobs;                                          \
234                                                                                                            \
235         for (int y = slice_start; y < slice_end; y++) {                                                    \
236             const unsigned map = s->map[plane];                                                            \
237             const uint16_t *u = s->u[map] + y * uv_linesize * ws * ws;                                     \
238             const uint16_t *v = s->v[map] + y * uv_linesize * ws * ws;                                     \
239             const int16_t *ker = s->ker[map] + y * uv_linesize * ws * ws;                                  \
240                                                                                                            \
241             s->remap_line(dst + y * out_linesize, width, src, in_linesize, u, v, ker);                     \
242         }                                                                                                  \
243     }                                                                                                      \
244                                                                                                            \
245     return 0;                                                                                              \
246 }
247
248 DEFINE_REMAP(1,  8)
249 DEFINE_REMAP(2,  8)
250 DEFINE_REMAP(4,  8)
251 DEFINE_REMAP(1, 16)
252 DEFINE_REMAP(2, 16)
253 DEFINE_REMAP(4, 16)
254
255 #define DEFINE_REMAP_LINE(ws, bits, div)                                                                   \
256 static void remap##ws##_##bits##bit_line_c(uint8_t *dst, int width, const uint8_t *src,                    \
257                                            ptrdiff_t in_linesize,                                          \
258                                            const uint16_t *u, const uint16_t *v, const int16_t *ker)       \
259 {                                                                                                          \
260     const uint##bits##_t *s = (const uint##bits##_t *)src;                                                 \
261     uint##bits##_t *d = (uint##bits##_t *)dst;                                                             \
262                                                                                                            \
263     in_linesize /= div;                                                                                    \
264                                                                                                            \
265     for (int x = 0; x < width; x++) {                                                                      \
266         const uint16_t *uu = u + x * ws * ws;                                                              \
267         const uint16_t *vv = v + x * ws * ws;                                                              \
268         const int16_t *kker = ker + x * ws * ws;                                                           \
269         int tmp = 0;                                                                                       \
270                                                                                                            \
271         for (int i = 0; i < ws; i++) {                                                                     \
272             for (int j = 0; j < ws; j++) {                                                                 \
273                 tmp += kker[i * ws + j] * s[vv[i * ws + j] * in_linesize + uu[i * ws + j]];                \
274             }                                                                                              \
275         }                                                                                                  \
276                                                                                                            \
277         d[x] = av_clip_uint##bits(tmp >> 14);                                                              \
278     }                                                                                                      \
279 }
280
281 DEFINE_REMAP_LINE(2,  8, 1)
282 DEFINE_REMAP_LINE(4,  8, 1)
283 DEFINE_REMAP_LINE(2, 16, 2)
284 DEFINE_REMAP_LINE(4, 16, 2)
285
286 void ff_v360_init(V360Context *s, int depth)
287 {
288     switch (s->interp) {
289     case NEAREST:
290         s->remap_line = depth <= 8 ? remap1_8bit_line_c : remap1_16bit_line_c;
291         break;
292     case BILINEAR:
293         s->remap_line = depth <= 8 ? remap2_8bit_line_c : remap2_16bit_line_c;
294         break;
295     case BICUBIC:
296     case LANCZOS:
297         s->remap_line = depth <= 8 ? remap4_8bit_line_c : remap4_16bit_line_c;
298         break;
299     }
300
301     if (ARCH_X86)
302         ff_v360_init_x86(s, depth);
303 }
304
305 /**
306  * Save nearest pixel coordinates for remapping.
307  *
308  * @param du horizontal relative coordinate
309  * @param dv vertical relative coordinate
310  * @param r_tmp calculated 4x4 window
311  * @param u u remap data
312  * @param v v remap data
313  * @param ker ker remap data
314  */
315 static void nearest_kernel(float du, float dv, const XYRemap *r_tmp,
316                            uint16_t *u, uint16_t *v, int16_t *ker)
317 {
318     const int i = roundf(dv) + 1;
319     const int j = roundf(du) + 1;
320
321     u[0] = r_tmp->u[i][j];
322     v[0] = r_tmp->v[i][j];
323 }
324
325 /**
326  * Calculate kernel for bilinear interpolation.
327  *
328  * @param du horizontal relative coordinate
329  * @param dv vertical relative coordinate
330  * @param r_tmp calculated 4x4 window
331  * @param u u remap data
332  * @param v v remap data
333  * @param ker ker remap data
334  */
335 static void bilinear_kernel(float du, float dv, const XYRemap *r_tmp,
336                             uint16_t *u, uint16_t *v, int16_t *ker)
337 {
338     int i, j;
339
340     for (i = 0; i < 2; i++) {
341         for (j = 0; j < 2; j++) {
342             u[i * 2 + j] = r_tmp->u[i + 1][j + 1];
343             v[i * 2 + j] = r_tmp->v[i + 1][j + 1];
344         }
345     }
346
347     ker[0] = (1.f - du) * (1.f - dv) * 16384;
348     ker[1] =        du  * (1.f - dv) * 16384;
349     ker[2] = (1.f - du) *        dv  * 16384;
350     ker[3] =        du  *        dv  * 16384;
351 }
352
353 /**
354  * Calculate 1-dimensional cubic coefficients.
355  *
356  * @param t relative coordinate
357  * @param coeffs coefficients
358  */
359 static inline void calculate_bicubic_coeffs(float t, float *coeffs)
360 {
361     const float tt  = t * t;
362     const float ttt = t * t * t;
363
364     coeffs[0] =     - t / 3.f + tt / 2.f - ttt / 6.f;
365     coeffs[1] = 1.f - t / 2.f - tt       + ttt / 2.f;
366     coeffs[2] =       t       + tt / 2.f - ttt / 2.f;
367     coeffs[3] =     - t / 6.f            + ttt / 6.f;
368 }
369
370 /**
371  * Calculate kernel for bicubic interpolation.
372  *
373  * @param du horizontal relative coordinate
374  * @param dv vertical relative coordinate
375  * @param r_tmp calculated 4x4 window
376  * @param u u remap data
377  * @param v v remap data
378  * @param ker ker remap data
379  */
380 static void bicubic_kernel(float du, float dv, const XYRemap *r_tmp,
381                            uint16_t *u, uint16_t *v, int16_t *ker)
382 {
383     int i, j;
384     float du_coeffs[4];
385     float dv_coeffs[4];
386
387     calculate_bicubic_coeffs(du, du_coeffs);
388     calculate_bicubic_coeffs(dv, dv_coeffs);
389
390     for (i = 0; i < 4; i++) {
391         for (j = 0; j < 4; j++) {
392             u[i * 4 + j] = r_tmp->u[i][j];
393             v[i * 4 + j] = r_tmp->v[i][j];
394             ker[i * 4 + j] = du_coeffs[j] * dv_coeffs[i] * 16384;
395         }
396     }
397 }
398
399 /**
400  * Calculate 1-dimensional lanczos coefficients.
401  *
402  * @param t relative coordinate
403  * @param coeffs coefficients
404  */
405 static inline void calculate_lanczos_coeffs(float t, float *coeffs)
406 {
407     int i;
408     float sum = 0.f;
409
410     for (i = 0; i < 4; i++) {
411         const float x = M_PI * (t - i + 1);
412         if (x == 0.f) {
413             coeffs[i] = 1.f;
414         } else {
415             coeffs[i] = sinf(x) * sinf(x / 2.f) / (x * x / 2.f);
416         }
417         sum += coeffs[i];
418     }
419
420     for (i = 0; i < 4; i++) {
421         coeffs[i] /= sum;
422     }
423 }
424
425 /**
426  * Calculate kernel for lanczos interpolation.
427  *
428  * @param du horizontal relative coordinate
429  * @param dv vertical relative coordinate
430  * @param r_tmp calculated 4x4 window
431  * @param u u remap data
432  * @param v v remap data
433  * @param ker ker remap data
434  */
435 static void lanczos_kernel(float du, float dv, const XYRemap *r_tmp,
436                            uint16_t *u, uint16_t *v, int16_t *ker)
437 {
438     int i, j;
439     float du_coeffs[4];
440     float dv_coeffs[4];
441
442     calculate_lanczos_coeffs(du, du_coeffs);
443     calculate_lanczos_coeffs(dv, dv_coeffs);
444
445     for (i = 0; i < 4; i++) {
446         for (j = 0; j < 4; j++) {
447             u[i * 4 + j] = r_tmp->u[i][j];
448             v[i * 4 + j] = r_tmp->v[i][j];
449             ker[i * 4 + j] = du_coeffs[j] * dv_coeffs[i] * 16384;
450         }
451     }
452 }
453
454 /**
455  * Modulo operation with only positive remainders.
456  *
457  * @param a dividend
458  * @param b divisor
459  *
460  * @return positive remainder of (a / b)
461  */
462 static inline int mod(int a, int b)
463 {
464     const int res = a % b;
465     if (res < 0) {
466         return res + b;
467     } else {
468         return res;
469     }
470 }
471
472 /**
473  * Convert char to corresponding direction.
474  * Used for cubemap options.
475  */
476 static int get_direction(char c)
477 {
478     switch (c) {
479     case 'r':
480         return RIGHT;
481     case 'l':
482         return LEFT;
483     case 'u':
484         return UP;
485     case 'd':
486         return DOWN;
487     case 'f':
488         return FRONT;
489     case 'b':
490         return BACK;
491     default:
492         return -1;
493     }
494 }
495
496 /**
497  * Convert char to corresponding rotation angle.
498  * Used for cubemap options.
499  */
500 static int get_rotation(char c)
501 {
502     switch (c) {
503     case '0':
504         return ROT_0;
505     case '1':
506         return ROT_90;
507     case '2':
508         return ROT_180;
509     case '3':
510         return ROT_270;
511     default:
512         return -1;
513     }
514 }
515
516 /**
517  * Convert char to corresponding rotation order.
518  */
519 static int get_rorder(char c)
520 {
521     switch (c) {
522     case 'Y':
523     case 'y':
524         return YAW;
525     case 'P':
526     case 'p':
527         return PITCH;
528     case 'R':
529     case 'r':
530         return ROLL;
531     default:
532         return -1;
533     }
534 }
535
536 /**
537  * Prepare data for processing cubemap input format.
538  *
539  * @param ctx filter context
540  *
541  * @return error code
542  */
543 static int prepare_cube_in(AVFilterContext *ctx)
544 {
545     V360Context *s = ctx->priv;
546
547     for (int face = 0; face < NB_FACES; face++) {
548         const char c = s->in_forder[face];
549         int direction;
550
551         if (c == '\0') {
552             av_log(ctx, AV_LOG_ERROR,
553                    "Incomplete in_forder option. Direction for all 6 faces should be specified.\n");
554             return AVERROR(EINVAL);
555         }
556
557         direction = get_direction(c);
558         if (direction == -1) {
559             av_log(ctx, AV_LOG_ERROR,
560                    "Incorrect direction symbol '%c' in in_forder option.\n", c);
561             return AVERROR(EINVAL);
562         }
563
564         s->in_cubemap_face_order[direction] = face;
565     }
566
567     for (int face = 0; face < NB_FACES; face++) {
568         const char c = s->in_frot[face];
569         int rotation;
570
571         if (c == '\0') {
572             av_log(ctx, AV_LOG_ERROR,
573                    "Incomplete in_frot option. Rotation for all 6 faces should be specified.\n");
574             return AVERROR(EINVAL);
575         }
576
577         rotation = get_rotation(c);
578         if (rotation == -1) {
579             av_log(ctx, AV_LOG_ERROR,
580                    "Incorrect rotation symbol '%c' in in_frot option.\n", c);
581             return AVERROR(EINVAL);
582         }
583
584         s->in_cubemap_face_rotation[face] = rotation;
585     }
586
587     return 0;
588 }
589
590 /**
591  * Prepare data for processing cubemap output format.
592  *
593  * @param ctx filter context
594  *
595  * @return error code
596  */
597 static int prepare_cube_out(AVFilterContext *ctx)
598 {
599     V360Context *s = ctx->priv;
600
601     for (int face = 0; face < NB_FACES; face++) {
602         const char c = s->out_forder[face];
603         int direction;
604
605         if (c == '\0') {
606             av_log(ctx, AV_LOG_ERROR,
607                    "Incomplete out_forder option. Direction for all 6 faces should be specified.\n");
608             return AVERROR(EINVAL);
609         }
610
611         direction = get_direction(c);
612         if (direction == -1) {
613             av_log(ctx, AV_LOG_ERROR,
614                    "Incorrect direction symbol '%c' in out_forder option.\n", c);
615             return AVERROR(EINVAL);
616         }
617
618         s->out_cubemap_direction_order[face] = direction;
619     }
620
621     for (int face = 0; face < NB_FACES; face++) {
622         const char c = s->out_frot[face];
623         int rotation;
624
625         if (c == '\0') {
626             av_log(ctx, AV_LOG_ERROR,
627                    "Incomplete out_frot option. Rotation for all 6 faces should be specified.\n");
628             return AVERROR(EINVAL);
629         }
630
631         rotation = get_rotation(c);
632         if (rotation == -1) {
633             av_log(ctx, AV_LOG_ERROR,
634                    "Incorrect rotation symbol '%c' in out_frot option.\n", c);
635             return AVERROR(EINVAL);
636         }
637
638         s->out_cubemap_face_rotation[face] = rotation;
639     }
640
641     return 0;
642 }
643
644 static inline void rotate_cube_face(float *uf, float *vf, int rotation)
645 {
646     float tmp;
647
648     switch (rotation) {
649     case ROT_0:
650         break;
651     case ROT_90:
652         tmp =  *uf;
653         *uf = -*vf;
654         *vf =  tmp;
655         break;
656     case ROT_180:
657         *uf = -*uf;
658         *vf = -*vf;
659         break;
660     case ROT_270:
661         tmp = -*uf;
662         *uf =  *vf;
663         *vf =  tmp;
664         break;
665     default:
666         av_assert0(0);
667     }
668 }
669
670 static inline void rotate_cube_face_inverse(float *uf, float *vf, int rotation)
671 {
672     float tmp;
673
674     switch (rotation) {
675     case ROT_0:
676         break;
677     case ROT_90:
678         tmp = -*uf;
679         *uf =  *vf;
680         *vf =  tmp;
681         break;
682     case ROT_180:
683         *uf = -*uf;
684         *vf = -*vf;
685         break;
686     case ROT_270:
687         tmp =  *uf;
688         *uf = -*vf;
689         *vf =  tmp;
690         break;
691     default:
692         av_assert0(0);
693     }
694 }
695
696 /**
697  * Normalize vector.
698  *
699  * @param vec vector
700  */
701 static void normalize_vector(float *vec)
702 {
703     const float norm = sqrtf(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);
704
705     vec[0] /= norm;
706     vec[1] /= norm;
707     vec[2] /= norm;
708 }
709
710 /**
711  * Calculate 3D coordinates on sphere for corresponding cubemap position.
712  * Common operation for every cubemap.
713  *
714  * @param s filter context
715  * @param uf horizontal cubemap coordinate [0, 1)
716  * @param vf vertical cubemap coordinate [0, 1)
717  * @param face face of cubemap
718  * @param vec coordinates on sphere
719  */
720 static void cube_to_xyz(const V360Context *s,
721                         float uf, float vf, int face,
722                         float *vec)
723 {
724     const int direction = s->out_cubemap_direction_order[face];
725     float l_x, l_y, l_z;
726
727     uf /= (1.f - s->out_pad);
728     vf /= (1.f - s->out_pad);
729
730     rotate_cube_face_inverse(&uf, &vf, s->out_cubemap_face_rotation[face]);
731
732     switch (direction) {
733     case RIGHT:
734         l_x =  1.f;
735         l_y = -vf;
736         l_z =  uf;
737         break;
738     case LEFT:
739         l_x = -1.f;
740         l_y = -vf;
741         l_z = -uf;
742         break;
743     case UP:
744         l_x =  uf;
745         l_y =  1.f;
746         l_z = -vf;
747         break;
748     case DOWN:
749         l_x =  uf;
750         l_y = -1.f;
751         l_z =  vf;
752         break;
753     case FRONT:
754         l_x =  uf;
755         l_y = -vf;
756         l_z = -1.f;
757         break;
758     case BACK:
759         l_x = -uf;
760         l_y = -vf;
761         l_z =  1.f;
762         break;
763     }
764
765     vec[0] = l_x;
766     vec[1] = l_y;
767     vec[2] = l_z;
768
769     normalize_vector(vec);
770 }
771
772 /**
773  * Calculate cubemap position for corresponding 3D coordinates on sphere.
774  * Common operation for every cubemap.
775  *
776  * @param s filter context
777  * @param vec coordinated on sphere
778  * @param uf horizontal cubemap coordinate [0, 1)
779  * @param vf vertical cubemap coordinate [0, 1)
780  * @param direction direction of view
781  */
782 static void xyz_to_cube(const V360Context *s,
783                         const float *vec,
784                         float *uf, float *vf, int *direction)
785 {
786     const float phi   = atan2f(vec[0], -vec[2]);
787     const float theta = asinf(-vec[1]);
788     float phi_norm, theta_threshold;
789     int face;
790
791     if (phi >= -M_PI_4 && phi < M_PI_4) {
792         *direction = FRONT;
793         phi_norm = phi;
794     } else if (phi >= -(M_PI_2 + M_PI_4) && phi < -M_PI_4) {
795         *direction = LEFT;
796         phi_norm = phi + M_PI_2;
797     } else if (phi >= M_PI_4 && phi < M_PI_2 + M_PI_4) {
798         *direction = RIGHT;
799         phi_norm = phi - M_PI_2;
800     } else {
801         *direction = BACK;
802         phi_norm = phi + ((phi > 0.f) ? -M_PI : M_PI);
803     }
804
805     theta_threshold = atanf(cosf(phi_norm));
806     if (theta > theta_threshold) {
807         *direction = DOWN;
808     } else if (theta < -theta_threshold) {
809         *direction = UP;
810     }
811
812     switch (*direction) {
813     case RIGHT:
814         *uf =  vec[2] / vec[0];
815         *vf = -vec[1] / vec[0];
816         break;
817     case LEFT:
818         *uf =  vec[2] / vec[0];
819         *vf =  vec[1] / vec[0];
820         break;
821     case UP:
822         *uf =  vec[0] / vec[1];
823         *vf = -vec[2] / vec[1];
824         break;
825     case DOWN:
826         *uf = -vec[0] / vec[1];
827         *vf = -vec[2] / vec[1];
828         break;
829     case FRONT:
830         *uf = -vec[0] / vec[2];
831         *vf =  vec[1] / vec[2];
832         break;
833     case BACK:
834         *uf = -vec[0] / vec[2];
835         *vf = -vec[1] / vec[2];
836         break;
837     default:
838         av_assert0(0);
839     }
840
841     face = s->in_cubemap_face_order[*direction];
842     rotate_cube_face(uf, vf, s->in_cubemap_face_rotation[face]);
843
844     (*uf) *= s->input_mirror_modifier[0];
845     (*vf) *= s->input_mirror_modifier[1];
846 }
847
848 /**
849  * Find position on another cube face in case of overflow/underflow.
850  * Used for calculation of interpolation window.
851  *
852  * @param s filter context
853  * @param uf horizontal cubemap coordinate
854  * @param vf vertical cubemap coordinate
855  * @param direction direction of view
856  * @param new_uf new horizontal cubemap coordinate
857  * @param new_vf new vertical cubemap coordinate
858  * @param face face position on cubemap
859  */
860 static void process_cube_coordinates(const V360Context *s,
861                                      float uf, float vf, int direction,
862                                      float *new_uf, float *new_vf, int *face)
863 {
864     /*
865      *  Cubemap orientation
866      *
867      *           width
868      *         <------->
869      *         +-------+
870      *         |       |                              U
871      *         | up    |                   h       ------->
872      * +-------+-------+-------+-------+ ^ e      |
873      * |       |       |       |       | | i    V |
874      * | left  | front | right | back  | | g      |
875      * +-------+-------+-------+-------+ v h      v
876      *         |       |                   t
877      *         | down  |
878      *         +-------+
879      */
880
881     *face = s->in_cubemap_face_order[direction];
882     rotate_cube_face_inverse(&uf, &vf, s->in_cubemap_face_rotation[*face]);
883
884     if ((uf < -1.f || uf >= 1.f) && (vf < -1.f || vf >= 1.f)) {
885         // There are no pixels to use in this case
886         *new_uf = uf;
887         *new_vf = vf;
888     } else if (uf < -1.f) {
889         uf += 2.f;
890         switch (direction) {
891         case RIGHT:
892             direction = FRONT;
893             *new_uf =  uf;
894             *new_vf =  vf;
895             break;
896         case LEFT:
897             direction = BACK;
898             *new_uf =  uf;
899             *new_vf =  vf;
900             break;
901         case UP:
902             direction = LEFT;
903             *new_uf =  vf;
904             *new_vf = -uf;
905             break;
906         case DOWN:
907             direction = LEFT;
908             *new_uf = -vf;
909             *new_vf =  uf;
910             break;
911         case FRONT:
912             direction = LEFT;
913             *new_uf =  uf;
914             *new_vf =  vf;
915             break;
916         case BACK:
917             direction = RIGHT;
918             *new_uf =  uf;
919             *new_vf =  vf;
920             break;
921         default:
922             av_assert0(0);
923         }
924     } else if (uf >= 1.f) {
925         uf -= 2.f;
926         switch (direction) {
927         case RIGHT:
928             direction = BACK;
929             *new_uf =  uf;
930             *new_vf =  vf;
931             break;
932         case LEFT:
933             direction = FRONT;
934             *new_uf =  uf;
935             *new_vf =  vf;
936             break;
937         case UP:
938             direction = RIGHT;
939             *new_uf = -vf;
940             *new_vf =  uf;
941             break;
942         case DOWN:
943             direction = RIGHT;
944             *new_uf =  vf;
945             *new_vf = -uf;
946             break;
947         case FRONT:
948             direction = RIGHT;
949             *new_uf =  uf;
950             *new_vf =  vf;
951             break;
952         case BACK:
953             direction = LEFT;
954             *new_uf =  uf;
955             *new_vf =  vf;
956             break;
957         default:
958             av_assert0(0);
959         }
960     } else if (vf < -1.f) {
961         vf += 2.f;
962         switch (direction) {
963         case RIGHT:
964             direction = UP;
965             *new_uf =  vf;
966             *new_vf = -uf;
967             break;
968         case LEFT:
969             direction = UP;
970             *new_uf = -vf;
971             *new_vf =  uf;
972             break;
973         case UP:
974             direction = BACK;
975             *new_uf = -uf;
976             *new_vf = -vf;
977             break;
978         case DOWN:
979             direction = FRONT;
980             *new_uf =  uf;
981             *new_vf =  vf;
982             break;
983         case FRONT:
984             direction = UP;
985             *new_uf =  uf;
986             *new_vf =  vf;
987             break;
988         case BACK:
989             direction = UP;
990             *new_uf = -uf;
991             *new_vf = -vf;
992             break;
993         default:
994             av_assert0(0);
995         }
996     } else if (vf >= 1.f) {
997         vf -= 2.f;
998         switch (direction) {
999         case RIGHT:
1000             direction = DOWN;
1001             *new_uf = -vf;
1002             *new_vf =  uf;
1003             break;
1004         case LEFT:
1005             direction = DOWN;
1006             *new_uf =  vf;
1007             *new_vf = -uf;
1008             break;
1009         case UP:
1010             direction = FRONT;
1011             *new_uf =  uf;
1012             *new_vf =  vf;
1013             break;
1014         case DOWN:
1015             direction = BACK;
1016             *new_uf = -uf;
1017             *new_vf = -vf;
1018             break;
1019         case FRONT:
1020             direction = DOWN;
1021             *new_uf =  uf;
1022             *new_vf =  vf;
1023             break;
1024         case BACK:
1025             direction = DOWN;
1026             *new_uf = -uf;
1027             *new_vf = -vf;
1028             break;
1029         default:
1030             av_assert0(0);
1031         }
1032     } else {
1033         // Inside cube face
1034         *new_uf = uf;
1035         *new_vf = vf;
1036     }
1037
1038     *face = s->in_cubemap_face_order[direction];
1039     rotate_cube_face(new_uf, new_vf, s->in_cubemap_face_rotation[*face]);
1040 }
1041
1042 /**
1043  * Calculate 3D coordinates on sphere for corresponding frame position in cubemap3x2 format.
1044  *
1045  * @param s filter context
1046  * @param i horizontal position on frame [0, width)
1047  * @param j vertical position on frame [0, height)
1048  * @param width frame width
1049  * @param height frame height
1050  * @param vec coordinates on sphere
1051  */
1052 static void cube3x2_to_xyz(const V360Context *s,
1053                            int i, int j, int width, int height,
1054                            float *vec)
1055 {
1056     const float ew = width  / 3.f;
1057     const float eh = height / 2.f;
1058
1059     const int u_face = floorf(i / ew);
1060     const int v_face = floorf(j / eh);
1061     const int face = u_face + 3 * v_face;
1062
1063     const int u_shift = ceilf(ew * u_face);
1064     const int v_shift = ceilf(eh * v_face);
1065     const int ewi = ceilf(ew * (u_face + 1)) - u_shift;
1066     const int ehi = ceilf(eh * (v_face + 1)) - v_shift;
1067
1068     const float uf = 2.f * (i - u_shift) / ewi - 1.f;
1069     const float vf = 2.f * (j - v_shift) / ehi - 1.f;
1070
1071     cube_to_xyz(s, uf, vf, face, vec);
1072 }
1073
1074 /**
1075  * Calculate frame position in cubemap3x2 format for corresponding 3D coordinates on sphere.
1076  *
1077  * @param s filter context
1078  * @param vec coordinates on sphere
1079  * @param width frame width
1080  * @param height frame height
1081  * @param us horizontal coordinates for interpolation window
1082  * @param vs vertical coordinates for interpolation window
1083  * @param du horizontal relative coordinate
1084  * @param dv vertical relative coordinate
1085  */
1086 static void xyz_to_cube3x2(const V360Context *s,
1087                            const float *vec, int width, int height,
1088                            uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1089 {
1090     const float ew = width  / 3.f;
1091     const float eh = height / 2.f;
1092     float uf, vf;
1093     int ui, vi;
1094     int ewi, ehi;
1095     int i, j;
1096     int direction, face;
1097     int u_face, v_face;
1098
1099     xyz_to_cube(s, vec, &uf, &vf, &direction);
1100
1101     uf *= (1.f - s->in_pad);
1102     vf *= (1.f - s->in_pad);
1103
1104     face = s->in_cubemap_face_order[direction];
1105     u_face = face % 3;
1106     v_face = face / 3;
1107     ewi = ceilf(ew * (u_face + 1)) - ceilf(ew * u_face);
1108     ehi = ceilf(eh * (v_face + 1)) - ceilf(eh * v_face);
1109
1110     uf = 0.5f * ewi * (uf + 1.f);
1111     vf = 0.5f * ehi * (vf + 1.f);
1112
1113     ui = floorf(uf);
1114     vi = floorf(vf);
1115
1116     *du = uf - ui;
1117     *dv = vf - vi;
1118
1119     for (i = -1; i < 3; i++) {
1120         for (j = -1; j < 3; j++) {
1121             int new_ui = ui + j;
1122             int new_vi = vi + i;
1123             int u_shift, v_shift;
1124             int new_ewi, new_ehi;
1125
1126             if (new_ui >= 0 && new_ui < ewi && new_vi >= 0 && new_vi < ehi) {
1127                 face = s->in_cubemap_face_order[direction];
1128
1129                 u_face = face % 3;
1130                 v_face = face / 3;
1131                 u_shift = ceilf(ew * u_face);
1132                 v_shift = ceilf(eh * v_face);
1133             } else {
1134                 uf = 2.f * new_ui / ewi - 1.f;
1135                 vf = 2.f * new_vi / ehi - 1.f;
1136
1137                 uf /= (1.f - s->in_pad);
1138                 vf /= (1.f - s->in_pad);
1139
1140                 process_cube_coordinates(s, uf, vf, direction, &uf, &vf, &face);
1141
1142                 uf *= (1.f - s->in_pad);
1143                 vf *= (1.f - s->in_pad);
1144
1145                 u_face = face % 3;
1146                 v_face = face / 3;
1147                 u_shift = ceilf(ew * u_face);
1148                 v_shift = ceilf(eh * v_face);
1149                 new_ewi = ceilf(ew * (u_face + 1)) - u_shift;
1150                 new_ehi = ceilf(eh * (v_face + 1)) - v_shift;
1151
1152                 new_ui = av_clip(roundf(0.5f * new_ewi * (uf + 1.f)), 0, new_ewi - 1);
1153                 new_vi = av_clip(roundf(0.5f * new_ehi * (vf + 1.f)), 0, new_ehi - 1);
1154             }
1155
1156             us[i + 1][j + 1] = u_shift + new_ui;
1157             vs[i + 1][j + 1] = v_shift + new_vi;
1158         }
1159     }
1160 }
1161
1162 /**
1163  * Calculate 3D coordinates on sphere for corresponding frame position in cubemap1x6 format.
1164  *
1165  * @param s filter context
1166  * @param i horizontal position on frame [0, width)
1167  * @param j vertical position on frame [0, height)
1168  * @param width frame width
1169  * @param height frame height
1170  * @param vec coordinates on sphere
1171  */
1172 static void cube1x6_to_xyz(const V360Context *s,
1173                            int i, int j, int width, int height,
1174                            float *vec)
1175 {
1176     const float ew = width;
1177     const float eh = height / 6.f;
1178
1179     const int face = floorf(j / eh);
1180
1181     const int v_shift = ceilf(eh * face);
1182     const int ehi = ceilf(eh * (face + 1)) - v_shift;
1183
1184     const float uf = 2.f *  i            / ew  - 1.f;
1185     const float vf = 2.f * (j - v_shift) / ehi - 1.f;
1186
1187     cube_to_xyz(s, uf, vf, face, vec);
1188 }
1189
1190 /**
1191  * Calculate 3D coordinates on sphere for corresponding frame position in cubemap6x1 format.
1192  *
1193  * @param s filter context
1194  * @param i horizontal position on frame [0, width)
1195  * @param j vertical position on frame [0, height)
1196  * @param width frame width
1197  * @param height frame height
1198  * @param vec coordinates on sphere
1199  */
1200 static void cube6x1_to_xyz(const V360Context *s,
1201                            int i, int j, int width, int height,
1202                            float *vec)
1203 {
1204     const float ew = width / 6.f;
1205     const float eh = height;
1206
1207     const int face = floorf(i / ew);
1208
1209     const int u_shift = ceilf(ew * face);
1210     const int ewi = ceilf(ew * (face + 1)) - u_shift;
1211
1212     const float uf = 2.f * (i - u_shift) / ewi - 1.f;
1213     const float vf = 2.f *  j            / eh  - 1.f;
1214
1215     cube_to_xyz(s, uf, vf, face, vec);
1216 }
1217
1218 /**
1219  * Calculate frame position in cubemap1x6 format for corresponding 3D coordinates on sphere.
1220  *
1221  * @param s filter context
1222  * @param vec coordinates on sphere
1223  * @param width frame width
1224  * @param height frame height
1225  * @param us horizontal coordinates for interpolation window
1226  * @param vs vertical coordinates for interpolation window
1227  * @param du horizontal relative coordinate
1228  * @param dv vertical relative coordinate
1229  */
1230 static void xyz_to_cube1x6(const V360Context *s,
1231                            const float *vec, int width, int height,
1232                            uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1233 {
1234     const float eh = height / 6.f;
1235     const int ewi = width;
1236     float uf, vf;
1237     int ui, vi;
1238     int ehi;
1239     int i, j;
1240     int direction, face;
1241
1242     xyz_to_cube(s, vec, &uf, &vf, &direction);
1243
1244     uf *= (1.f - s->in_pad);
1245     vf *= (1.f - s->in_pad);
1246
1247     face = s->in_cubemap_face_order[direction];
1248     ehi = ceilf(eh * (face + 1)) - ceilf(eh * face);
1249
1250     uf = 0.5f * ewi * (uf + 1.f);
1251     vf = 0.5f * ehi * (vf + 1.f);
1252
1253     ui = floorf(uf);
1254     vi = floorf(vf);
1255
1256     *du = uf - ui;
1257     *dv = vf - vi;
1258
1259     for (i = -1; i < 3; i++) {
1260         for (j = -1; j < 3; j++) {
1261             int new_ui = ui + j;
1262             int new_vi = vi + i;
1263             int v_shift;
1264             int new_ehi;
1265
1266             if (new_ui >= 0 && new_ui < ewi && new_vi >= 0 && new_vi < ehi) {
1267                 face = s->in_cubemap_face_order[direction];
1268
1269                 v_shift = ceilf(eh * face);
1270             } else {
1271                 uf = 2.f * new_ui / ewi - 1.f;
1272                 vf = 2.f * new_vi / ehi - 1.f;
1273
1274                 uf /= (1.f - s->in_pad);
1275                 vf /= (1.f - s->in_pad);
1276
1277                 process_cube_coordinates(s, uf, vf, direction, &uf, &vf, &face);
1278
1279                 uf *= (1.f - s->in_pad);
1280                 vf *= (1.f - s->in_pad);
1281
1282                 v_shift = ceilf(eh * face);
1283                 new_ehi = ceilf(eh * (face + 1)) - v_shift;
1284
1285                 new_ui = av_clip(roundf(0.5f *     ewi * (uf + 1.f)), 0,     ewi - 1);
1286                 new_vi = av_clip(roundf(0.5f * new_ehi * (vf + 1.f)), 0, new_ehi - 1);
1287             }
1288
1289             us[i + 1][j + 1] =           new_ui;
1290             vs[i + 1][j + 1] = v_shift + new_vi;
1291         }
1292     }
1293 }
1294
1295 /**
1296  * Calculate frame position in cubemap6x1 format for corresponding 3D coordinates on sphere.
1297  *
1298  * @param s filter context
1299  * @param vec coordinates on sphere
1300  * @param width frame width
1301  * @param height frame height
1302  * @param us horizontal coordinates for interpolation window
1303  * @param vs vertical coordinates for interpolation window
1304  * @param du horizontal relative coordinate
1305  * @param dv vertical relative coordinate
1306  */
1307 static void xyz_to_cube6x1(const V360Context *s,
1308                            const float *vec, int width, int height,
1309                            uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1310 {
1311     const float ew = width / 6.f;
1312     const int ehi = height;
1313     float uf, vf;
1314     int ui, vi;
1315     int ewi;
1316     int i, j;
1317     int direction, face;
1318
1319     xyz_to_cube(s, vec, &uf, &vf, &direction);
1320
1321     uf *= (1.f - s->in_pad);
1322     vf *= (1.f - s->in_pad);
1323
1324     face = s->in_cubemap_face_order[direction];
1325     ewi = ceilf(ew * (face + 1)) - ceilf(ew * face);
1326
1327     uf = 0.5f * ewi * (uf + 1.f);
1328     vf = 0.5f * ehi * (vf + 1.f);
1329
1330     ui = floorf(uf);
1331     vi = floorf(vf);
1332
1333     *du = uf - ui;
1334     *dv = vf - vi;
1335
1336     for (i = -1; i < 3; i++) {
1337         for (j = -1; j < 3; j++) {
1338             int new_ui = ui + j;
1339             int new_vi = vi + i;
1340             int u_shift;
1341             int new_ewi;
1342
1343             if (new_ui >= 0 && new_ui < ewi && new_vi >= 0 && new_vi < ehi) {
1344                 face = s->in_cubemap_face_order[direction];
1345
1346                 u_shift = ceilf(ew * face);
1347             } else {
1348                 uf = 2.f * new_ui / ewi - 1.f;
1349                 vf = 2.f * new_vi / ehi - 1.f;
1350
1351                 uf /= (1.f - s->in_pad);
1352                 vf /= (1.f - s->in_pad);
1353
1354                 process_cube_coordinates(s, uf, vf, direction, &uf, &vf, &face);
1355
1356                 uf *= (1.f - s->in_pad);
1357                 vf *= (1.f - s->in_pad);
1358
1359                 u_shift = ceilf(ew * face);
1360                 new_ewi = ceilf(ew * (face + 1)) - u_shift;
1361
1362                 new_ui = av_clip(roundf(0.5f * new_ewi * (uf + 1.f)), 0, new_ewi - 1);
1363                 new_vi = av_clip(roundf(0.5f *     ehi * (vf + 1.f)), 0,     ehi - 1);
1364             }
1365
1366             us[i + 1][j + 1] = u_shift + new_ui;
1367             vs[i + 1][j + 1] =           new_vi;
1368         }
1369     }
1370 }
1371
1372 /**
1373  * Calculate 3D coordinates on sphere for corresponding frame position in equirectangular format.
1374  *
1375  * @param s filter context
1376  * @param i horizontal position on frame [0, width)
1377  * @param j vertical position on frame [0, height)
1378  * @param width frame width
1379  * @param height frame height
1380  * @param vec coordinates on sphere
1381  */
1382 static void equirect_to_xyz(const V360Context *s,
1383                             int i, int j, int width, int height,
1384                             float *vec)
1385 {
1386     const float phi   = ((2.f * i) / width  - 1.f) * M_PI;
1387     const float theta = ((2.f * j) / height - 1.f) * M_PI_2;
1388
1389     const float sin_phi   = sinf(phi);
1390     const float cos_phi   = cosf(phi);
1391     const float sin_theta = sinf(theta);
1392     const float cos_theta = cosf(theta);
1393
1394     vec[0] =  cos_theta * sin_phi;
1395     vec[1] = -sin_theta;
1396     vec[2] = -cos_theta * cos_phi;
1397 }
1398
1399 /**
1400  * Prepare data for processing stereographic output format.
1401  *
1402  * @param ctx filter context
1403  *
1404  * @return error code
1405  */
1406 static int prepare_stereographic_out(AVFilterContext *ctx)
1407 {
1408     V360Context *s = ctx->priv;
1409
1410     const float h_angle = tan(FFMIN(s->h_fov, 359.f) * M_PI / 720.f);
1411     const float v_angle = tan(FFMIN(s->v_fov, 359.f) * M_PI / 720.f);
1412
1413     s->flat_range[0] = h_angle;
1414     s->flat_range[1] = v_angle;
1415
1416     return 0;
1417 }
1418
1419 /**
1420  * Calculate 3D coordinates on sphere for corresponding frame position in stereographic format.
1421  *
1422  * @param s filter context
1423  * @param i horizontal position on frame [0, width)
1424  * @param j vertical position on frame [0, height)
1425  * @param width frame width
1426  * @param height frame height
1427  * @param vec coordinates on sphere
1428  */
1429 static void stereographic_to_xyz(const V360Context *s,
1430                                  int i, int j, int width, int height,
1431                                  float *vec)
1432 {
1433     const float x = ((2.f * i) / width  - 1.f) * s->flat_range[0];
1434     const float y = ((2.f * j) / height - 1.f) * s->flat_range[1];
1435     const float xy = x * x + y * y;
1436
1437     vec[0] = 2.f * x / (1.f + xy);
1438     vec[1] = (-1.f + xy) / (1.f + xy);
1439     vec[2] = 2.f * y / (1.f + xy);
1440
1441     normalize_vector(vec);
1442 }
1443
1444 /**
1445  * Calculate frame position in stereographic format for corresponding 3D coordinates on sphere.
1446  *
1447  * @param s filter context
1448  * @param vec coordinates on sphere
1449  * @param width frame width
1450  * @param height frame height
1451  * @param us horizontal coordinates for interpolation window
1452  * @param vs vertical coordinates for interpolation window
1453  * @param du horizontal relative coordinate
1454  * @param dv vertical relative coordinate
1455  */
1456 static void xyz_to_stereographic(const V360Context *s,
1457                                  const float *vec, int width, int height,
1458                                  uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1459 {
1460     const float x = av_clipf(vec[0] / (1.f - vec[1]), -1.f, 1.f) * s->input_mirror_modifier[0];
1461     const float y = av_clipf(vec[2] / (1.f - vec[1]), -1.f, 1.f) * s->input_mirror_modifier[1];
1462     float uf, vf;
1463     int ui, vi;
1464     int i, j;
1465
1466     uf = (x + 1.f) * width  / 2.f;
1467     vf = (y + 1.f) * height / 2.f;
1468     ui = floorf(uf);
1469     vi = floorf(vf);
1470
1471     *du = uf - ui;
1472     *dv = vf - vi;
1473
1474     for (i = -1; i < 3; i++) {
1475         for (j = -1; j < 3; j++) {
1476             us[i + 1][j + 1] = av_clip(ui + j, 0, width - 1);
1477             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1478         }
1479     }
1480 }
1481
1482 /**
1483  * Calculate frame position in equirectangular format for corresponding 3D coordinates on sphere.
1484  *
1485  * @param s filter context
1486  * @param vec coordinates on sphere
1487  * @param width frame width
1488  * @param height frame height
1489  * @param us horizontal coordinates for interpolation window
1490  * @param vs vertical coordinates for interpolation window
1491  * @param du horizontal relative coordinate
1492  * @param dv vertical relative coordinate
1493  */
1494 static void xyz_to_equirect(const V360Context *s,
1495                             const float *vec, int width, int height,
1496                             uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1497 {
1498     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1499     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
1500     float uf, vf;
1501     int ui, vi;
1502     int i, j;
1503
1504     uf = (phi   / M_PI   + 1.f) * width  / 2.f;
1505     vf = (theta / M_PI_2 + 1.f) * height / 2.f;
1506     ui = floorf(uf);
1507     vi = floorf(vf);
1508
1509     *du = uf - ui;
1510     *dv = vf - vi;
1511
1512     for (i = -1; i < 3; i++) {
1513         for (j = -1; j < 3; j++) {
1514             us[i + 1][j + 1] = mod(ui + j, width);
1515             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1516         }
1517     }
1518 }
1519
1520 /**
1521  * Prepare data for processing equi-angular cubemap input format.
1522  *
1523  * @param ctx filter context
1524
1525  * @return error code
1526  */
1527 static int prepare_eac_in(AVFilterContext *ctx)
1528 {
1529     V360Context *s = ctx->priv;
1530
1531     if (s->ih_flip && s->iv_flip) {
1532         s->in_cubemap_face_order[RIGHT] = BOTTOM_LEFT;
1533         s->in_cubemap_face_order[LEFT]  = BOTTOM_RIGHT;
1534         s->in_cubemap_face_order[UP]    = TOP_LEFT;
1535         s->in_cubemap_face_order[DOWN]  = TOP_RIGHT;
1536         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
1537         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
1538     } else if (s->ih_flip) {
1539         s->in_cubemap_face_order[RIGHT] = TOP_LEFT;
1540         s->in_cubemap_face_order[LEFT]  = TOP_RIGHT;
1541         s->in_cubemap_face_order[UP]    = BOTTOM_LEFT;
1542         s->in_cubemap_face_order[DOWN]  = BOTTOM_RIGHT;
1543         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
1544         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
1545     } else if (s->iv_flip) {
1546         s->in_cubemap_face_order[RIGHT] = BOTTOM_RIGHT;
1547         s->in_cubemap_face_order[LEFT]  = BOTTOM_LEFT;
1548         s->in_cubemap_face_order[UP]    = TOP_RIGHT;
1549         s->in_cubemap_face_order[DOWN]  = TOP_LEFT;
1550         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
1551         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
1552     } else {
1553         s->in_cubemap_face_order[RIGHT] = TOP_RIGHT;
1554         s->in_cubemap_face_order[LEFT]  = TOP_LEFT;
1555         s->in_cubemap_face_order[UP]    = BOTTOM_RIGHT;
1556         s->in_cubemap_face_order[DOWN]  = BOTTOM_LEFT;
1557         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
1558         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
1559     }
1560
1561     if (s->iv_flip) {
1562         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_270;
1563         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_90;
1564         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_270;
1565         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_0;
1566         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_0;
1567         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_0;
1568     } else {
1569         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1570         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1571         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1572         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1573         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1574         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1575     }
1576
1577     return 0;
1578 }
1579
1580 /**
1581  * Prepare data for processing equi-angular cubemap output format.
1582  *
1583  * @param ctx filter context
1584  *
1585  * @return error code
1586  */
1587 static int prepare_eac_out(AVFilterContext *ctx)
1588 {
1589     V360Context *s = ctx->priv;
1590
1591     s->out_cubemap_direction_order[TOP_LEFT]      = LEFT;
1592     s->out_cubemap_direction_order[TOP_MIDDLE]    = FRONT;
1593     s->out_cubemap_direction_order[TOP_RIGHT]     = RIGHT;
1594     s->out_cubemap_direction_order[BOTTOM_LEFT]   = DOWN;
1595     s->out_cubemap_direction_order[BOTTOM_MIDDLE] = BACK;
1596     s->out_cubemap_direction_order[BOTTOM_RIGHT]  = UP;
1597
1598     s->out_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1599     s->out_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1600     s->out_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1601     s->out_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1602     s->out_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1603     s->out_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1604
1605     return 0;
1606 }
1607
1608 /**
1609  * Calculate 3D coordinates on sphere for corresponding frame position in equi-angular cubemap format.
1610  *
1611  * @param s filter context
1612  * @param i horizontal position on frame [0, width)
1613  * @param j vertical position on frame [0, height)
1614  * @param width frame width
1615  * @param height frame height
1616  * @param vec coordinates on sphere
1617  */
1618 static void eac_to_xyz(const V360Context *s,
1619                        int i, int j, int width, int height,
1620                        float *vec)
1621 {
1622     const float pixel_pad = 2;
1623     const float u_pad = pixel_pad / width;
1624     const float v_pad = pixel_pad / height;
1625
1626     int u_face, v_face, face;
1627
1628     float l_x, l_y, l_z;
1629
1630     float uf = (float)i / width;
1631     float vf = (float)j / height;
1632
1633     // EAC has 2-pixel padding on faces except between faces on the same row
1634     // Padding pixels seems not to be stretched with tangent as regular pixels
1635     // Formulas below approximate original padding as close as I could get experimentally
1636
1637     // Horizontal padding
1638     uf = 3.f * (uf - u_pad) / (1.f - 2.f * u_pad);
1639     if (uf < 0.f) {
1640         u_face = 0;
1641         uf -= 0.5f;
1642     } else if (uf >= 3.f) {
1643         u_face = 2;
1644         uf -= 2.5f;
1645     } else {
1646         u_face = floorf(uf);
1647         uf = fmodf(uf, 1.f) - 0.5f;
1648     }
1649
1650     // Vertical padding
1651     v_face = floorf(vf * 2.f);
1652     vf = (vf - v_pad - 0.5f * v_face) / (0.5f - 2.f * v_pad) - 0.5f;
1653
1654     if (uf >= -0.5f && uf < 0.5f) {
1655         uf = tanf(M_PI_2 * uf);
1656     } else {
1657         uf = 2.f * uf;
1658     }
1659     if (vf >= -0.5f && vf < 0.5f) {
1660         vf = tanf(M_PI_2 * vf);
1661     } else {
1662         vf = 2.f * vf;
1663     }
1664
1665     face = u_face + 3 * v_face;
1666
1667     switch (face) {
1668     case TOP_LEFT:
1669         l_x = -1.f;
1670         l_y = -vf;
1671         l_z = -uf;
1672         break;
1673     case TOP_MIDDLE:
1674         l_x =  uf;
1675         l_y = -vf;
1676         l_z = -1.f;
1677         break;
1678     case TOP_RIGHT:
1679         l_x =  1.f;
1680         l_y = -vf;
1681         l_z =  uf;
1682         break;
1683     case BOTTOM_LEFT:
1684         l_x = -vf;
1685         l_y = -1.f;
1686         l_z =  uf;
1687         break;
1688     case BOTTOM_MIDDLE:
1689         l_x = -vf;
1690         l_y =  uf;
1691         l_z =  1.f;
1692         break;
1693     case BOTTOM_RIGHT:
1694         l_x = -vf;
1695         l_y =  1.f;
1696         l_z = -uf;
1697         break;
1698     default:
1699         av_assert0(0);
1700     }
1701
1702     vec[0] = l_x;
1703     vec[1] = l_y;
1704     vec[2] = l_z;
1705
1706     normalize_vector(vec);
1707 }
1708
1709 /**
1710  * Calculate frame position in equi-angular cubemap format for corresponding 3D coordinates on sphere.
1711  *
1712  * @param s filter context
1713  * @param vec coordinates on sphere
1714  * @param width frame width
1715  * @param height frame height
1716  * @param us horizontal coordinates for interpolation window
1717  * @param vs vertical coordinates for interpolation window
1718  * @param du horizontal relative coordinate
1719  * @param dv vertical relative coordinate
1720  */
1721 static void xyz_to_eac(const V360Context *s,
1722                        const float *vec, int width, int height,
1723                        uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1724 {
1725     const float pixel_pad = 2;
1726     const float u_pad = pixel_pad / width;
1727     const float v_pad = pixel_pad / height;
1728
1729     float uf, vf;
1730     int ui, vi;
1731     int i, j;
1732     int direction, face;
1733     int u_face, v_face;
1734
1735     xyz_to_cube(s, vec, &uf, &vf, &direction);
1736
1737     face = s->in_cubemap_face_order[direction];
1738     u_face = face % 3;
1739     v_face = face / 3;
1740
1741     uf = M_2_PI * atanf(uf) + 0.5f;
1742     vf = M_2_PI * atanf(vf) + 0.5f;
1743
1744     // These formulas are inversed from eac_to_xyz ones
1745     uf = (uf + u_face) * (1.f - 2.f * u_pad) / 3.f + u_pad;
1746     vf = vf * (0.5f - 2.f * v_pad) + v_pad + 0.5f * v_face;
1747
1748     uf *= width;
1749     vf *= height;
1750
1751     ui = floorf(uf);
1752     vi = floorf(vf);
1753
1754     *du = uf - ui;
1755     *dv = vf - vi;
1756
1757     for (i = -1; i < 3; i++) {
1758         for (j = -1; j < 3; j++) {
1759             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1760             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1761         }
1762     }
1763 }
1764
1765 /**
1766  * Prepare data for processing flat output format.
1767  *
1768  * @param ctx filter context
1769  *
1770  * @return error code
1771  */
1772 static int prepare_flat_out(AVFilterContext *ctx)
1773 {
1774     V360Context *s = ctx->priv;
1775
1776     const float h_angle = 0.5f * s->h_fov * M_PI / 180.f;
1777     const float v_angle = 0.5f * s->v_fov * M_PI / 180.f;
1778
1779     const float sin_phi   = sinf(h_angle);
1780     const float cos_phi   = cosf(h_angle);
1781     const float sin_theta = sinf(v_angle);
1782     const float cos_theta = cosf(v_angle);
1783
1784     s->flat_range[0] =  cos_theta * sin_phi;
1785     s->flat_range[1] =  sin_theta;
1786     s->flat_range[2] = -cos_theta * cos_phi;
1787
1788     return 0;
1789 }
1790
1791 /**
1792  * Calculate 3D coordinates on sphere for corresponding frame position in flat format.
1793  *
1794  * @param s filter context
1795  * @param i horizontal position on frame [0, width)
1796  * @param j vertical position on frame [0, height)
1797  * @param width frame width
1798  * @param height frame height
1799  * @param vec coordinates on sphere
1800  */
1801 static void flat_to_xyz(const V360Context *s,
1802                         int i, int j, int width, int height,
1803                         float *vec)
1804 {
1805     const float l_x =  s->flat_range[0] * (2.f * i / width  - 1.f);
1806     const float l_y = -s->flat_range[1] * (2.f * j / height - 1.f);
1807     const float l_z =  s->flat_range[2];
1808
1809     vec[0] = l_x;
1810     vec[1] = l_y;
1811     vec[2] = l_z;
1812
1813     normalize_vector(vec);
1814 }
1815
1816 /**
1817  * Calculate frame position in dual fisheye format for corresponding 3D coordinates on sphere.
1818  *
1819  * @param s filter context
1820  * @param vec coordinates on sphere
1821  * @param width frame width
1822  * @param height frame height
1823  * @param us horizontal coordinates for interpolation window
1824  * @param vs vertical coordinates for interpolation window
1825  * @param du horizontal relative coordinate
1826  * @param dv vertical relative coordinate
1827  */
1828 static void xyz_to_dfisheye(const V360Context *s,
1829                             const float *vec, int width, int height,
1830                             uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1831 {
1832     const float scale = 1.f - s->in_pad;
1833
1834     const float ew = width / 2.f;
1835     const float eh = height;
1836
1837     const float phi   = atan2f(-vec[1], -vec[0]) * s->input_mirror_modifier[0];
1838     const float theta = acosf(fabsf(vec[2])) / M_PI * s->input_mirror_modifier[1];
1839
1840     float uf = (theta * cosf(phi) * scale + 0.5f) * ew;
1841     float vf = (theta * sinf(phi) * scale + 0.5f) * eh;
1842
1843     int ui, vi;
1844     int u_shift;
1845     int i, j;
1846
1847     if (vec[2] >= 0) {
1848         u_shift = 0;
1849     } else {
1850         u_shift = ceilf(ew);
1851         uf = ew - uf;
1852     }
1853
1854     ui = floorf(uf);
1855     vi = floorf(vf);
1856
1857     *du = uf - ui;
1858     *dv = vf - vi;
1859
1860     for (i = -1; i < 3; i++) {
1861         for (j = -1; j < 3; j++) {
1862             us[i + 1][j + 1] = av_clip(u_shift + ui + j, 0, width  - 1);
1863             vs[i + 1][j + 1] = av_clip(          vi + i, 0, height - 1);
1864         }
1865     }
1866 }
1867
1868 /**
1869  * Calculate 3D coordinates on sphere for corresponding frame position in barrel facebook's format.
1870  *
1871  * @param s filter context
1872  * @param i horizontal position on frame [0, width)
1873  * @param j vertical position on frame [0, height)
1874  * @param width frame width
1875  * @param height frame height
1876  * @param vec coordinates on sphere
1877  */
1878 static void barrel_to_xyz(const V360Context *s,
1879                           int i, int j, int width, int height,
1880                           float *vec)
1881 {
1882     const float scale = 0.99f;
1883     float l_x, l_y, l_z;
1884
1885     if (i < 4 * width / 5) {
1886         const float theta_range = M_PI_4;
1887
1888         const int ew = 4 * width / 5;
1889         const int eh = height;
1890
1891         const float phi   = ((2.f * i) / ew - 1.f) * M_PI        / scale;
1892         const float theta = ((2.f * j) / eh - 1.f) * theta_range / scale;
1893
1894         const float sin_phi   = sinf(phi);
1895         const float cos_phi   = cosf(phi);
1896         const float sin_theta = sinf(theta);
1897         const float cos_theta = cosf(theta);
1898
1899         l_x =  cos_theta * sin_phi;
1900         l_y = -sin_theta;
1901         l_z = -cos_theta * cos_phi;
1902     } else {
1903         const int ew = width  / 5;
1904         const int eh = height / 2;
1905
1906         float uf, vf;
1907
1908         if (j < eh) {   // UP
1909             uf = 2.f * (i - 4 * ew) / ew  - 1.f;
1910             vf = 2.f * (j         ) / eh - 1.f;
1911
1912             uf /= scale;
1913             vf /= scale;
1914
1915             l_x =  uf;
1916             l_y =  1.f;
1917             l_z = -vf;
1918         } else {            // DOWN
1919             uf = 2.f * (i - 4 * ew) / ew - 1.f;
1920             vf = 2.f * (j -     eh) / eh - 1.f;
1921
1922             uf /= scale;
1923             vf /= scale;
1924
1925             l_x =  uf;
1926             l_y = -1.f;
1927             l_z =  vf;
1928         }
1929     }
1930
1931     vec[0] = l_x;
1932     vec[1] = l_y;
1933     vec[2] = l_z;
1934
1935     normalize_vector(vec);
1936 }
1937
1938 /**
1939  * Calculate frame position in barrel facebook's format for corresponding 3D coordinates on sphere.
1940  *
1941  * @param s filter context
1942  * @param vec coordinates on sphere
1943  * @param width frame width
1944  * @param height frame height
1945  * @param us horizontal coordinates for interpolation window
1946  * @param vs vertical coordinates for interpolation window
1947  * @param du horizontal relative coordinate
1948  * @param dv vertical relative coordinate
1949  */
1950 static void xyz_to_barrel(const V360Context *s,
1951                           const float *vec, int width, int height,
1952                           uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1953 {
1954     const float scale = 0.99f;
1955
1956     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1957     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
1958     const float theta_range = M_PI_4;
1959
1960     int ew, eh;
1961     int u_shift, v_shift;
1962     float uf, vf;
1963     int ui, vi;
1964     int i, j;
1965
1966     if (theta > -theta_range && theta < theta_range) {
1967         ew = 4 * width / 5;
1968         eh = height;
1969
1970         u_shift = s->ih_flip ? width / 5 : 0;
1971         v_shift = 0;
1972
1973         uf = (phi   / M_PI        * scale + 1.f) * ew / 2.f;
1974         vf = (theta / theta_range * scale + 1.f) * eh / 2.f;
1975     } else {
1976         ew = width  / 5;
1977         eh = height / 2;
1978
1979         u_shift = s->ih_flip ? 0 : 4 * ew;
1980
1981         if (theta < 0.f) {  // UP
1982             uf =  vec[0] / vec[1];
1983             vf = -vec[2] / vec[1];
1984             v_shift = 0;
1985         } else {            // DOWN
1986             uf = -vec[0] / vec[1];
1987             vf = -vec[2] / vec[1];
1988             v_shift = eh;
1989         }
1990
1991         uf *= s->input_mirror_modifier[0] * s->input_mirror_modifier[1];
1992         vf *= s->input_mirror_modifier[1];
1993
1994         uf = 0.5f * ew * (uf * scale + 1.f);
1995         vf = 0.5f * eh * (vf * scale + 1.f);
1996     }
1997
1998     ui = floorf(uf);
1999     vi = floorf(vf);
2000
2001     *du = uf - ui;
2002     *dv = vf - vi;
2003
2004     for (i = -1; i < 3; i++) {
2005         for (j = -1; j < 3; j++) {
2006             us[i + 1][j + 1] = u_shift + av_clip(ui + j, 0, ew - 1);
2007             vs[i + 1][j + 1] = v_shift + av_clip(vi + i, 0, eh - 1);
2008         }
2009     }
2010 }
2011
2012 static void multiply_matrix(float c[3][3], const float a[3][3], const float b[3][3])
2013 {
2014     for (int i = 0; i < 3; i++) {
2015         for (int j = 0; j < 3; j++) {
2016             float sum = 0;
2017
2018             for (int k = 0; k < 3; k++)
2019                 sum += a[i][k] * b[k][j];
2020
2021             c[i][j] = sum;
2022         }
2023     }
2024 }
2025
2026 /**
2027  * Calculate rotation matrix for yaw/pitch/roll angles.
2028  */
2029 static inline void calculate_rotation_matrix(float yaw, float pitch, float roll,
2030                                              float rot_mat[3][3],
2031                                              const int rotation_order[3])
2032 {
2033     const float yaw_rad   = yaw   * M_PI / 180.f;
2034     const float pitch_rad = pitch * M_PI / 180.f;
2035     const float roll_rad  = roll  * M_PI / 180.f;
2036
2037     const float sin_yaw   = sinf(-yaw_rad);
2038     const float cos_yaw   = cosf(-yaw_rad);
2039     const float sin_pitch = sinf(pitch_rad);
2040     const float cos_pitch = cosf(pitch_rad);
2041     const float sin_roll  = sinf(roll_rad);
2042     const float cos_roll  = cosf(roll_rad);
2043
2044     float m[3][3][3];
2045     float temp[3][3];
2046
2047     m[0][0][0] =  cos_yaw;  m[0][0][1] = 0;          m[0][0][2] =  sin_yaw;
2048     m[0][1][0] =  0;        m[0][1][1] = 1;          m[0][1][2] =  0;
2049     m[0][2][0] = -sin_yaw;  m[0][2][1] = 0;          m[0][2][2] =  cos_yaw;
2050
2051     m[1][0][0] = 1;         m[1][0][1] = 0;          m[1][0][2] =  0;
2052     m[1][1][0] = 0;         m[1][1][1] = cos_pitch;  m[1][1][2] = -sin_pitch;
2053     m[1][2][0] = 0;         m[1][2][1] = sin_pitch;  m[1][2][2] =  cos_pitch;
2054
2055     m[2][0][0] = cos_roll;  m[2][0][1] = -sin_roll;  m[2][0][2] =  0;
2056     m[2][1][0] = sin_roll;  m[2][1][1] =  cos_roll;  m[2][1][2] =  0;
2057     m[2][2][0] = 0;         m[2][2][1] =  0;         m[2][2][2] =  1;
2058
2059     multiply_matrix(temp, m[rotation_order[0]], m[rotation_order[1]]);
2060     multiply_matrix(rot_mat, temp, m[rotation_order[2]]);
2061 }
2062
2063 /**
2064  * Rotate vector with given rotation matrix.
2065  *
2066  * @param rot_mat rotation matrix
2067  * @param vec vector
2068  */
2069 static inline void rotate(const float rot_mat[3][3],
2070                           float *vec)
2071 {
2072     const float x_tmp = vec[0] * rot_mat[0][0] + vec[1] * rot_mat[0][1] + vec[2] * rot_mat[0][2];
2073     const float y_tmp = vec[0] * rot_mat[1][0] + vec[1] * rot_mat[1][1] + vec[2] * rot_mat[1][2];
2074     const float z_tmp = vec[0] * rot_mat[2][0] + vec[1] * rot_mat[2][1] + vec[2] * rot_mat[2][2];
2075
2076     vec[0] = x_tmp;
2077     vec[1] = y_tmp;
2078     vec[2] = z_tmp;
2079 }
2080
2081 static inline void set_mirror_modifier(int h_flip, int v_flip, int d_flip,
2082                                        float *modifier)
2083 {
2084     modifier[0] = h_flip ? -1.f : 1.f;
2085     modifier[1] = v_flip ? -1.f : 1.f;
2086     modifier[2] = d_flip ? -1.f : 1.f;
2087 }
2088
2089 static inline void mirror(const float *modifier, float *vec)
2090 {
2091     vec[0] *= modifier[0];
2092     vec[1] *= modifier[1];
2093     vec[2] *= modifier[2];
2094 }
2095
2096 static int allocate_plane(V360Context *s, int sizeof_uv, int sizeof_ker, int p)
2097 {
2098     s->u[p] = av_calloc(s->uv_linesize[p] * s->planeheight[p], sizeof_uv);
2099     s->v[p] = av_calloc(s->uv_linesize[p] * s->planeheight[p], sizeof_uv);
2100     if (!s->u[p] || !s->v[p])
2101         return AVERROR(ENOMEM);
2102     if (sizeof_ker) {
2103         s->ker[p] = av_calloc(s->uv_linesize[p] * s->planeheight[p], sizeof_ker);
2104         if (!s->ker[p])
2105             return AVERROR(ENOMEM);
2106     }
2107
2108     return 0;
2109 }
2110
2111 static int config_output(AVFilterLink *outlink)
2112 {
2113     AVFilterContext *ctx = outlink->src;
2114     AVFilterLink *inlink = ctx->inputs[0];
2115     V360Context *s = ctx->priv;
2116     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
2117     const int depth = desc->comp[0].depth;
2118     int sizeof_uv;
2119     int sizeof_ker;
2120     int elements;
2121     int err;
2122     int p, h, w;
2123     float hf, wf;
2124     float output_mirror_modifier[3];
2125     void (*in_transform)(const V360Context *s,
2126                          const float *vec, int width, int height,
2127                          uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv);
2128     void (*out_transform)(const V360Context *s,
2129                           int i, int j, int width, int height,
2130                           float *vec);
2131     void (*calculate_kernel)(float du, float dv, const XYRemap *r_tmp,
2132                              uint16_t *u, uint16_t *v, int16_t *ker);
2133     float rot_mat[3][3];
2134
2135     s->input_mirror_modifier[0] = s->ih_flip ? -1.f : 1.f;
2136     s->input_mirror_modifier[1] = s->iv_flip ? -1.f : 1.f;
2137
2138     switch (s->interp) {
2139     case NEAREST:
2140         calculate_kernel = nearest_kernel;
2141         s->remap_slice = depth <= 8 ? remap1_8bit_slice : remap1_16bit_slice;
2142         elements = 1;
2143         sizeof_uv = sizeof(uint16_t) * elements;
2144         sizeof_ker = 0;
2145         break;
2146     case BILINEAR:
2147         calculate_kernel = bilinear_kernel;
2148         s->remap_slice = depth <= 8 ? remap2_8bit_slice : remap2_16bit_slice;
2149         elements = 2 * 2;
2150         sizeof_uv = sizeof(uint16_t) * elements;
2151         sizeof_ker = sizeof(uint16_t) * elements;
2152         break;
2153     case BICUBIC:
2154         calculate_kernel = bicubic_kernel;
2155         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2156         elements = 4 * 4;
2157         sizeof_uv = sizeof(uint16_t) * elements;
2158         sizeof_ker = sizeof(uint16_t) * elements;
2159         break;
2160     case LANCZOS:
2161         calculate_kernel = lanczos_kernel;
2162         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2163         elements = 4 * 4;
2164         sizeof_uv = sizeof(uint16_t) * elements;
2165         sizeof_ker = sizeof(uint16_t) * elements;
2166         break;
2167     default:
2168         av_assert0(0);
2169     }
2170
2171     ff_v360_init(s, depth);
2172
2173     for (int order = 0; order < NB_RORDERS; order++) {
2174         const char c = s->rorder[order];
2175         int rorder;
2176
2177         if (c == '\0') {
2178             av_log(ctx, AV_LOG_ERROR,
2179                    "Incomplete rorder option. Direction for all 3 rotation orders should be specified.\n");
2180             return AVERROR(EINVAL);
2181         }
2182
2183         rorder = get_rorder(c);
2184         if (rorder == -1) {
2185             av_log(ctx, AV_LOG_ERROR,
2186                    "Incorrect rotation order symbol '%c' in rorder option.\n", c);
2187             return AVERROR(EINVAL);
2188         }
2189
2190         s->rotation_order[order] = rorder;
2191     }
2192
2193     switch (s->in) {
2194     case EQUIRECTANGULAR:
2195         in_transform = xyz_to_equirect;
2196         err = 0;
2197         wf = inlink->w;
2198         hf = inlink->h;
2199         break;
2200     case CUBEMAP_3_2:
2201         in_transform = xyz_to_cube3x2;
2202         err = prepare_cube_in(ctx);
2203         wf = inlink->w / 3.f * 4.f;
2204         hf = inlink->h;
2205         break;
2206     case CUBEMAP_1_6:
2207         in_transform = xyz_to_cube1x6;
2208         err = prepare_cube_in(ctx);
2209         wf = inlink->w * 4.f;
2210         hf = inlink->h / 3.f;
2211         break;
2212     case CUBEMAP_6_1:
2213         in_transform = xyz_to_cube6x1;
2214         err = prepare_cube_in(ctx);
2215         wf = inlink->w / 3.f * 2.f;
2216         hf = inlink->h * 2.f;
2217         break;
2218     case EQUIANGULAR:
2219         in_transform = xyz_to_eac;
2220         err = prepare_eac_in(ctx);
2221         wf = inlink->w;
2222         hf = inlink->h / 9.f * 8.f;
2223         break;
2224     case FLAT:
2225         av_log(ctx, AV_LOG_ERROR, "Flat format is not accepted as input.\n");
2226         return AVERROR(EINVAL);
2227     case DUAL_FISHEYE:
2228         in_transform = xyz_to_dfisheye;
2229         err = 0;
2230         wf = inlink->w;
2231         hf = inlink->h;
2232         break;
2233     case BARREL:
2234         in_transform = xyz_to_barrel;
2235         err = 0;
2236         wf = inlink->w / 5.f * 4.f;
2237         hf = inlink->h;
2238         break;
2239     case STEREOGRAPHIC:
2240         in_transform = xyz_to_stereographic;
2241         err = 0;
2242         wf = inlink->w;
2243         hf = inlink->h / 2.f;
2244         break;
2245     default:
2246         av_log(ctx, AV_LOG_ERROR, "Specified input format is not handled.\n");
2247         return AVERROR_BUG;
2248     }
2249
2250     if (err != 0) {
2251         return err;
2252     }
2253
2254     switch (s->out) {
2255     case EQUIRECTANGULAR:
2256         out_transform = equirect_to_xyz;
2257         err = 0;
2258         w = roundf(wf);
2259         h = roundf(hf);
2260         break;
2261     case CUBEMAP_3_2:
2262         out_transform = cube3x2_to_xyz;
2263         err = prepare_cube_out(ctx);
2264         w = roundf(wf / 4.f * 3.f);
2265         h = roundf(hf);
2266         break;
2267     case CUBEMAP_1_6:
2268         out_transform = cube1x6_to_xyz;
2269         err = prepare_cube_out(ctx);
2270         w = roundf(wf / 4.f);
2271         h = roundf(hf * 3.f);
2272         break;
2273     case CUBEMAP_6_1:
2274         out_transform = cube6x1_to_xyz;
2275         err = prepare_cube_out(ctx);
2276         w = roundf(wf / 2.f * 3.f);
2277         h = roundf(hf / 2.f);
2278         break;
2279     case EQUIANGULAR:
2280         out_transform = eac_to_xyz;
2281         err = prepare_eac_out(ctx);
2282         w = roundf(wf);
2283         h = roundf(hf / 8.f * 9.f);
2284         break;
2285     case FLAT:
2286         out_transform = flat_to_xyz;
2287         err = prepare_flat_out(ctx);
2288         w = roundf(wf);
2289         h = roundf(hf);
2290         break;
2291     case DUAL_FISHEYE:
2292         av_log(ctx, AV_LOG_ERROR, "Dual fisheye format is not accepted as output.\n");
2293         return AVERROR(EINVAL);
2294     case BARREL:
2295         out_transform = barrel_to_xyz;
2296         err = 0;
2297         w = roundf(wf / 4.f * 5.f);
2298         h = roundf(hf);
2299         break;
2300     case STEREOGRAPHIC:
2301         out_transform = stereographic_to_xyz;
2302         err = prepare_stereographic_out(ctx);
2303         w = roundf(wf);
2304         h = roundf(hf * 2.f);
2305         break;
2306     default:
2307         av_log(ctx, AV_LOG_ERROR, "Specified output format is not handled.\n");
2308         return AVERROR_BUG;
2309     }
2310
2311     if (err != 0) {
2312         return err;
2313     }
2314
2315     // Override resolution with user values if specified
2316     if (s->width > 0 && s->height > 0) {
2317         w = s->width;
2318         h = s->height;
2319     } else if (s->width > 0 || s->height > 0) {
2320         av_log(ctx, AV_LOG_ERROR, "Both width and height values should be specified.\n");
2321         return AVERROR(EINVAL);
2322     } else {
2323         if (s->out_transpose)
2324             FFSWAP(int, w, h);
2325
2326         if (s->in_transpose)
2327             FFSWAP(int, w, h);
2328     }
2329
2330     s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(h, desc->log2_chroma_h);
2331     s->planeheight[0] = s->planeheight[3] = h;
2332     s->planewidth[1]  = s->planewidth[2] = FF_CEIL_RSHIFT(w, desc->log2_chroma_w);
2333     s->planewidth[0]  = s->planewidth[3] = w;
2334
2335     for (int i = 0; i < 4; i++)
2336         s->uv_linesize[i] = FFALIGN(s->planewidth[i], 8);
2337
2338     outlink->h = h;
2339     outlink->w = w;
2340
2341     s->inplaneheight[1] = s->inplaneheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
2342     s->inplaneheight[0] = s->inplaneheight[3] = inlink->h;
2343     s->inplanewidth[1]  = s->inplanewidth[2]  = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
2344     s->inplanewidth[0]  = s->inplanewidth[3]  = inlink->w;
2345     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
2346
2347     if (desc->log2_chroma_h == desc->log2_chroma_w && desc->log2_chroma_h == 0) {
2348         s->nb_allocated = 1;
2349         s->map[0] = s->map[1] = s->map[2] = s->map[3] = 0;
2350         allocate_plane(s, sizeof_uv, sizeof_ker, 0);
2351     } else {
2352         s->nb_allocated = 2;
2353         s->map[0] = 0;
2354         s->map[1] = s->map[2] = 1;
2355         s->map[3] = 0;
2356         allocate_plane(s, sizeof_uv, sizeof_ker, 0);
2357         allocate_plane(s, sizeof_uv, sizeof_ker, 1);
2358     }
2359
2360     calculate_rotation_matrix(s->yaw, s->pitch, s->roll, rot_mat, s->rotation_order);
2361     set_mirror_modifier(s->h_flip, s->v_flip, s->d_flip, output_mirror_modifier);
2362
2363     // Calculate remap data
2364     for (p = 0; p < s->nb_allocated; p++) {
2365         const int width = s->planewidth[p];
2366         const int uv_linesize = s->uv_linesize[p];
2367         const int height = s->planeheight[p];
2368         const int in_width = s->inplanewidth[p];
2369         const int in_height = s->inplaneheight[p];
2370         float du, dv;
2371         float vec[3];
2372         XYRemap r_tmp;
2373         int i, j;
2374
2375         for (i = 0; i < width; i++) {
2376             for (j = 0; j < height; j++) {
2377                 uint16_t *u = s->u[p] + (j * uv_linesize + i) * elements;
2378                 uint16_t *v = s->v[p] + (j * uv_linesize + i) * elements;
2379                 int16_t *ker = s->ker[p] + (j * uv_linesize + i) * elements;
2380
2381                 if (s->out_transpose)
2382                     out_transform(s, j, i, height, width, vec);
2383                 else
2384                     out_transform(s, i, j, width, height, vec);
2385                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2386                 rotate(rot_mat, vec);
2387                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2388                 normalize_vector(vec);
2389                 mirror(output_mirror_modifier, vec);
2390                 if (s->in_transpose)
2391                     in_transform(s, vec, in_height, in_width, r_tmp.v, r_tmp.u, &du, &dv);
2392                 else
2393                     in_transform(s, vec, in_width, in_height, r_tmp.u, r_tmp.v, &du, &dv);
2394                 av_assert1(!isnan(du) && !isnan(dv));
2395                 calculate_kernel(du, dv, &r_tmp, u, v, ker);
2396             }
2397         }
2398     }
2399
2400     return 0;
2401 }
2402
2403 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
2404 {
2405     AVFilterContext *ctx = inlink->dst;
2406     AVFilterLink *outlink = ctx->outputs[0];
2407     V360Context *s = ctx->priv;
2408     AVFrame *out;
2409     ThreadData td;
2410
2411     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
2412     if (!out) {
2413         av_frame_free(&in);
2414         return AVERROR(ENOMEM);
2415     }
2416     av_frame_copy_props(out, in);
2417
2418     td.in = in;
2419     td.out = out;
2420
2421     ctx->internal->execute(ctx, s->remap_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
2422
2423     av_frame_free(&in);
2424     return ff_filter_frame(outlink, out);
2425 }
2426
2427 static av_cold void uninit(AVFilterContext *ctx)
2428 {
2429     V360Context *s = ctx->priv;
2430     int p;
2431
2432     for (p = 0; p < s->nb_allocated; p++) {
2433         av_freep(&s->u[p]);
2434         av_freep(&s->v[p]);
2435         av_freep(&s->ker[p]);
2436     }
2437 }
2438
2439 static const AVFilterPad inputs[] = {
2440     {
2441         .name         = "default",
2442         .type         = AVMEDIA_TYPE_VIDEO,
2443         .filter_frame = filter_frame,
2444     },
2445     { NULL }
2446 };
2447
2448 static const AVFilterPad outputs[] = {
2449     {
2450         .name         = "default",
2451         .type         = AVMEDIA_TYPE_VIDEO,
2452         .config_props = config_output,
2453     },
2454     { NULL }
2455 };
2456
2457 AVFilter ff_vf_v360 = {
2458     .name          = "v360",
2459     .description   = NULL_IF_CONFIG_SMALL("Convert 360 projection of video."),
2460     .priv_size     = sizeof(V360Context),
2461     .uninit        = uninit,
2462     .query_formats = query_formats,
2463     .inputs        = inputs,
2464     .outputs       = outputs,
2465     .priv_class    = &v360_class,
2466     .flags         = AVFILTER_FLAG_SLICE_THREADS,
2467 };