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