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