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