]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_v360.c
avfilter/vf_v360: add support for input fov to input sg 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  * Prepare data for processing stereographic input format.
1586  *
1587  * @param ctx filter context
1588  *
1589  * @return error code
1590  */
1591 static int prepare_stereographic_in(AVFilterContext *ctx)
1592 {
1593     V360Context *s = ctx->priv;
1594
1595     s->iflat_range[0] = tanf(FFMIN(s->ih_fov, 359.f) * M_PI / 720.f);
1596     s->iflat_range[1] = tanf(FFMIN(s->iv_fov, 359.f) * M_PI / 720.f);
1597
1598     return 0;
1599 }
1600
1601 /**
1602  * Calculate frame position in stereographic format for corresponding 3D coordinates on sphere.
1603  *
1604  * @param s filter private context
1605  * @param vec coordinates on sphere
1606  * @param width frame width
1607  * @param height frame height
1608  * @param us horizontal coordinates for interpolation window
1609  * @param vs vertical coordinates for interpolation window
1610  * @param du horizontal relative coordinate
1611  * @param dv vertical relative coordinate
1612  */
1613 static void xyz_to_stereographic(const V360Context *s,
1614                                  const float *vec, int width, int height,
1615                                  int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1616 {
1617     const float x = vec[0] / (1.f - vec[1]) / s->iflat_range[0] * s->input_mirror_modifier[0];
1618     const float y = vec[2] / (1.f - vec[1]) / s->iflat_range[1] * s->input_mirror_modifier[1];
1619     float uf, vf;
1620     int visible, ui, vi;
1621
1622     uf = (x + 1.f) * width  / 2.f;
1623     vf = (y + 1.f) * height / 2.f;
1624     ui = floorf(uf);
1625     vi = floorf(vf);
1626
1627     visible = isfinite(x) && isfinite(y) && vi >= 0 && vi < height && ui >= 0 && ui < width;
1628
1629     *du = visible ? uf - ui : 0.f;
1630     *dv = visible ? vf - vi : 0.f;
1631
1632     for (int i = -1; i < 3; i++) {
1633         for (int j = -1; j < 3; j++) {
1634             us[i + 1][j + 1] = visible ? av_clip(ui + j, 0, width  - 1) : 0;
1635             vs[i + 1][j + 1] = visible ? av_clip(vi + i, 0, height - 1) : 0;
1636         }
1637     }
1638 }
1639
1640 /**
1641  * Calculate frame position in equirectangular format for corresponding 3D coordinates on sphere.
1642  *
1643  * @param s filter private context
1644  * @param vec coordinates on sphere
1645  * @param width frame width
1646  * @param height frame height
1647  * @param us horizontal coordinates for interpolation window
1648  * @param vs vertical coordinates for interpolation window
1649  * @param du horizontal relative coordinate
1650  * @param dv vertical relative coordinate
1651  */
1652 static void xyz_to_equirect(const V360Context *s,
1653                             const float *vec, int width, int height,
1654                             int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1655 {
1656     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1657     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
1658     float uf, vf;
1659     int ui, vi;
1660
1661     uf = (phi   / M_PI   + 1.f) * width  / 2.f;
1662     vf = (theta / M_PI_2 + 1.f) * height / 2.f;
1663     ui = floorf(uf);
1664     vi = floorf(vf);
1665
1666     *du = uf - ui;
1667     *dv = vf - vi;
1668
1669     for (int i = -1; i < 3; i++) {
1670         for (int j = -1; j < 3; j++) {
1671             us[i + 1][j + 1] = mod(ui + j, width);
1672             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1673         }
1674     }
1675 }
1676
1677 /**
1678  * Prepare data for processing flat input format.
1679  *
1680  * @param ctx filter context
1681  *
1682  * @return error code
1683  */
1684 static int prepare_flat_in(AVFilterContext *ctx)
1685 {
1686     V360Context *s = ctx->priv;
1687
1688     s->iflat_range[0] = tanf(0.5f * s->ih_fov * M_PI / 180.f);
1689     s->iflat_range[1] = tanf(0.5f * s->iv_fov * M_PI / 180.f);
1690
1691     return 0;
1692 }
1693
1694 /**
1695  * Calculate frame position in flat format for corresponding 3D coordinates on sphere.
1696  *
1697  * @param s filter private context
1698  * @param vec coordinates on sphere
1699  * @param width frame width
1700  * @param height frame height
1701  * @param us horizontal coordinates for interpolation window
1702  * @param vs vertical coordinates for interpolation window
1703  * @param du horizontal relative coordinate
1704  * @param dv vertical relative coordinate
1705  */
1706 static void xyz_to_flat(const V360Context *s,
1707                         const float *vec, int width, int height,
1708                         int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1709 {
1710     const float theta = acosf(vec[2]);
1711     const float r = tanf(theta);
1712     const float rr = fabsf(r) < 1e+6f ? r : hypotf(width, height);
1713     const float zf = -vec[2];
1714     const float h = hypotf(vec[0], vec[1]);
1715     const float c = h <= 1e-6f ? 1.f : rr / h;
1716     float uf = -vec[0] * c / s->iflat_range[0] * s->input_mirror_modifier[0];
1717     float vf =  vec[1] * c / s->iflat_range[1] * s->input_mirror_modifier[1];
1718     int visible, ui, vi;
1719
1720     uf = zf >= 0.f ? (uf + 1.f) * width  / 2.f : 0.f;
1721     vf = zf >= 0.f ? (vf + 1.f) * height / 2.f : 0.f;
1722
1723     ui = floorf(uf);
1724     vi = floorf(vf);
1725
1726     visible = vi >= 0 && vi < height && ui >= 0 && ui < width;
1727
1728     *du = uf - ui;
1729     *dv = vf - vi;
1730
1731     for (int i = -1; i < 3; i++) {
1732         for (int j = -1; j < 3; j++) {
1733             us[i + 1][j + 1] = visible ? av_clip(ui + j, 0, width  - 1) : 0;
1734             vs[i + 1][j + 1] = visible ? av_clip(vi + i, 0, height - 1) : 0;
1735         }
1736     }
1737 }
1738
1739 /**
1740  * Calculate frame position in mercator format for corresponding 3D coordinates on sphere.
1741  *
1742  * @param s filter private context
1743  * @param vec coordinates on sphere
1744  * @param width frame width
1745  * @param height frame height
1746  * @param us horizontal coordinates for interpolation window
1747  * @param vs vertical coordinates for interpolation window
1748  * @param du horizontal relative coordinate
1749  * @param dv vertical relative coordinate
1750  */
1751 static void xyz_to_mercator(const V360Context *s,
1752                             const float *vec, int width, int height,
1753                             int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1754 {
1755     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1756     const float theta = -vec[1] * s->input_mirror_modifier[1];
1757     float uf, vf;
1758     int ui, vi;
1759
1760     uf = (phi / M_PI + 1.f) * width / 2.f;
1761     vf = (av_clipf(logf((1.f + theta) / (1.f - theta)) / (2.f * M_PI), -1.f, 1.f) + 1.f) * height / 2.f;
1762     ui = floorf(uf);
1763     vi = floorf(vf);
1764
1765     *du = uf - ui;
1766     *dv = vf - vi;
1767
1768     for (int i = -1; i < 3; i++) {
1769         for (int j = -1; j < 3; j++) {
1770             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1771             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1772         }
1773     }
1774 }
1775
1776 /**
1777  * Calculate 3D coordinates on sphere for corresponding frame position in mercator format.
1778  *
1779  * @param s filter private context
1780  * @param i horizontal position on frame [0, width)
1781  * @param j vertical position on frame [0, height)
1782  * @param width frame width
1783  * @param height frame height
1784  * @param vec coordinates on sphere
1785  */
1786 static void mercator_to_xyz(const V360Context *s,
1787                             int i, int j, int width, int height,
1788                             float *vec)
1789 {
1790     const float phi = ((2.f * i) / width - 1.f) * M_PI + M_PI_2;
1791     const float y   = ((2.f * j) / height - 1.f) * M_PI;
1792     const float div = expf(2.f * y) + 1.f;
1793
1794     const float sin_phi   = sinf(phi);
1795     const float cos_phi   = cosf(phi);
1796     const float sin_theta = -2.f * expf(y) / div;
1797     const float cos_theta = -(expf(2.f * y) - 1.f) / div;
1798
1799     vec[0] = sin_theta * cos_phi;
1800     vec[1] = cos_theta;
1801     vec[2] = sin_theta * sin_phi;
1802 }
1803
1804 /**
1805  * Calculate frame position in ball format for corresponding 3D coordinates on sphere.
1806  *
1807  * @param s filter private context
1808  * @param vec coordinates on sphere
1809  * @param width frame width
1810  * @param height frame height
1811  * @param us horizontal coordinates for interpolation window
1812  * @param vs vertical coordinates for interpolation window
1813  * @param du horizontal relative coordinate
1814  * @param dv vertical relative coordinate
1815  */
1816 static void xyz_to_ball(const V360Context *s,
1817                         const float *vec, int width, int height,
1818                         int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1819 {
1820     const float l = hypotf(vec[0], vec[1]);
1821     const float r = sqrtf(1.f + vec[2]) / M_SQRT2;
1822     float uf, vf;
1823     int ui, vi;
1824
1825     uf = (1.f + r * vec[0] * s->input_mirror_modifier[0] / (l > 0.f ? l : 1.f)) * width  * 0.5f;
1826     vf = (1.f - r * vec[1] * s->input_mirror_modifier[1] / (l > 0.f ? l : 1.f)) * height * 0.5f;
1827
1828     ui = floorf(uf);
1829     vi = floorf(vf);
1830
1831     *du = uf - ui;
1832     *dv = vf - vi;
1833
1834     for (int i = -1; i < 3; i++) {
1835         for (int j = -1; j < 3; j++) {
1836             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1837             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1838         }
1839     }
1840 }
1841
1842 /**
1843  * Calculate 3D coordinates on sphere for corresponding frame position in ball format.
1844  *
1845  * @param s filter private context
1846  * @param i horizontal position on frame [0, width)
1847  * @param j vertical position on frame [0, height)
1848  * @param width frame width
1849  * @param height frame height
1850  * @param vec coordinates on sphere
1851  */
1852 static void ball_to_xyz(const V360Context *s,
1853                         int i, int j, int width, int height,
1854                         float *vec)
1855 {
1856     const float x = (2.f * i) / width  - 1.f;
1857     const float y = (2.f * j) / height - 1.f;
1858     const float l = hypotf(x, y);
1859
1860     if (l <= 1.f) {
1861         const float z = 2.f * l * sqrtf(1.f - l * l);
1862
1863         vec[0] =  z * x / (l > 0.f ? l : 1.f);
1864         vec[1] = -z * y / (l > 0.f ? l : 1.f);
1865         vec[2] = -1.f + 2.f * l * l;
1866     } else {
1867         vec[0] =  0.f;
1868         vec[1] = -1.f;
1869         vec[2] =  0.f;
1870     }
1871 }
1872
1873 /**
1874  * Calculate 3D coordinates on sphere for corresponding frame position in hammer format.
1875  *
1876  * @param s filter private context
1877  * @param i horizontal position on frame [0, width)
1878  * @param j vertical position on frame [0, height)
1879  * @param width frame width
1880  * @param height frame height
1881  * @param vec coordinates on sphere
1882  */
1883 static void hammer_to_xyz(const V360Context *s,
1884                           int i, int j, int width, int height,
1885                           float *vec)
1886 {
1887     const float x = ((2.f * i) / width  - 1.f);
1888     const float y = ((2.f * j) / height - 1.f);
1889
1890     const float xx = x * x;
1891     const float yy = y * y;
1892
1893     const float z = sqrtf(1.f - xx * 0.5f - yy * 0.5f);
1894
1895     const float a = M_SQRT2 * x * z;
1896     const float b = 2.f * z * z - 1.f;
1897
1898     const float aa = a * a;
1899     const float bb = b * b;
1900
1901     const float w = sqrtf(1.f - 2.f * yy * z * z);
1902
1903     vec[0] =  w * 2.f * a * b / (aa + bb);
1904     vec[1] = -M_SQRT2 * y * z;
1905     vec[2] = -w * (bb  - aa) / (aa + bb);
1906
1907     normalize_vector(vec);
1908 }
1909
1910 /**
1911  * Calculate frame position in hammer format for corresponding 3D coordinates on sphere.
1912  *
1913  * @param s filter private context
1914  * @param vec coordinates on sphere
1915  * @param width frame width
1916  * @param height frame height
1917  * @param us horizontal coordinates for interpolation window
1918  * @param vs vertical coordinates for interpolation window
1919  * @param du horizontal relative coordinate
1920  * @param dv vertical relative coordinate
1921  */
1922 static void xyz_to_hammer(const V360Context *s,
1923                           const float *vec, int width, int height,
1924                           int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1925 {
1926     const float theta = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1927
1928     const float z = sqrtf(1.f + sqrtf(1.f - vec[1] * vec[1]) * cosf(theta * 0.5f));
1929     const float x = sqrtf(1.f - vec[1] * vec[1]) * sinf(theta * 0.5f) / z;
1930     const float y = -vec[1] / z * s->input_mirror_modifier[1];
1931     float uf, vf;
1932     int ui, vi;
1933
1934     uf = (x + 1.f) * width  / 2.f;
1935     vf = (y + 1.f) * height / 2.f;
1936     ui = floorf(uf);
1937     vi = floorf(vf);
1938
1939     *du = uf - ui;
1940     *dv = vf - vi;
1941
1942     for (int i = -1; i < 3; i++) {
1943         for (int j = -1; j < 3; j++) {
1944             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1945             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1946         }
1947     }
1948 }
1949
1950 /**
1951  * Calculate 3D coordinates on sphere for corresponding frame position in sinusoidal format.
1952  *
1953  * @param s filter private context
1954  * @param i horizontal position on frame [0, width)
1955  * @param j vertical position on frame [0, height)
1956  * @param width frame width
1957  * @param height frame height
1958  * @param vec coordinates on sphere
1959  */
1960 static void sinusoidal_to_xyz(const V360Context *s,
1961                               int i, int j, int width, int height,
1962                               float *vec)
1963 {
1964     const float theta = ((2.f * j) / height - 1.f) * M_PI_2;
1965     const float phi   = ((2.f * i) / width  - 1.f) * M_PI / cosf(theta);
1966
1967     const float sin_phi   = sinf(phi);
1968     const float cos_phi   = cosf(phi);
1969     const float sin_theta = sinf(theta);
1970     const float cos_theta = cosf(theta);
1971
1972     vec[0] =  cos_theta * sin_phi;
1973     vec[1] = -sin_theta;
1974     vec[2] = -cos_theta * cos_phi;
1975
1976     normalize_vector(vec);
1977 }
1978
1979 /**
1980  * Calculate frame position in sinusoidal format for corresponding 3D coordinates on sphere.
1981  *
1982  * @param s filter private context
1983  * @param vec coordinates on sphere
1984  * @param width frame width
1985  * @param height frame height
1986  * @param us horizontal coordinates for interpolation window
1987  * @param vs vertical coordinates for interpolation window
1988  * @param du horizontal relative coordinate
1989  * @param dv vertical relative coordinate
1990  */
1991 static void xyz_to_sinusoidal(const V360Context *s,
1992                               const float *vec, int width, int height,
1993                               int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
1994 {
1995     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
1996     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0] * cosf(theta);
1997     float uf, vf;
1998     int ui, vi;
1999
2000     uf = (phi   / M_PI   + 1.f) * width  / 2.f;
2001     vf = (theta / M_PI_2 + 1.f) * height / 2.f;
2002     ui = floorf(uf);
2003     vi = floorf(vf);
2004
2005     *du = uf - ui;
2006     *dv = vf - vi;
2007
2008     for (int i = -1; i < 3; i++) {
2009         for (int j = -1; j < 3; j++) {
2010             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
2011             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
2012         }
2013     }
2014 }
2015
2016 /**
2017  * Prepare data for processing equi-angular cubemap input format.
2018  *
2019  * @param ctx filter context
2020  *
2021  * @return error code
2022  */
2023 static int prepare_eac_in(AVFilterContext *ctx)
2024 {
2025     V360Context *s = ctx->priv;
2026
2027     if (s->ih_flip && s->iv_flip) {
2028         s->in_cubemap_face_order[RIGHT] = BOTTOM_LEFT;
2029         s->in_cubemap_face_order[LEFT]  = BOTTOM_RIGHT;
2030         s->in_cubemap_face_order[UP]    = TOP_LEFT;
2031         s->in_cubemap_face_order[DOWN]  = TOP_RIGHT;
2032         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
2033         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
2034     } else if (s->ih_flip) {
2035         s->in_cubemap_face_order[RIGHT] = TOP_LEFT;
2036         s->in_cubemap_face_order[LEFT]  = TOP_RIGHT;
2037         s->in_cubemap_face_order[UP]    = BOTTOM_LEFT;
2038         s->in_cubemap_face_order[DOWN]  = BOTTOM_RIGHT;
2039         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
2040         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
2041     } else if (s->iv_flip) {
2042         s->in_cubemap_face_order[RIGHT] = BOTTOM_RIGHT;
2043         s->in_cubemap_face_order[LEFT]  = BOTTOM_LEFT;
2044         s->in_cubemap_face_order[UP]    = TOP_RIGHT;
2045         s->in_cubemap_face_order[DOWN]  = TOP_LEFT;
2046         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
2047         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
2048     } else {
2049         s->in_cubemap_face_order[RIGHT] = TOP_RIGHT;
2050         s->in_cubemap_face_order[LEFT]  = TOP_LEFT;
2051         s->in_cubemap_face_order[UP]    = BOTTOM_RIGHT;
2052         s->in_cubemap_face_order[DOWN]  = BOTTOM_LEFT;
2053         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
2054         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
2055     }
2056
2057     if (s->iv_flip) {
2058         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_270;
2059         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_90;
2060         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_270;
2061         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_0;
2062         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_0;
2063         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_0;
2064     } else {
2065         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
2066         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
2067         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
2068         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
2069         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
2070         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
2071     }
2072
2073     return 0;
2074 }
2075
2076 /**
2077  * Prepare data for processing equi-angular cubemap output format.
2078  *
2079  * @param ctx filter context
2080  *
2081  * @return error code
2082  */
2083 static int prepare_eac_out(AVFilterContext *ctx)
2084 {
2085     V360Context *s = ctx->priv;
2086
2087     s->out_cubemap_direction_order[TOP_LEFT]      = LEFT;
2088     s->out_cubemap_direction_order[TOP_MIDDLE]    = FRONT;
2089     s->out_cubemap_direction_order[TOP_RIGHT]     = RIGHT;
2090     s->out_cubemap_direction_order[BOTTOM_LEFT]   = DOWN;
2091     s->out_cubemap_direction_order[BOTTOM_MIDDLE] = BACK;
2092     s->out_cubemap_direction_order[BOTTOM_RIGHT]  = UP;
2093
2094     s->out_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
2095     s->out_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
2096     s->out_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
2097     s->out_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
2098     s->out_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
2099     s->out_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
2100
2101     return 0;
2102 }
2103
2104 /**
2105  * Calculate 3D coordinates on sphere for corresponding frame position in equi-angular cubemap format.
2106  *
2107  * @param s filter private context
2108  * @param i horizontal position on frame [0, width)
2109  * @param j vertical position on frame [0, height)
2110  * @param width frame width
2111  * @param height frame height
2112  * @param vec coordinates on sphere
2113  */
2114 static void eac_to_xyz(const V360Context *s,
2115                        int i, int j, int width, int height,
2116                        float *vec)
2117 {
2118     const float pixel_pad = 2;
2119     const float u_pad = pixel_pad / width;
2120     const float v_pad = pixel_pad / height;
2121
2122     int u_face, v_face, face;
2123
2124     float l_x, l_y, l_z;
2125
2126     float uf = (i + 0.5f) / width;
2127     float vf = (j + 0.5f) / height;
2128
2129     // EAC has 2-pixel padding on faces except between faces on the same row
2130     // Padding pixels seems not to be stretched with tangent as regular pixels
2131     // Formulas below approximate original padding as close as I could get experimentally
2132
2133     // Horizontal padding
2134     uf = 3.f * (uf - u_pad) / (1.f - 2.f * u_pad);
2135     if (uf < 0.f) {
2136         u_face = 0;
2137         uf -= 0.5f;
2138     } else if (uf >= 3.f) {
2139         u_face = 2;
2140         uf -= 2.5f;
2141     } else {
2142         u_face = floorf(uf);
2143         uf = fmodf(uf, 1.f) - 0.5f;
2144     }
2145
2146     // Vertical padding
2147     v_face = floorf(vf * 2.f);
2148     vf = (vf - v_pad - 0.5f * v_face) / (0.5f - 2.f * v_pad) - 0.5f;
2149
2150     if (uf >= -0.5f && uf < 0.5f) {
2151         uf = tanf(M_PI_2 * uf);
2152     } else {
2153         uf = 2.f * uf;
2154     }
2155     if (vf >= -0.5f && vf < 0.5f) {
2156         vf = tanf(M_PI_2 * vf);
2157     } else {
2158         vf = 2.f * vf;
2159     }
2160
2161     face = u_face + 3 * v_face;
2162
2163     switch (face) {
2164     case TOP_LEFT:
2165         l_x = -1.f;
2166         l_y = -vf;
2167         l_z = -uf;
2168         break;
2169     case TOP_MIDDLE:
2170         l_x =  uf;
2171         l_y = -vf;
2172         l_z = -1.f;
2173         break;
2174     case TOP_RIGHT:
2175         l_x =  1.f;
2176         l_y = -vf;
2177         l_z =  uf;
2178         break;
2179     case BOTTOM_LEFT:
2180         l_x = -vf;
2181         l_y = -1.f;
2182         l_z =  uf;
2183         break;
2184     case BOTTOM_MIDDLE:
2185         l_x = -vf;
2186         l_y =  uf;
2187         l_z =  1.f;
2188         break;
2189     case BOTTOM_RIGHT:
2190         l_x = -vf;
2191         l_y =  1.f;
2192         l_z = -uf;
2193         break;
2194     default:
2195         av_assert0(0);
2196     }
2197
2198     vec[0] = l_x;
2199     vec[1] = l_y;
2200     vec[2] = l_z;
2201
2202     normalize_vector(vec);
2203 }
2204
2205 /**
2206  * Calculate frame position in equi-angular cubemap format for corresponding 3D coordinates on sphere.
2207  *
2208  * @param s filter private context
2209  * @param vec coordinates on sphere
2210  * @param width frame width
2211  * @param height frame height
2212  * @param us horizontal coordinates for interpolation window
2213  * @param vs vertical coordinates for interpolation window
2214  * @param du horizontal relative coordinate
2215  * @param dv vertical relative coordinate
2216  */
2217 static void xyz_to_eac(const V360Context *s,
2218                        const float *vec, int width, int height,
2219                        int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
2220 {
2221     const float pixel_pad = 2;
2222     const float u_pad = pixel_pad / width;
2223     const float v_pad = pixel_pad / height;
2224
2225     float uf, vf;
2226     int ui, vi;
2227     int direction, face;
2228     int u_face, v_face;
2229
2230     xyz_to_cube(s, vec, &uf, &vf, &direction);
2231
2232     face = s->in_cubemap_face_order[direction];
2233     u_face = face % 3;
2234     v_face = face / 3;
2235
2236     uf = M_2_PI * atanf(uf) + 0.5f;
2237     vf = M_2_PI * atanf(vf) + 0.5f;
2238
2239     // These formulas are inversed from eac_to_xyz ones
2240     uf = (uf + u_face) * (1.f - 2.f * u_pad) / 3.f + u_pad;
2241     vf = vf * (0.5f - 2.f * v_pad) + v_pad + 0.5f * v_face;
2242
2243     uf *= width;
2244     vf *= height;
2245
2246     uf -= 0.5f;
2247     vf -= 0.5f;
2248
2249     ui = floorf(uf);
2250     vi = floorf(vf);
2251
2252     *du = uf - ui;
2253     *dv = vf - vi;
2254
2255     for (int i = -1; i < 3; i++) {
2256         for (int j = -1; j < 3; j++) {
2257             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
2258             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
2259         }
2260     }
2261 }
2262
2263 /**
2264  * Prepare data for processing flat output format.
2265  *
2266  * @param ctx filter context
2267  *
2268  * @return error code
2269  */
2270 static int prepare_flat_out(AVFilterContext *ctx)
2271 {
2272     V360Context *s = ctx->priv;
2273
2274     s->flat_range[0] = tanf(0.5f * s->h_fov * M_PI / 180.f);
2275     s->flat_range[1] = tanf(0.5f * s->v_fov * M_PI / 180.f);
2276
2277     return 0;
2278 }
2279
2280 /**
2281  * Calculate 3D coordinates on sphere for corresponding frame position in flat format.
2282  *
2283  * @param s filter private context
2284  * @param i horizontal position on frame [0, width)
2285  * @param j vertical position on frame [0, height)
2286  * @param width frame width
2287  * @param height frame height
2288  * @param vec coordinates on sphere
2289  */
2290 static void flat_to_xyz(const V360Context *s,
2291                         int i, int j, int width, int height,
2292                         float *vec)
2293 {
2294     const float l_x =  s->flat_range[0] * (2.f * i / width  - 1.f);
2295     const float l_y = -s->flat_range[1] * (2.f * j / height - 1.f);
2296
2297     vec[0] =  l_x;
2298     vec[1] =  l_y;
2299     vec[2] = -1.f;
2300
2301     normalize_vector(vec);
2302 }
2303
2304 /**
2305  * Prepare data for processing fisheye output format.
2306  *
2307  * @param ctx filter context
2308  *
2309  * @return error code
2310  */
2311 static int prepare_fisheye_out(AVFilterContext *ctx)
2312 {
2313     V360Context *s = ctx->priv;
2314
2315     s->flat_range[0] = s->h_fov / 180.f;
2316     s->flat_range[1] = s->v_fov / 180.f;
2317
2318     return 0;
2319 }
2320
2321 /**
2322  * Calculate 3D coordinates on sphere for corresponding frame position in fisheye format.
2323  *
2324  * @param s filter private context
2325  * @param i horizontal position on frame [0, width)
2326  * @param j vertical position on frame [0, height)
2327  * @param width frame width
2328  * @param height frame height
2329  * @param vec coordinates on sphere
2330  */
2331 static void fisheye_to_xyz(const V360Context *s,
2332                            int i, int j, int width, int height,
2333                            float *vec)
2334 {
2335     const float uf = s->flat_range[0] * ((2.f * i) / width  - 1.f);
2336     const float vf = s->flat_range[1] * ((2.f * j) / height - 1.f);
2337
2338     const float phi   = -atan2f(vf, uf);
2339     const float theta = -M_PI_2 * (1.f - hypotf(uf, vf));
2340
2341     vec[0] = cosf(theta) * cosf(phi);
2342     vec[1] = cosf(theta) * sinf(phi);
2343     vec[2] = sinf(theta);
2344
2345     normalize_vector(vec);
2346 }
2347
2348 /**
2349  * Calculate 3D coordinates on sphere for corresponding frame position in pannini format.
2350  *
2351  * @param s filter private context
2352  * @param i horizontal position on frame [0, width)
2353  * @param j vertical position on frame [0, height)
2354  * @param width frame width
2355  * @param height frame height
2356  * @param vec coordinates on sphere
2357  */
2358 static void pannini_to_xyz(const V360Context *s,
2359                            int i, int j, int width, int height,
2360                            float *vec)
2361 {
2362     const float uf = ((2.f * i) / width  - 1.f);
2363     const float vf = ((2.f * j) / height - 1.f);
2364
2365     const float d = s->h_fov;
2366     const float k = uf * uf / ((d + 1.f) * (d + 1.f));
2367     const float dscr = k * k * d * d - (k + 1.f) * (k * d * d - 1.f);
2368     const float clon = (-k * d + sqrtf(dscr)) / (k + 1.f);
2369     const float S = (d + 1.f) / (d + clon);
2370     const float lon = -(M_PI + atan2f(uf, S * clon));
2371     const float lat = -atan2f(vf, S);
2372
2373     vec[0] = sinf(lon) * cosf(lat);
2374     vec[1] = sinf(lat);
2375     vec[2] = cosf(lon) * cosf(lat);
2376
2377     normalize_vector(vec);
2378 }
2379
2380 /**
2381  * Prepare data for processing cylindrical output format.
2382  *
2383  * @param ctx filter context
2384  *
2385  * @return error code
2386  */
2387 static int prepare_cylindrical_out(AVFilterContext *ctx)
2388 {
2389     V360Context *s = ctx->priv;
2390
2391     s->flat_range[0] = M_PI * s->h_fov / 360.f;
2392     s->flat_range[1] = tanf(0.5f * s->v_fov * M_PI / 180.f);
2393
2394     return 0;
2395 }
2396
2397 /**
2398  * Calculate 3D coordinates on sphere for corresponding frame position in cylindrical format.
2399  *
2400  * @param s filter private context
2401  * @param i horizontal position on frame [0, width)
2402  * @param j vertical position on frame [0, height)
2403  * @param width frame width
2404  * @param height frame height
2405  * @param vec coordinates on sphere
2406  */
2407 static void cylindrical_to_xyz(const V360Context *s,
2408                                int i, int j, int width, int height,
2409                                float *vec)
2410 {
2411     const float uf = s->flat_range[0] * ((2.f * i) / width  - 1.f);
2412     const float vf = s->flat_range[1] * ((2.f * j) / height - 1.f);
2413
2414     const float phi   = uf;
2415     const float theta = atanf(vf);
2416
2417     const float sin_phi   = sinf(phi);
2418     const float cos_phi   = cosf(phi);
2419     const float sin_theta = sinf(theta);
2420     const float cos_theta = cosf(theta);
2421
2422     vec[0] =  cos_theta * sin_phi;
2423     vec[1] = -sin_theta;
2424     vec[2] = -cos_theta * cos_phi;
2425
2426     normalize_vector(vec);
2427 }
2428
2429 /**
2430  * Prepare data for processing cylindrical input format.
2431  *
2432  * @param ctx filter context
2433  *
2434  * @return error code
2435  */
2436 static int prepare_cylindrical_in(AVFilterContext *ctx)
2437 {
2438     V360Context *s = ctx->priv;
2439
2440     s->iflat_range[0] = M_PI * s->ih_fov / 360.f;
2441     s->iflat_range[1] = tanf(0.5f * s->iv_fov * M_PI / 180.f);
2442
2443     return 0;
2444 }
2445
2446 /**
2447  * Calculate frame position in cylindrical format for corresponding 3D coordinates on sphere.
2448  *
2449  * @param s filter private context
2450  * @param vec coordinates on sphere
2451  * @param width frame width
2452  * @param height frame height
2453  * @param us horizontal coordinates for interpolation window
2454  * @param vs vertical coordinates for interpolation window
2455  * @param du horizontal relative coordinate
2456  * @param dv vertical relative coordinate
2457  */
2458 static void xyz_to_cylindrical(const V360Context *s,
2459                                const float *vec, int width, int height,
2460                                int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
2461 {
2462     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0] / s->iflat_range[0];
2463     const float theta = atan2f(-vec[1], hypotf(vec[0], vec[2])) * s->input_mirror_modifier[1] / s->iflat_range[1];
2464     int visible, ui, vi;
2465     float uf, vf;
2466
2467     uf = (phi + 1.f) * (width - 1) / 2.f;
2468     vf = (tanf(theta) + 1.f) * height / 2.f;
2469     ui = floorf(uf);
2470     vi = floorf(vf);
2471
2472     visible = vi >= 0 && vi < height && ui >= 0 && ui < width &&
2473               theta <=  M_PI * s->iv_fov / 180.f &&
2474               theta >= -M_PI * s->iv_fov / 180.f;
2475
2476     *du = uf - ui;
2477     *dv = vf - vi;
2478
2479     for (int i = -1; i < 3; i++) {
2480         for (int j = -1; j < 3; j++) {
2481             us[i + 1][j + 1] = visible ? av_clip(ui + j, 0, width  - 1) : 0;
2482             vs[i + 1][j + 1] = visible ? av_clip(vi + i, 0, height - 1) : 0;
2483         }
2484     }
2485 }
2486
2487 /**
2488  * Calculate 3D coordinates on sphere for corresponding frame position in perspective format.
2489  *
2490  * @param s filter private context
2491  * @param i horizontal position on frame [0, width)
2492  * @param j vertical position on frame [0, height)
2493  * @param width frame width
2494  * @param height frame height
2495  * @param vec coordinates on sphere
2496  */
2497 static void perspective_to_xyz(const V360Context *s,
2498                                int i, int j, int width, int height,
2499                                float *vec)
2500 {
2501     const float uf = ((2.f * i) / width  - 1.f);
2502     const float vf = ((2.f * j) / height - 1.f);
2503     const float rh = hypotf(uf, vf);
2504     const float sinzz = 1.f - rh * rh;
2505     const float h = 1.f + s->v_fov;
2506     const float sinz = (h - sqrtf(sinzz)) / (h / rh + rh / h);
2507     const float sinz2 = sinz * sinz;
2508
2509     if (sinz2 <= 1.f) {
2510         const float cosz = sqrtf(1.f - sinz2);
2511
2512         const float theta = asinf(cosz);
2513         const float phi   = atan2f(uf, vf);
2514
2515         const float sin_phi   = sinf(phi);
2516         const float cos_phi   = cosf(phi);
2517         const float sin_theta = sinf(theta);
2518         const float cos_theta = cosf(theta);
2519
2520         vec[0] =  cos_theta * sin_phi;
2521         vec[1] =  sin_theta;
2522         vec[2] = -cos_theta * cos_phi;
2523     } else {
2524         vec[0] =  0.f;
2525         vec[1] = -1.f;
2526         vec[2] =  0.f;
2527     }
2528
2529     normalize_vector(vec);
2530 }
2531
2532 /**
2533  * Calculate 3D coordinates on sphere for corresponding frame position in dual fisheye format.
2534  *
2535  * @param s filter private context
2536  * @param i horizontal position on frame [0, width)
2537  * @param j vertical position on frame [0, height)
2538  * @param width frame width
2539  * @param height frame height
2540  * @param vec coordinates on sphere
2541  */
2542 static void dfisheye_to_xyz(const V360Context *s,
2543                             int i, int j, int width, int height,
2544                             float *vec)
2545 {
2546     const float scale = 1.f + s->out_pad;
2547
2548     const float ew = width / 2.f;
2549     const float eh = height;
2550
2551     const int ei = i >= ew ? i - ew : i;
2552     const float m = i >= ew ? -1.f : 1.f;
2553
2554     const float uf = ((2.f * ei) / ew - 1.f) * scale;
2555     const float vf = ((2.f *  j) / eh - 1.f) * scale;
2556
2557     const float h     = hypotf(uf, vf);
2558     const float lh    = h > 0.f ? h : 1.f;
2559     const float theta = m * M_PI_2 * (1.f - h);
2560
2561     const float sin_theta = sinf(theta);
2562     const float cos_theta = cosf(theta);
2563
2564     vec[0] = cos_theta * m * -uf / lh;
2565     vec[1] = cos_theta *     -vf / lh;
2566     vec[2] = sin_theta;
2567
2568     normalize_vector(vec);
2569 }
2570
2571 /**
2572  * Calculate frame position in dual fisheye format for corresponding 3D coordinates on sphere.
2573  *
2574  * @param s filter private context
2575  * @param vec coordinates on sphere
2576  * @param width frame width
2577  * @param height frame height
2578  * @param us horizontal coordinates for interpolation window
2579  * @param vs vertical coordinates for interpolation window
2580  * @param du horizontal relative coordinate
2581  * @param dv vertical relative coordinate
2582  */
2583 static void xyz_to_dfisheye(const V360Context *s,
2584                             const float *vec, int width, int height,
2585                             int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
2586 {
2587     const float scale = 1.f - s->in_pad;
2588
2589     const float ew = width / 2.f;
2590     const float eh = height;
2591
2592     const float h     = hypotf(vec[0], vec[1]);
2593     const float lh    = h > 0.f ? h : 1.f;
2594     const float theta = acosf(fabsf(vec[2])) / M_PI;
2595
2596     float uf = (theta * (-vec[0] / lh) * s->input_mirror_modifier[0] * scale + 0.5f) * ew;
2597     float vf = (theta * (-vec[1] / lh) * s->input_mirror_modifier[1] * scale + 0.5f) * eh;
2598
2599     int ui, vi;
2600     int u_shift;
2601
2602     if (vec[2] >= 0.f) {
2603         u_shift = 0;
2604     } else {
2605         u_shift = ceilf(ew);
2606         uf = ew - uf;
2607     }
2608
2609     ui = floorf(uf);
2610     vi = floorf(vf);
2611
2612     *du = uf - ui;
2613     *dv = vf - vi;
2614
2615     for (int i = -1; i < 3; i++) {
2616         for (int j = -1; j < 3; j++) {
2617             us[i + 1][j + 1] = av_clip(u_shift + ui + j, 0, width  - 1);
2618             vs[i + 1][j + 1] = av_clip(          vi + i, 0, height - 1);
2619         }
2620     }
2621 }
2622
2623 /**
2624  * Calculate 3D coordinates on sphere for corresponding frame position in barrel facebook's format.
2625  *
2626  * @param s filter private context
2627  * @param i horizontal position on frame [0, width)
2628  * @param j vertical position on frame [0, height)
2629  * @param width frame width
2630  * @param height frame height
2631  * @param vec coordinates on sphere
2632  */
2633 static void barrel_to_xyz(const V360Context *s,
2634                           int i, int j, int width, int height,
2635                           float *vec)
2636 {
2637     const float scale = 0.99f;
2638     float l_x, l_y, l_z;
2639
2640     if (i < 4 * width / 5) {
2641         const float theta_range = M_PI_4;
2642
2643         const int ew = 4 * width / 5;
2644         const int eh = height;
2645
2646         const float phi   = ((2.f * i) / ew - 1.f) * M_PI        / scale;
2647         const float theta = ((2.f * j) / eh - 1.f) * theta_range / scale;
2648
2649         const float sin_phi   = sinf(phi);
2650         const float cos_phi   = cosf(phi);
2651         const float sin_theta = sinf(theta);
2652         const float cos_theta = cosf(theta);
2653
2654         l_x =  cos_theta * sin_phi;
2655         l_y = -sin_theta;
2656         l_z = -cos_theta * cos_phi;
2657     } else {
2658         const int ew = width  / 5;
2659         const int eh = height / 2;
2660
2661         float uf, vf;
2662
2663         if (j < eh) {   // UP
2664             uf = 2.f * (i - 4 * ew) / ew  - 1.f;
2665             vf = 2.f * (j         ) / eh - 1.f;
2666
2667             uf /= scale;
2668             vf /= scale;
2669
2670             l_x =  uf;
2671             l_y =  1.f;
2672             l_z = -vf;
2673         } else {            // DOWN
2674             uf = 2.f * (i - 4 * ew) / ew - 1.f;
2675             vf = 2.f * (j -     eh) / eh - 1.f;
2676
2677             uf /= scale;
2678             vf /= scale;
2679
2680             l_x =  uf;
2681             l_y = -1.f;
2682             l_z =  vf;
2683         }
2684     }
2685
2686     vec[0] = l_x;
2687     vec[1] = l_y;
2688     vec[2] = l_z;
2689
2690     normalize_vector(vec);
2691 }
2692
2693 /**
2694  * Calculate frame position in barrel facebook's format for corresponding 3D coordinates on sphere.
2695  *
2696  * @param s filter private context
2697  * @param vec coordinates on sphere
2698  * @param width frame width
2699  * @param height frame height
2700  * @param us horizontal coordinates for interpolation window
2701  * @param vs vertical coordinates for interpolation window
2702  * @param du horizontal relative coordinate
2703  * @param dv vertical relative coordinate
2704  */
2705 static void xyz_to_barrel(const V360Context *s,
2706                           const float *vec, int width, int height,
2707                           int16_t us[4][4], int16_t vs[4][4], float *du, float *dv)
2708 {
2709     const float scale = 0.99f;
2710
2711     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
2712     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
2713     const float theta_range = M_PI_4;
2714
2715     int ew, eh;
2716     int u_shift, v_shift;
2717     float uf, vf;
2718     int ui, vi;
2719
2720     if (theta > -theta_range && theta < theta_range) {
2721         ew = 4 * width / 5;
2722         eh = height;
2723
2724         u_shift = s->ih_flip ? width / 5 : 0;
2725         v_shift = 0;
2726
2727         uf = (phi   / M_PI        * scale + 1.f) * ew / 2.f;
2728         vf = (theta / theta_range * scale + 1.f) * eh / 2.f;
2729     } else {
2730         ew = width  / 5;
2731         eh = height / 2;
2732
2733         u_shift = s->ih_flip ? 0 : 4 * ew;
2734
2735         if (theta < 0.f) {  // UP
2736             uf =  vec[0] / vec[1];
2737             vf = -vec[2] / vec[1];
2738             v_shift = 0;
2739         } else {            // DOWN
2740             uf = -vec[0] / vec[1];
2741             vf = -vec[2] / vec[1];
2742             v_shift = eh;
2743         }
2744
2745         uf *= s->input_mirror_modifier[0] * s->input_mirror_modifier[1];
2746         vf *= s->input_mirror_modifier[1];
2747
2748         uf = 0.5f * ew * (uf * scale + 1.f);
2749         vf = 0.5f * eh * (vf * scale + 1.f);
2750     }
2751
2752     ui = floorf(uf);
2753     vi = floorf(vf);
2754
2755     *du = uf - ui;
2756     *dv = vf - vi;
2757
2758     for (int i = -1; i < 3; i++) {
2759         for (int j = -1; j < 3; j++) {
2760             us[i + 1][j + 1] = u_shift + av_clip(ui + j, 0, ew - 1);
2761             vs[i + 1][j + 1] = v_shift + av_clip(vi + i, 0, eh - 1);
2762         }
2763     }
2764 }
2765
2766 static void multiply_matrix(float c[3][3], const float a[3][3], const float b[3][3])
2767 {
2768     for (int i = 0; i < 3; i++) {
2769         for (int j = 0; j < 3; j++) {
2770             float sum = 0.f;
2771
2772             for (int k = 0; k < 3; k++)
2773                 sum += a[i][k] * b[k][j];
2774
2775             c[i][j] = sum;
2776         }
2777     }
2778 }
2779
2780 /**
2781  * Calculate rotation matrix for yaw/pitch/roll angles.
2782  */
2783 static inline void calculate_rotation_matrix(float yaw, float pitch, float roll,
2784                                              float rot_mat[3][3],
2785                                              const int rotation_order[3])
2786 {
2787     const float yaw_rad   = yaw   * M_PI / 180.f;
2788     const float pitch_rad = pitch * M_PI / 180.f;
2789     const float roll_rad  = roll  * M_PI / 180.f;
2790
2791     const float sin_yaw   = sinf(-yaw_rad);
2792     const float cos_yaw   = cosf(-yaw_rad);
2793     const float sin_pitch = sinf(pitch_rad);
2794     const float cos_pitch = cosf(pitch_rad);
2795     const float sin_roll  = sinf(roll_rad);
2796     const float cos_roll  = cosf(roll_rad);
2797
2798     float m[3][3][3];
2799     float temp[3][3];
2800
2801     m[0][0][0] =  cos_yaw;  m[0][0][1] = 0;          m[0][0][2] =  sin_yaw;
2802     m[0][1][0] =  0;        m[0][1][1] = 1;          m[0][1][2] =  0;
2803     m[0][2][0] = -sin_yaw;  m[0][2][1] = 0;          m[0][2][2] =  cos_yaw;
2804
2805     m[1][0][0] = 1;         m[1][0][1] = 0;          m[1][0][2] =  0;
2806     m[1][1][0] = 0;         m[1][1][1] = cos_pitch;  m[1][1][2] = -sin_pitch;
2807     m[1][2][0] = 0;         m[1][2][1] = sin_pitch;  m[1][2][2] =  cos_pitch;
2808
2809     m[2][0][0] = cos_roll;  m[2][0][1] = -sin_roll;  m[2][0][2] =  0;
2810     m[2][1][0] = sin_roll;  m[2][1][1] =  cos_roll;  m[2][1][2] =  0;
2811     m[2][2][0] = 0;         m[2][2][1] =  0;         m[2][2][2] =  1;
2812
2813     multiply_matrix(temp, m[rotation_order[0]], m[rotation_order[1]]);
2814     multiply_matrix(rot_mat, temp, m[rotation_order[2]]);
2815 }
2816
2817 /**
2818  * Rotate vector with given rotation matrix.
2819  *
2820  * @param rot_mat rotation matrix
2821  * @param vec vector
2822  */
2823 static inline void rotate(const float rot_mat[3][3],
2824                           float *vec)
2825 {
2826     const float x_tmp = vec[0] * rot_mat[0][0] + vec[1] * rot_mat[0][1] + vec[2] * rot_mat[0][2];
2827     const float y_tmp = vec[0] * rot_mat[1][0] + vec[1] * rot_mat[1][1] + vec[2] * rot_mat[1][2];
2828     const float z_tmp = vec[0] * rot_mat[2][0] + vec[1] * rot_mat[2][1] + vec[2] * rot_mat[2][2];
2829
2830     vec[0] = x_tmp;
2831     vec[1] = y_tmp;
2832     vec[2] = z_tmp;
2833 }
2834
2835 static inline void set_mirror_modifier(int h_flip, int v_flip, int d_flip,
2836                                        float *modifier)
2837 {
2838     modifier[0] = h_flip ? -1.f : 1.f;
2839     modifier[1] = v_flip ? -1.f : 1.f;
2840     modifier[2] = d_flip ? -1.f : 1.f;
2841 }
2842
2843 static inline void mirror(const float *modifier, float *vec)
2844 {
2845     vec[0] *= modifier[0];
2846     vec[1] *= modifier[1];
2847     vec[2] *= modifier[2];
2848 }
2849
2850 static int allocate_plane(V360Context *s, int sizeof_uv, int sizeof_ker, int p)
2851 {
2852     s->u[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_uv);
2853     s->v[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_uv);
2854     if (!s->u[p] || !s->v[p])
2855         return AVERROR(ENOMEM);
2856     if (sizeof_ker) {
2857         s->ker[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_ker);
2858         if (!s->ker[p])
2859             return AVERROR(ENOMEM);
2860     }
2861
2862     return 0;
2863 }
2864
2865 static void fov_from_dfov(float d_fov, float w, float h, float *h_fov, float *v_fov)
2866 {
2867     const float da = tanf(0.5 * FFMIN(d_fov, 359.f) * M_PI / 180.f);
2868     const float d = hypotf(w, h);
2869
2870     *h_fov = atan2f(da * w, d) * 360.f / M_PI;
2871     *v_fov = atan2f(da * h, d) * 360.f / M_PI;
2872
2873     if (*h_fov < 0.f)
2874         *h_fov += 360.f;
2875     if (*v_fov < 0.f)
2876         *v_fov += 360.f;
2877 }
2878
2879 static void set_dimensions(int *outw, int *outh, int w, int h, const AVPixFmtDescriptor *desc)
2880 {
2881     outw[1] = outw[2] = FF_CEIL_RSHIFT(w, desc->log2_chroma_w);
2882     outw[0] = outw[3] = w;
2883     outh[1] = outh[2] = FF_CEIL_RSHIFT(h, desc->log2_chroma_h);
2884     outh[0] = outh[3] = h;
2885 }
2886
2887 // Calculate remap data
2888 static av_always_inline int v360_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
2889 {
2890     V360Context *s = ctx->priv;
2891
2892     for (int p = 0; p < s->nb_allocated; p++) {
2893         const int width = s->pr_width[p];
2894         const int uv_linesize = s->uv_linesize[p];
2895         const int height = s->pr_height[p];
2896         const int in_width = s->inplanewidth[p];
2897         const int in_height = s->inplaneheight[p];
2898         const int slice_start = (height *  jobnr     ) / nb_jobs;
2899         const int slice_end   = (height * (jobnr + 1)) / nb_jobs;
2900         float du, dv;
2901         float vec[3];
2902         XYRemap rmap;
2903
2904         for (int j = slice_start; j < slice_end; j++) {
2905             for (int i = 0; i < width; i++) {
2906                 int16_t *u = s->u[p] + (j * uv_linesize + i) * s->elements;
2907                 int16_t *v = s->v[p] + (j * uv_linesize + i) * s->elements;
2908                 int16_t *ker = s->ker[p] + (j * uv_linesize + i) * s->elements;
2909
2910                 if (s->out_transpose)
2911                     s->out_transform(s, j, i, height, width, vec);
2912                 else
2913                     s->out_transform(s, i, j, width, height, vec);
2914                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2915                 rotate(s->rot_mat, vec);
2916                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2917                 normalize_vector(vec);
2918                 mirror(s->output_mirror_modifier, vec);
2919                 if (s->in_transpose)
2920                     s->in_transform(s, vec, in_height, in_width, rmap.v, rmap.u, &du, &dv);
2921                 else
2922                     s->in_transform(s, vec, in_width, in_height, rmap.u, rmap.v, &du, &dv);
2923                 av_assert1(!isnan(du) && !isnan(dv));
2924                 s->calculate_kernel(du, dv, &rmap, u, v, ker);
2925             }
2926         }
2927     }
2928
2929     return 0;
2930 }
2931
2932 static int config_output(AVFilterLink *outlink)
2933 {
2934     AVFilterContext *ctx = outlink->src;
2935     AVFilterLink *inlink = ctx->inputs[0];
2936     V360Context *s = ctx->priv;
2937     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
2938     const int depth = desc->comp[0].depth;
2939     int sizeof_uv;
2940     int sizeof_ker;
2941     int err;
2942     int h, w;
2943     int in_offset_h, in_offset_w;
2944     int out_offset_h, out_offset_w;
2945     float hf, wf;
2946     int (*prepare_out)(AVFilterContext *ctx);
2947
2948     s->input_mirror_modifier[0] = s->ih_flip ? -1.f : 1.f;
2949     s->input_mirror_modifier[1] = s->iv_flip ? -1.f : 1.f;
2950
2951     switch (s->interp) {
2952     case NEAREST:
2953         s->calculate_kernel = nearest_kernel;
2954         s->remap_slice = depth <= 8 ? remap1_8bit_slice : remap1_16bit_slice;
2955         s->elements = 1;
2956         sizeof_uv = sizeof(int16_t) * s->elements;
2957         sizeof_ker = 0;
2958         break;
2959     case BILINEAR:
2960         s->calculate_kernel = bilinear_kernel;
2961         s->remap_slice = depth <= 8 ? remap2_8bit_slice : remap2_16bit_slice;
2962         s->elements = 2 * 2;
2963         sizeof_uv = sizeof(int16_t) * s->elements;
2964         sizeof_ker = sizeof(int16_t) * s->elements;
2965         break;
2966     case BICUBIC:
2967         s->calculate_kernel = bicubic_kernel;
2968         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2969         s->elements = 4 * 4;
2970         sizeof_uv = sizeof(int16_t) * s->elements;
2971         sizeof_ker = sizeof(int16_t) * s->elements;
2972         break;
2973     case LANCZOS:
2974         s->calculate_kernel = lanczos_kernel;
2975         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2976         s->elements = 4 * 4;
2977         sizeof_uv = sizeof(int16_t) * s->elements;
2978         sizeof_ker = sizeof(int16_t) * s->elements;
2979         break;
2980     case SPLINE16:
2981         s->calculate_kernel = spline16_kernel;
2982         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2983         s->elements = 4 * 4;
2984         sizeof_uv = sizeof(int16_t) * s->elements;
2985         sizeof_ker = sizeof(int16_t) * s->elements;
2986         break;
2987     case GAUSSIAN:
2988         s->calculate_kernel = gaussian_kernel;
2989         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2990         s->elements = 4 * 4;
2991         sizeof_uv = sizeof(int16_t) * s->elements;
2992         sizeof_ker = sizeof(int16_t) * s->elements;
2993         break;
2994     default:
2995         av_assert0(0);
2996     }
2997
2998     ff_v360_init(s, depth);
2999
3000     for (int order = 0; order < NB_RORDERS; order++) {
3001         const char c = s->rorder[order];
3002         int rorder;
3003
3004         if (c == '\0') {
3005             av_log(ctx, AV_LOG_ERROR,
3006                    "Incomplete rorder option. Direction for all 3 rotation orders should be specified.\n");
3007             return AVERROR(EINVAL);
3008         }
3009
3010         rorder = get_rorder(c);
3011         if (rorder == -1) {
3012             av_log(ctx, AV_LOG_ERROR,
3013                    "Incorrect rotation order symbol '%c' in rorder option.\n", c);
3014             return AVERROR(EINVAL);
3015         }
3016
3017         s->rotation_order[order] = rorder;
3018     }
3019
3020     switch (s->in_stereo) {
3021     case STEREO_2D:
3022         w = inlink->w;
3023         h = inlink->h;
3024         in_offset_w = in_offset_h = 0;
3025         break;
3026     case STEREO_SBS:
3027         w = inlink->w / 2;
3028         h = inlink->h;
3029         in_offset_w = w;
3030         in_offset_h = 0;
3031         break;
3032     case STEREO_TB:
3033         w = inlink->w;
3034         h = inlink->h / 2;
3035         in_offset_w = 0;
3036         in_offset_h = h;
3037         break;
3038     default:
3039         av_assert0(0);
3040     }
3041
3042     set_dimensions(s->inplanewidth, s->inplaneheight, w, h, desc);
3043     set_dimensions(s->in_offset_w, s->in_offset_h, in_offset_w, in_offset_h, desc);
3044
3045     s->in_width = s->inplanewidth[0];
3046     s->in_height = s->inplaneheight[0];
3047
3048     if (s->id_fov > 0.f)
3049         fov_from_dfov(s->id_fov, w, h, &s->ih_fov, &s->iv_fov);
3050
3051     if (s->in_transpose)
3052         FFSWAP(int, s->in_width, s->in_height);
3053
3054     switch (s->in) {
3055     case EQUIRECTANGULAR:
3056         s->in_transform = xyz_to_equirect;
3057         err = 0;
3058         wf = w;
3059         hf = h;
3060         break;
3061     case CUBEMAP_3_2:
3062         s->in_transform = xyz_to_cube3x2;
3063         err = prepare_cube_in(ctx);
3064         wf = w / 3.f * 4.f;
3065         hf = h;
3066         break;
3067     case CUBEMAP_1_6:
3068         s->in_transform = xyz_to_cube1x6;
3069         err = prepare_cube_in(ctx);
3070         wf = w * 4.f;
3071         hf = h / 3.f;
3072         break;
3073     case CUBEMAP_6_1:
3074         s->in_transform = xyz_to_cube6x1;
3075         err = prepare_cube_in(ctx);
3076         wf = w / 3.f * 2.f;
3077         hf = h * 2.f;
3078         break;
3079     case EQUIANGULAR:
3080         s->in_transform = xyz_to_eac;
3081         err = prepare_eac_in(ctx);
3082         wf = w;
3083         hf = h / 9.f * 8.f;
3084         break;
3085     case FLAT:
3086         s->in_transform = xyz_to_flat;
3087         err = prepare_flat_in(ctx);
3088         wf = w;
3089         hf = h;
3090         break;
3091     case PERSPECTIVE:
3092     case PANNINI:
3093     case FISHEYE:
3094         av_log(ctx, AV_LOG_ERROR, "Supplied format is not accepted as input.\n");
3095         return AVERROR(EINVAL);
3096     case DUAL_FISHEYE:
3097         s->in_transform = xyz_to_dfisheye;
3098         err = 0;
3099         wf = w;
3100         hf = h;
3101         break;
3102     case BARREL:
3103         s->in_transform = xyz_to_barrel;
3104         err = 0;
3105         wf = w / 5.f * 4.f;
3106         hf = h;
3107         break;
3108     case STEREOGRAPHIC:
3109         s->in_transform = xyz_to_stereographic;
3110         err = prepare_stereographic_in(ctx);
3111         wf = w;
3112         hf = h / 2.f;
3113         break;
3114     case MERCATOR:
3115         s->in_transform = xyz_to_mercator;
3116         err = 0;
3117         wf = w;
3118         hf = h / 2.f;
3119         break;
3120     case BALL:
3121         s->in_transform = xyz_to_ball;
3122         err = 0;
3123         wf = w;
3124         hf = h / 2.f;
3125         break;
3126     case HAMMER:
3127         s->in_transform = xyz_to_hammer;
3128         err = 0;
3129         wf = w;
3130         hf = h;
3131         break;
3132     case SINUSOIDAL:
3133         s->in_transform = xyz_to_sinusoidal;
3134         err = 0;
3135         wf = w;
3136         hf = h;
3137         break;
3138     case CYLINDRICAL:
3139         s->in_transform = xyz_to_cylindrical;
3140         err = prepare_cylindrical_in(ctx);
3141         wf = w;
3142         hf = h * 2.f;
3143         break;
3144     default:
3145         av_log(ctx, AV_LOG_ERROR, "Specified input format is not handled.\n");
3146         return AVERROR_BUG;
3147     }
3148
3149     if (err != 0) {
3150         return err;
3151     }
3152
3153     switch (s->out) {
3154     case EQUIRECTANGULAR:
3155         s->out_transform = equirect_to_xyz;
3156         prepare_out = NULL;
3157         w = lrintf(wf);
3158         h = lrintf(hf);
3159         break;
3160     case CUBEMAP_3_2:
3161         s->out_transform = cube3x2_to_xyz;
3162         prepare_out = prepare_cube_out;
3163         w = lrintf(wf / 4.f * 3.f);
3164         h = lrintf(hf);
3165         break;
3166     case CUBEMAP_1_6:
3167         s->out_transform = cube1x6_to_xyz;
3168         prepare_out = prepare_cube_out;
3169         w = lrintf(wf / 4.f);
3170         h = lrintf(hf * 3.f);
3171         break;
3172     case CUBEMAP_6_1:
3173         s->out_transform = cube6x1_to_xyz;
3174         prepare_out = prepare_cube_out;
3175         w = lrintf(wf / 2.f * 3.f);
3176         h = lrintf(hf / 2.f);
3177         break;
3178     case EQUIANGULAR:
3179         s->out_transform = eac_to_xyz;
3180         prepare_out = prepare_eac_out;
3181         w = lrintf(wf);
3182         h = lrintf(hf / 8.f * 9.f);
3183         break;
3184     case FLAT:
3185         s->out_transform = flat_to_xyz;
3186         prepare_out = prepare_flat_out;
3187         w = lrintf(wf);
3188         h = lrintf(hf);
3189         break;
3190     case DUAL_FISHEYE:
3191         s->out_transform = dfisheye_to_xyz;
3192         prepare_out = NULL;
3193         w = lrintf(wf);
3194         h = lrintf(hf);
3195         break;
3196     case BARREL:
3197         s->out_transform = barrel_to_xyz;
3198         prepare_out = NULL;
3199         w = lrintf(wf / 4.f * 5.f);
3200         h = lrintf(hf);
3201         break;
3202     case STEREOGRAPHIC:
3203         s->out_transform = stereographic_to_xyz;
3204         prepare_out = prepare_stereographic_out;
3205         w = lrintf(wf);
3206         h = lrintf(hf * 2.f);
3207         break;
3208     case MERCATOR:
3209         s->out_transform = mercator_to_xyz;
3210         prepare_out = NULL;
3211         w = lrintf(wf);
3212         h = lrintf(hf * 2.f);
3213         break;
3214     case BALL:
3215         s->out_transform = ball_to_xyz;
3216         prepare_out = NULL;
3217         w = lrintf(wf);
3218         h = lrintf(hf * 2.f);
3219         break;
3220     case HAMMER:
3221         s->out_transform = hammer_to_xyz;
3222         prepare_out = NULL;
3223         w = lrintf(wf);
3224         h = lrintf(hf);
3225         break;
3226     case SINUSOIDAL:
3227         s->out_transform = sinusoidal_to_xyz;
3228         prepare_out = NULL;
3229         w = lrintf(wf);
3230         h = lrintf(hf);
3231         break;
3232     case FISHEYE:
3233         s->out_transform = fisheye_to_xyz;
3234         prepare_out = prepare_fisheye_out;
3235         w = lrintf(wf * 0.5f);
3236         h = lrintf(hf);
3237         break;
3238     case PANNINI:
3239         s->out_transform = pannini_to_xyz;
3240         prepare_out = NULL;
3241         w = lrintf(wf);
3242         h = lrintf(hf);
3243         break;
3244     case CYLINDRICAL:
3245         s->out_transform = cylindrical_to_xyz;
3246         prepare_out = prepare_cylindrical_out;
3247         w = lrintf(wf);
3248         h = lrintf(hf * 0.5f);
3249         break;
3250     case PERSPECTIVE:
3251         s->out_transform = perspective_to_xyz;
3252         prepare_out = NULL;
3253         w = lrintf(wf / 2.f);
3254         h = lrintf(hf);
3255         break;
3256     default:
3257         av_log(ctx, AV_LOG_ERROR, "Specified output format is not handled.\n");
3258         return AVERROR_BUG;
3259     }
3260
3261     // Override resolution with user values if specified
3262     if (s->width > 0 && s->height > 0) {
3263         w = s->width;
3264         h = s->height;
3265     } else if (s->width > 0 || s->height > 0) {
3266         av_log(ctx, AV_LOG_ERROR, "Both width and height values should be specified.\n");
3267         return AVERROR(EINVAL);
3268     } else {
3269         if (s->out_transpose)
3270             FFSWAP(int, w, h);
3271
3272         if (s->in_transpose)
3273             FFSWAP(int, w, h);
3274     }
3275
3276     if (s->d_fov > 0.f)
3277         fov_from_dfov(s->d_fov, w, h, &s->h_fov, &s->v_fov);
3278
3279     if (prepare_out) {
3280         err = prepare_out(ctx);
3281         if (err != 0)
3282             return err;
3283     }
3284
3285     set_dimensions(s->pr_width, s->pr_height, w, h, desc);
3286
3287     s->out_width = s->pr_width[0];
3288     s->out_height = s->pr_height[0];
3289
3290     if (s->out_transpose)
3291         FFSWAP(int, s->out_width, s->out_height);
3292
3293     switch (s->out_stereo) {
3294     case STEREO_2D:
3295         out_offset_w = out_offset_h = 0;
3296         break;
3297     case STEREO_SBS:
3298         out_offset_w = w;
3299         out_offset_h = 0;
3300         w *= 2;
3301         break;
3302     case STEREO_TB:
3303         out_offset_w = 0;
3304         out_offset_h = h;
3305         h *= 2;
3306         break;
3307     default:
3308         av_assert0(0);
3309     }
3310
3311     set_dimensions(s->out_offset_w, s->out_offset_h, out_offset_w, out_offset_h, desc);
3312     set_dimensions(s->planewidth, s->planeheight, w, h, desc);
3313
3314     for (int i = 0; i < 4; i++)
3315         s->uv_linesize[i] = FFALIGN(s->pr_width[i], 8);
3316
3317     outlink->h = h;
3318     outlink->w = w;
3319
3320     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
3321
3322     if (desc->log2_chroma_h == desc->log2_chroma_w && desc->log2_chroma_h == 0) {
3323         s->nb_allocated = 1;
3324         s->map[0] = s->map[1] = s->map[2] = s->map[3] = 0;
3325     } else {
3326         s->nb_allocated = 2;
3327         s->map[0] = s->map[3] = 0;
3328         s->map[1] = s->map[2] = 1;
3329     }
3330
3331     for (int i = 0; i < s->nb_allocated; i++)
3332         allocate_plane(s, sizeof_uv, sizeof_ker, i);
3333
3334     calculate_rotation_matrix(s->yaw, s->pitch, s->roll, s->rot_mat, s->rotation_order);
3335     set_mirror_modifier(s->h_flip, s->v_flip, s->d_flip, s->output_mirror_modifier);
3336
3337     ctx->internal->execute(ctx, v360_slice, NULL, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
3338
3339     return 0;
3340 }
3341
3342 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
3343 {
3344     AVFilterContext *ctx = inlink->dst;
3345     AVFilterLink *outlink = ctx->outputs[0];
3346     V360Context *s = ctx->priv;
3347     AVFrame *out;
3348     ThreadData td;
3349
3350     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
3351     if (!out) {
3352         av_frame_free(&in);
3353         return AVERROR(ENOMEM);
3354     }
3355     av_frame_copy_props(out, in);
3356
3357     td.in = in;
3358     td.out = out;
3359
3360     ctx->internal->execute(ctx, s->remap_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
3361
3362     av_frame_free(&in);
3363     return ff_filter_frame(outlink, out);
3364 }
3365
3366 static av_cold void uninit(AVFilterContext *ctx)
3367 {
3368     V360Context *s = ctx->priv;
3369
3370     for (int p = 0; p < s->nb_allocated; p++) {
3371         av_freep(&s->u[p]);
3372         av_freep(&s->v[p]);
3373         av_freep(&s->ker[p]);
3374     }
3375 }
3376
3377 static const AVFilterPad inputs[] = {
3378     {
3379         .name         = "default",
3380         .type         = AVMEDIA_TYPE_VIDEO,
3381         .filter_frame = filter_frame,
3382     },
3383     { NULL }
3384 };
3385
3386 static const AVFilterPad outputs[] = {
3387     {
3388         .name         = "default",
3389         .type         = AVMEDIA_TYPE_VIDEO,
3390         .config_props = config_output,
3391     },
3392     { NULL }
3393 };
3394
3395 AVFilter ff_vf_v360 = {
3396     .name          = "v360",
3397     .description   = NULL_IF_CONFIG_SMALL("Convert 360 projection of video."),
3398     .priv_size     = sizeof(V360Context),
3399     .uninit        = uninit,
3400     .query_formats = query_formats,
3401     .inputs        = inputs,
3402     .outputs       = outputs,
3403     .priv_class    = &v360_class,
3404     .flags         = AVFILTER_FLAG_SLICE_THREADS,
3405 };