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