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