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