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