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