]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_v360.c
avfilter/vf_v360: add fixed pixel padding options
[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 = 0.5f * asinhf(vec[1] / sqrtf(1.f - vec[1] * 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 = (theta / M_PI + 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] = mod(ui + j, width);
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;
1593     const float theta = atanf(sinhf(((2.f * j) / height - 1.f) * 2.f * M_PI));
1594
1595     const float sin_phi   = sinf(phi);
1596     const float cos_phi   = cosf(phi);
1597     const float sin_theta = sinf(theta);
1598     const float cos_theta = cosf(theta);
1599
1600     vec[0] =  cos_theta * sin_phi;
1601     vec[1] = -sin_theta;
1602     vec[2] = -cos_theta * cos_phi;
1603 }
1604
1605 /**
1606  * Calculate frame position in ball format for corresponding 3D coordinates on sphere.
1607  *
1608  * @param s filter private context
1609  * @param vec coordinates on sphere
1610  * @param width frame width
1611  * @param height frame height
1612  * @param us horizontal coordinates for interpolation window
1613  * @param vs vertical coordinates for interpolation window
1614  * @param du horizontal relative coordinate
1615  * @param dv vertical relative coordinate
1616  */
1617 static void xyz_to_ball(const V360Context *s,
1618                         const float *vec, int width, int height,
1619                         uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1620 {
1621     const float l = hypotf(vec[0], vec[1]);
1622     const float r = sqrtf(1.f + vec[2]) / M_SQRT2;
1623     float uf, vf;
1624     int ui, vi;
1625
1626     uf = (1.f + r * vec[0] * s->input_mirror_modifier[0] / (l > 0.f ? l : 1.f)) * width  * 0.5f;
1627     vf = (1.f - r * vec[1] * s->input_mirror_modifier[1] / (l > 0.f ? l : 1.f)) * height * 0.5f;
1628
1629     ui = floorf(uf);
1630     vi = floorf(vf);
1631
1632     *du = uf - ui;
1633     *dv = vf - vi;
1634
1635     for (int i = -1; i < 3; i++) {
1636         for (int j = -1; j < 3; j++) {
1637             us[i + 1][j + 1] = mod(ui + j, width);
1638             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1639         }
1640     }
1641 }
1642
1643 /**
1644  * Calculate 3D coordinates on sphere for corresponding frame position in ball format.
1645  *
1646  * @param s filter private context
1647  * @param i horizontal position on frame [0, width)
1648  * @param j vertical position on frame [0, height)
1649  * @param width frame width
1650  * @param height frame height
1651  * @param vec coordinates on sphere
1652  */
1653 static void ball_to_xyz(const V360Context *s,
1654                         int i, int j, int width, int height,
1655                         float *vec)
1656 {
1657     const float x = (2.f * i) / width  - 1.f;
1658     const float y = (2.f * j) / height - 1.f;
1659     const float l = hypotf(x, y);
1660
1661     if (l <= 1.f) {
1662         const float z = 2.f * l * sqrtf(1.f - l * l);
1663
1664         vec[0] =  z * x / (l > 0.f ? l : 1.f);
1665         vec[1] = -z * y / (l > 0.f ? l : 1.f);
1666         vec[2] = -1.f + 2.f * l * l;
1667     } else {
1668         vec[0] =  0.f;
1669         vec[1] = -1.f;
1670         vec[2] =  0.f;
1671     }
1672 }
1673
1674 /**
1675  * Calculate 3D coordinates on sphere for corresponding frame position in hammer format.
1676  *
1677  * @param s filter private context
1678  * @param i horizontal position on frame [0, width)
1679  * @param j vertical position on frame [0, height)
1680  * @param width frame width
1681  * @param height frame height
1682  * @param vec coordinates on sphere
1683  */
1684 static void hammer_to_xyz(const V360Context *s,
1685                           int i, int j, int width, int height,
1686                           float *vec)
1687 {
1688     const float x = ((2.f * i) / width  - 1.f);
1689     const float y = ((2.f * j) / height - 1.f);
1690
1691     const float xx = x * x;
1692     const float yy = y * y;
1693
1694     const float z = sqrtf(1.f - xx * 0.5f - yy * 0.5f);
1695
1696     const float a = M_SQRT2 * x * z;
1697     const float b = 2.f * z * z - 1.f;
1698
1699     const float aa = a * a;
1700     const float bb = b * b;
1701
1702     const float w = sqrtf(1.f - 2.f * yy * z * z);
1703
1704     vec[0] =  w * 2.f * a * b / (aa + bb);
1705     vec[1] = -M_SQRT2 * y * z;
1706     vec[2] = -w * (bb  - aa) / (aa + bb);
1707
1708     normalize_vector(vec);
1709 }
1710
1711 /**
1712  * Calculate frame position in hammer format for corresponding 3D coordinates on sphere.
1713  *
1714  * @param s filter private context
1715  * @param vec coordinates on sphere
1716  * @param width frame width
1717  * @param height frame height
1718  * @param us horizontal coordinates for interpolation window
1719  * @param vs vertical coordinates for interpolation window
1720  * @param du horizontal relative coordinate
1721  * @param dv vertical relative coordinate
1722  */
1723 static void xyz_to_hammer(const V360Context *s,
1724                           const float *vec, int width, int height,
1725                           uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1726 {
1727     const float theta = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
1728
1729     const float z = sqrtf(1.f + sqrtf(1.f - vec[1] * vec[1]) * cosf(theta * 0.5f));
1730     const float x = sqrtf(1.f - vec[1] * vec[1]) * sinf(theta * 0.5f) / z;
1731     const float y = -vec[1] / z * s->input_mirror_modifier[1];
1732     float uf, vf;
1733     int ui, vi;
1734
1735     uf = (x + 1.f) * width  / 2.f;
1736     vf = (y + 1.f) * height / 2.f;
1737     ui = floorf(uf);
1738     vi = floorf(vf);
1739
1740     *du = uf - ui;
1741     *dv = vf - vi;
1742
1743     for (int i = -1; i < 3; i++) {
1744         for (int j = -1; j < 3; j++) {
1745             us[i + 1][j + 1] = mod(ui + j, width);
1746             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1747         }
1748     }
1749 }
1750
1751 /**
1752  * Prepare data for processing equi-angular cubemap input format.
1753  *
1754  * @param ctx filter context
1755  *
1756  * @return error code
1757  */
1758 static int prepare_eac_in(AVFilterContext *ctx)
1759 {
1760     V360Context *s = ctx->priv;
1761
1762     if (s->ih_flip && s->iv_flip) {
1763         s->in_cubemap_face_order[RIGHT] = BOTTOM_LEFT;
1764         s->in_cubemap_face_order[LEFT]  = BOTTOM_RIGHT;
1765         s->in_cubemap_face_order[UP]    = TOP_LEFT;
1766         s->in_cubemap_face_order[DOWN]  = TOP_RIGHT;
1767         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
1768         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
1769     } else if (s->ih_flip) {
1770         s->in_cubemap_face_order[RIGHT] = TOP_LEFT;
1771         s->in_cubemap_face_order[LEFT]  = TOP_RIGHT;
1772         s->in_cubemap_face_order[UP]    = BOTTOM_LEFT;
1773         s->in_cubemap_face_order[DOWN]  = BOTTOM_RIGHT;
1774         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
1775         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
1776     } else if (s->iv_flip) {
1777         s->in_cubemap_face_order[RIGHT] = BOTTOM_RIGHT;
1778         s->in_cubemap_face_order[LEFT]  = BOTTOM_LEFT;
1779         s->in_cubemap_face_order[UP]    = TOP_RIGHT;
1780         s->in_cubemap_face_order[DOWN]  = TOP_LEFT;
1781         s->in_cubemap_face_order[FRONT] = BOTTOM_MIDDLE;
1782         s->in_cubemap_face_order[BACK]  = TOP_MIDDLE;
1783     } else {
1784         s->in_cubemap_face_order[RIGHT] = TOP_RIGHT;
1785         s->in_cubemap_face_order[LEFT]  = TOP_LEFT;
1786         s->in_cubemap_face_order[UP]    = BOTTOM_RIGHT;
1787         s->in_cubemap_face_order[DOWN]  = BOTTOM_LEFT;
1788         s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
1789         s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
1790     }
1791
1792     if (s->iv_flip) {
1793         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_270;
1794         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_90;
1795         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_270;
1796         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_0;
1797         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_0;
1798         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_0;
1799     } else {
1800         s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1801         s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1802         s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1803         s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1804         s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1805         s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1806     }
1807
1808     return 0;
1809 }
1810
1811 /**
1812  * Prepare data for processing equi-angular cubemap output format.
1813  *
1814  * @param ctx filter context
1815  *
1816  * @return error code
1817  */
1818 static int prepare_eac_out(AVFilterContext *ctx)
1819 {
1820     V360Context *s = ctx->priv;
1821
1822     s->out_cubemap_direction_order[TOP_LEFT]      = LEFT;
1823     s->out_cubemap_direction_order[TOP_MIDDLE]    = FRONT;
1824     s->out_cubemap_direction_order[TOP_RIGHT]     = RIGHT;
1825     s->out_cubemap_direction_order[BOTTOM_LEFT]   = DOWN;
1826     s->out_cubemap_direction_order[BOTTOM_MIDDLE] = BACK;
1827     s->out_cubemap_direction_order[BOTTOM_RIGHT]  = UP;
1828
1829     s->out_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1830     s->out_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1831     s->out_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1832     s->out_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1833     s->out_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1834     s->out_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1835
1836     return 0;
1837 }
1838
1839 /**
1840  * Calculate 3D coordinates on sphere for corresponding frame position in equi-angular cubemap format.
1841  *
1842  * @param s filter private context
1843  * @param i horizontal position on frame [0, width)
1844  * @param j vertical position on frame [0, height)
1845  * @param width frame width
1846  * @param height frame height
1847  * @param vec coordinates on sphere
1848  */
1849 static void eac_to_xyz(const V360Context *s,
1850                        int i, int j, int width, int height,
1851                        float *vec)
1852 {
1853     const float pixel_pad = 2;
1854     const float u_pad = pixel_pad / width;
1855     const float v_pad = pixel_pad / height;
1856
1857     int u_face, v_face, face;
1858
1859     float l_x, l_y, l_z;
1860
1861     float uf = (i + 0.5f) / width;
1862     float vf = (j + 0.5f) / height;
1863
1864     // EAC has 2-pixel padding on faces except between faces on the same row
1865     // Padding pixels seems not to be stretched with tangent as regular pixels
1866     // Formulas below approximate original padding as close as I could get experimentally
1867
1868     // Horizontal padding
1869     uf = 3.f * (uf - u_pad) / (1.f - 2.f * u_pad);
1870     if (uf < 0.f) {
1871         u_face = 0;
1872         uf -= 0.5f;
1873     } else if (uf >= 3.f) {
1874         u_face = 2;
1875         uf -= 2.5f;
1876     } else {
1877         u_face = floorf(uf);
1878         uf = fmodf(uf, 1.f) - 0.5f;
1879     }
1880
1881     // Vertical padding
1882     v_face = floorf(vf * 2.f);
1883     vf = (vf - v_pad - 0.5f * v_face) / (0.5f - 2.f * v_pad) - 0.5f;
1884
1885     if (uf >= -0.5f && uf < 0.5f) {
1886         uf = tanf(M_PI_2 * uf);
1887     } else {
1888         uf = 2.f * uf;
1889     }
1890     if (vf >= -0.5f && vf < 0.5f) {
1891         vf = tanf(M_PI_2 * vf);
1892     } else {
1893         vf = 2.f * vf;
1894     }
1895
1896     face = u_face + 3 * v_face;
1897
1898     switch (face) {
1899     case TOP_LEFT:
1900         l_x = -1.f;
1901         l_y = -vf;
1902         l_z = -uf;
1903         break;
1904     case TOP_MIDDLE:
1905         l_x =  uf;
1906         l_y = -vf;
1907         l_z = -1.f;
1908         break;
1909     case TOP_RIGHT:
1910         l_x =  1.f;
1911         l_y = -vf;
1912         l_z =  uf;
1913         break;
1914     case BOTTOM_LEFT:
1915         l_x = -vf;
1916         l_y = -1.f;
1917         l_z =  uf;
1918         break;
1919     case BOTTOM_MIDDLE:
1920         l_x = -vf;
1921         l_y =  uf;
1922         l_z =  1.f;
1923         break;
1924     case BOTTOM_RIGHT:
1925         l_x = -vf;
1926         l_y =  1.f;
1927         l_z = -uf;
1928         break;
1929     default:
1930         av_assert0(0);
1931     }
1932
1933     vec[0] = l_x;
1934     vec[1] = l_y;
1935     vec[2] = l_z;
1936
1937     normalize_vector(vec);
1938 }
1939
1940 /**
1941  * Calculate frame position in equi-angular cubemap format for corresponding 3D coordinates on sphere.
1942  *
1943  * @param s filter private context
1944  * @param vec coordinates on sphere
1945  * @param width frame width
1946  * @param height frame height
1947  * @param us horizontal coordinates for interpolation window
1948  * @param vs vertical coordinates for interpolation window
1949  * @param du horizontal relative coordinate
1950  * @param dv vertical relative coordinate
1951  */
1952 static void xyz_to_eac(const V360Context *s,
1953                        const float *vec, int width, int height,
1954                        uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1955 {
1956     const float pixel_pad = 2;
1957     const float u_pad = pixel_pad / width;
1958     const float v_pad = pixel_pad / height;
1959
1960     float uf, vf;
1961     int ui, vi;
1962     int direction, face;
1963     int u_face, v_face;
1964
1965     xyz_to_cube(s, vec, &uf, &vf, &direction);
1966
1967     face = s->in_cubemap_face_order[direction];
1968     u_face = face % 3;
1969     v_face = face / 3;
1970
1971     uf = M_2_PI * atanf(uf) + 0.5f;
1972     vf = M_2_PI * atanf(vf) + 0.5f;
1973
1974     // These formulas are inversed from eac_to_xyz ones
1975     uf = (uf + u_face) * (1.f - 2.f * u_pad) / 3.f + u_pad;
1976     vf = vf * (0.5f - 2.f * v_pad) + v_pad + 0.5f * v_face;
1977
1978     uf *= width;
1979     vf *= height;
1980
1981     uf -= 0.5f;
1982     vf -= 0.5f;
1983
1984     ui = floorf(uf);
1985     vi = floorf(vf);
1986
1987     *du = uf - ui;
1988     *dv = vf - vi;
1989
1990     for (int i = -1; i < 3; i++) {
1991         for (int j = -1; j < 3; j++) {
1992             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1993             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1994         }
1995     }
1996 }
1997
1998 /**
1999  * Prepare data for processing flat output format.
2000  *
2001  * @param ctx filter context
2002  *
2003  * @return error code
2004  */
2005 static int prepare_flat_out(AVFilterContext *ctx)
2006 {
2007     V360Context *s = ctx->priv;
2008
2009     s->flat_range[0] = tanf(0.5f * s->h_fov * M_PI / 180.f);
2010     s->flat_range[1] = tanf(0.5f * s->v_fov * M_PI / 180.f);
2011
2012     return 0;
2013 }
2014
2015 /**
2016  * Calculate 3D coordinates on sphere for corresponding frame position in flat format.
2017  *
2018  * @param s filter private context
2019  * @param i horizontal position on frame [0, width)
2020  * @param j vertical position on frame [0, height)
2021  * @param width frame width
2022  * @param height frame height
2023  * @param vec coordinates on sphere
2024  */
2025 static void flat_to_xyz(const V360Context *s,
2026                         int i, int j, int width, int height,
2027                         float *vec)
2028 {
2029     const float l_x =  s->flat_range[0] * (2.f * i / width  - 1.f);
2030     const float l_y = -s->flat_range[1] * (2.f * j / height - 1.f);
2031
2032     vec[0] =  l_x;
2033     vec[1] =  l_y;
2034     vec[2] = -1.f;
2035
2036     normalize_vector(vec);
2037 }
2038
2039 /**
2040  * Calculate 3D coordinates on sphere for corresponding frame position in dual fisheye format.
2041  *
2042  * @param s filter private context
2043  * @param i horizontal position on frame [0, width)
2044  * @param j vertical position on frame [0, height)
2045  * @param width frame width
2046  * @param height frame height
2047  * @param vec coordinates on sphere
2048  */
2049 static void dfisheye_to_xyz(const V360Context *s,
2050                             int i, int j, int width, int height,
2051                             float *vec)
2052 {
2053     const float scale = 1.f + s->out_pad;
2054
2055     const float ew = width / 2.f;
2056     const float eh = height;
2057
2058     const int ei = i >= ew ? i - ew : i;
2059     const float m = i >= ew ? -1.f : 1.f;
2060
2061     const float uf = ((2.f * ei) / ew - 1.f) * scale;
2062     const float vf = ((2.f *  j) / eh - 1.f) * scale;
2063
2064     const float h     = hypotf(uf, vf);
2065     const float lh    = h > 0.f ? h : 1.f;
2066     const float theta = m * M_PI_2 * (1.f - h);
2067
2068     const float sin_theta = sinf(theta);
2069     const float cos_theta = cosf(theta);
2070
2071     vec[0] = cos_theta *  uf / lh;
2072     vec[1] = cos_theta * -vf / lh;
2073     vec[2] = sin_theta;
2074
2075     normalize_vector(vec);
2076 }
2077
2078 /**
2079  * Calculate frame position in dual fisheye format for corresponding 3D coordinates on sphere.
2080  *
2081  * @param s filter private context
2082  * @param vec coordinates on sphere
2083  * @param width frame width
2084  * @param height frame height
2085  * @param us horizontal coordinates for interpolation window
2086  * @param vs vertical coordinates for interpolation window
2087  * @param du horizontal relative coordinate
2088  * @param dv vertical relative coordinate
2089  */
2090 static void xyz_to_dfisheye(const V360Context *s,
2091                             const float *vec, int width, int height,
2092                             uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
2093 {
2094     const float scale = 1.f - s->in_pad;
2095
2096     const float ew = width / 2.f;
2097     const float eh = height;
2098
2099     const float h     = hypotf(vec[0], vec[1]);
2100     const float lh    = h > 0.f ? h : 1.f;
2101     const float theta = acosf(fabsf(vec[2])) / M_PI;
2102
2103     float uf = (theta * (-vec[0] / lh) * s->input_mirror_modifier[0] * scale + 0.5f) * ew;
2104     float vf = (theta * (-vec[1] / lh) * s->input_mirror_modifier[1] * scale + 0.5f) * eh;
2105
2106     int ui, vi;
2107     int u_shift;
2108
2109     if (vec[2] >= 0.f) {
2110         u_shift = 0;
2111     } else {
2112         u_shift = ceilf(ew);
2113         uf = ew - uf;
2114     }
2115
2116     ui = floorf(uf);
2117     vi = floorf(vf);
2118
2119     *du = uf - ui;
2120     *dv = vf - vi;
2121
2122     for (int i = -1; i < 3; i++) {
2123         for (int j = -1; j < 3; j++) {
2124             us[i + 1][j + 1] = av_clip(u_shift + ui + j, 0, width  - 1);
2125             vs[i + 1][j + 1] = av_clip(          vi + i, 0, height - 1);
2126         }
2127     }
2128 }
2129
2130 /**
2131  * Calculate 3D coordinates on sphere for corresponding frame position in barrel facebook's format.
2132  *
2133  * @param s filter private context
2134  * @param i horizontal position on frame [0, width)
2135  * @param j vertical position on frame [0, height)
2136  * @param width frame width
2137  * @param height frame height
2138  * @param vec coordinates on sphere
2139  */
2140 static void barrel_to_xyz(const V360Context *s,
2141                           int i, int j, int width, int height,
2142                           float *vec)
2143 {
2144     const float scale = 0.99f;
2145     float l_x, l_y, l_z;
2146
2147     if (i < 4 * width / 5) {
2148         const float theta_range = M_PI_4;
2149
2150         const int ew = 4 * width / 5;
2151         const int eh = height;
2152
2153         const float phi   = ((2.f * i) / ew - 1.f) * M_PI        / scale;
2154         const float theta = ((2.f * j) / eh - 1.f) * theta_range / scale;
2155
2156         const float sin_phi   = sinf(phi);
2157         const float cos_phi   = cosf(phi);
2158         const float sin_theta = sinf(theta);
2159         const float cos_theta = cosf(theta);
2160
2161         l_x =  cos_theta * sin_phi;
2162         l_y = -sin_theta;
2163         l_z = -cos_theta * cos_phi;
2164     } else {
2165         const int ew = width  / 5;
2166         const int eh = height / 2;
2167
2168         float uf, vf;
2169
2170         if (j < eh) {   // UP
2171             uf = 2.f * (i - 4 * ew) / ew  - 1.f;
2172             vf = 2.f * (j         ) / eh - 1.f;
2173
2174             uf /= scale;
2175             vf /= scale;
2176
2177             l_x =  uf;
2178             l_y =  1.f;
2179             l_z = -vf;
2180         } else {            // DOWN
2181             uf = 2.f * (i - 4 * ew) / ew - 1.f;
2182             vf = 2.f * (j -     eh) / eh - 1.f;
2183
2184             uf /= scale;
2185             vf /= scale;
2186
2187             l_x =  uf;
2188             l_y = -1.f;
2189             l_z =  vf;
2190         }
2191     }
2192
2193     vec[0] = l_x;
2194     vec[1] = l_y;
2195     vec[2] = l_z;
2196
2197     normalize_vector(vec);
2198 }
2199
2200 /**
2201  * Calculate frame position in barrel facebook's format for corresponding 3D coordinates on sphere.
2202  *
2203  * @param s filter private context
2204  * @param vec coordinates on sphere
2205  * @param width frame width
2206  * @param height frame height
2207  * @param us horizontal coordinates for interpolation window
2208  * @param vs vertical coordinates for interpolation window
2209  * @param du horizontal relative coordinate
2210  * @param dv vertical relative coordinate
2211  */
2212 static void xyz_to_barrel(const V360Context *s,
2213                           const float *vec, int width, int height,
2214                           uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
2215 {
2216     const float scale = 0.99f;
2217
2218     const float phi   = atan2f(vec[0], -vec[2]) * s->input_mirror_modifier[0];
2219     const float theta = asinf(-vec[1]) * s->input_mirror_modifier[1];
2220     const float theta_range = M_PI_4;
2221
2222     int ew, eh;
2223     int u_shift, v_shift;
2224     float uf, vf;
2225     int ui, vi;
2226
2227     if (theta > -theta_range && theta < theta_range) {
2228         ew = 4 * width / 5;
2229         eh = height;
2230
2231         u_shift = s->ih_flip ? width / 5 : 0;
2232         v_shift = 0;
2233
2234         uf = (phi   / M_PI        * scale + 1.f) * ew / 2.f;
2235         vf = (theta / theta_range * scale + 1.f) * eh / 2.f;
2236     } else {
2237         ew = width  / 5;
2238         eh = height / 2;
2239
2240         u_shift = s->ih_flip ? 0 : 4 * ew;
2241
2242         if (theta < 0.f) {  // UP
2243             uf =  vec[0] / vec[1];
2244             vf = -vec[2] / vec[1];
2245             v_shift = 0;
2246         } else {            // DOWN
2247             uf = -vec[0] / vec[1];
2248             vf = -vec[2] / vec[1];
2249             v_shift = eh;
2250         }
2251
2252         uf *= s->input_mirror_modifier[0] * s->input_mirror_modifier[1];
2253         vf *= s->input_mirror_modifier[1];
2254
2255         uf = 0.5f * ew * (uf * scale + 1.f);
2256         vf = 0.5f * eh * (vf * scale + 1.f);
2257     }
2258
2259     ui = floorf(uf);
2260     vi = floorf(vf);
2261
2262     *du = uf - ui;
2263     *dv = vf - vi;
2264
2265     for (int i = -1; i < 3; i++) {
2266         for (int j = -1; j < 3; j++) {
2267             us[i + 1][j + 1] = u_shift + av_clip(ui + j, 0, ew - 1);
2268             vs[i + 1][j + 1] = v_shift + av_clip(vi + i, 0, eh - 1);
2269         }
2270     }
2271 }
2272
2273 static void multiply_matrix(float c[3][3], const float a[3][3], const float b[3][3])
2274 {
2275     for (int i = 0; i < 3; i++) {
2276         for (int j = 0; j < 3; j++) {
2277             float sum = 0;
2278
2279             for (int k = 0; k < 3; k++)
2280                 sum += a[i][k] * b[k][j];
2281
2282             c[i][j] = sum;
2283         }
2284     }
2285 }
2286
2287 /**
2288  * Calculate rotation matrix for yaw/pitch/roll angles.
2289  */
2290 static inline void calculate_rotation_matrix(float yaw, float pitch, float roll,
2291                                              float rot_mat[3][3],
2292                                              const int rotation_order[3])
2293 {
2294     const float yaw_rad   = yaw   * M_PI / 180.f;
2295     const float pitch_rad = pitch * M_PI / 180.f;
2296     const float roll_rad  = roll  * M_PI / 180.f;
2297
2298     const float sin_yaw   = sinf(-yaw_rad);
2299     const float cos_yaw   = cosf(-yaw_rad);
2300     const float sin_pitch = sinf(pitch_rad);
2301     const float cos_pitch = cosf(pitch_rad);
2302     const float sin_roll  = sinf(roll_rad);
2303     const float cos_roll  = cosf(roll_rad);
2304
2305     float m[3][3][3];
2306     float temp[3][3];
2307
2308     m[0][0][0] =  cos_yaw;  m[0][0][1] = 0;          m[0][0][2] =  sin_yaw;
2309     m[0][1][0] =  0;        m[0][1][1] = 1;          m[0][1][2] =  0;
2310     m[0][2][0] = -sin_yaw;  m[0][2][1] = 0;          m[0][2][2] =  cos_yaw;
2311
2312     m[1][0][0] = 1;         m[1][0][1] = 0;          m[1][0][2] =  0;
2313     m[1][1][0] = 0;         m[1][1][1] = cos_pitch;  m[1][1][2] = -sin_pitch;
2314     m[1][2][0] = 0;         m[1][2][1] = sin_pitch;  m[1][2][2] =  cos_pitch;
2315
2316     m[2][0][0] = cos_roll;  m[2][0][1] = -sin_roll;  m[2][0][2] =  0;
2317     m[2][1][0] = sin_roll;  m[2][1][1] =  cos_roll;  m[2][1][2] =  0;
2318     m[2][2][0] = 0;         m[2][2][1] =  0;         m[2][2][2] =  1;
2319
2320     multiply_matrix(temp, m[rotation_order[0]], m[rotation_order[1]]);
2321     multiply_matrix(rot_mat, temp, m[rotation_order[2]]);
2322 }
2323
2324 /**
2325  * Rotate vector with given rotation matrix.
2326  *
2327  * @param rot_mat rotation matrix
2328  * @param vec vector
2329  */
2330 static inline void rotate(const float rot_mat[3][3],
2331                           float *vec)
2332 {
2333     const float x_tmp = vec[0] * rot_mat[0][0] + vec[1] * rot_mat[0][1] + vec[2] * rot_mat[0][2];
2334     const float y_tmp = vec[0] * rot_mat[1][0] + vec[1] * rot_mat[1][1] + vec[2] * rot_mat[1][2];
2335     const float z_tmp = vec[0] * rot_mat[2][0] + vec[1] * rot_mat[2][1] + vec[2] * rot_mat[2][2];
2336
2337     vec[0] = x_tmp;
2338     vec[1] = y_tmp;
2339     vec[2] = z_tmp;
2340 }
2341
2342 static inline void set_mirror_modifier(int h_flip, int v_flip, int d_flip,
2343                                        float *modifier)
2344 {
2345     modifier[0] = h_flip ? -1.f : 1.f;
2346     modifier[1] = v_flip ? -1.f : 1.f;
2347     modifier[2] = d_flip ? -1.f : 1.f;
2348 }
2349
2350 static inline void mirror(const float *modifier, float *vec)
2351 {
2352     vec[0] *= modifier[0];
2353     vec[1] *= modifier[1];
2354     vec[2] *= modifier[2];
2355 }
2356
2357 static int allocate_plane(V360Context *s, int sizeof_uv, int sizeof_ker, int p)
2358 {
2359     s->u[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_uv);
2360     s->v[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_uv);
2361     if (!s->u[p] || !s->v[p])
2362         return AVERROR(ENOMEM);
2363     if (sizeof_ker) {
2364         s->ker[p] = av_calloc(s->uv_linesize[p] * s->pr_height[p], sizeof_ker);
2365         if (!s->ker[p])
2366             return AVERROR(ENOMEM);
2367     }
2368
2369     return 0;
2370 }
2371
2372 static void fov_from_dfov(V360Context *s, float w, float h)
2373 {
2374     const float da = tanf(0.5 * FFMIN(s->d_fov, 359.f) * M_PI / 180.f);
2375     const float d = hypotf(w, h);
2376
2377     s->h_fov = atan2f(da * w, d) * 360.f / M_PI;
2378     s->v_fov = atan2f(da * h, d) * 360.f / M_PI;
2379
2380     if (s->h_fov < 0.f)
2381         s->h_fov += 360.f;
2382     if (s->v_fov < 0.f)
2383         s->v_fov += 360.f;
2384 }
2385
2386 static void set_dimensions(int *outw, int *outh, int w, int h, const AVPixFmtDescriptor *desc)
2387 {
2388     outw[1] = outw[2] = FF_CEIL_RSHIFT(w, desc->log2_chroma_w);
2389     outw[0] = outw[3] = w;
2390     outh[1] = outh[2] = FF_CEIL_RSHIFT(h, desc->log2_chroma_h);
2391     outh[0] = outh[3] = h;
2392 }
2393
2394 // Calculate remap data
2395 static av_always_inline int v360_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
2396 {
2397     V360Context *s = ctx->priv;
2398
2399     for (int p = 0; p < s->nb_allocated; p++) {
2400         const int width = s->pr_width[p];
2401         const int uv_linesize = s->uv_linesize[p];
2402         const int height = s->pr_height[p];
2403         const int in_width = s->inplanewidth[p];
2404         const int in_height = s->inplaneheight[p];
2405         const int slice_start = (height *  jobnr     ) / nb_jobs;
2406         const int slice_end   = (height * (jobnr + 1)) / nb_jobs;
2407         float du, dv;
2408         float vec[3];
2409         XYRemap rmap;
2410
2411         for (int j = slice_start; j < slice_end; j++) {
2412             for (int i = 0; i < width; i++) {
2413                 uint16_t *u = s->u[p] + (j * uv_linesize + i) * s->elements;
2414                 uint16_t *v = s->v[p] + (j * uv_linesize + i) * s->elements;
2415                 int16_t *ker = s->ker[p] + (j * uv_linesize + i) * s->elements;
2416
2417                 if (s->out_transpose)
2418                     s->out_transform(s, j, i, height, width, vec);
2419                 else
2420                     s->out_transform(s, i, j, width, height, vec);
2421                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2422                 rotate(s->rot_mat, vec);
2423                 av_assert1(!isnan(vec[0]) && !isnan(vec[1]) && !isnan(vec[2]));
2424                 normalize_vector(vec);
2425                 mirror(s->output_mirror_modifier, vec);
2426                 if (s->in_transpose)
2427                     s->in_transform(s, vec, in_height, in_width, rmap.v, rmap.u, &du, &dv);
2428                 else
2429                     s->in_transform(s, vec, in_width, in_height, rmap.u, rmap.v, &du, &dv);
2430                 av_assert1(!isnan(du) && !isnan(dv));
2431                 s->calculate_kernel(du, dv, &rmap, u, v, ker);
2432             }
2433         }
2434     }
2435
2436     return 0;
2437 }
2438
2439 static int config_output(AVFilterLink *outlink)
2440 {
2441     AVFilterContext *ctx = outlink->src;
2442     AVFilterLink *inlink = ctx->inputs[0];
2443     V360Context *s = ctx->priv;
2444     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
2445     const int depth = desc->comp[0].depth;
2446     int sizeof_uv;
2447     int sizeof_ker;
2448     int err;
2449     int h, w;
2450     int in_offset_h, in_offset_w;
2451     int out_offset_h, out_offset_w;
2452     float hf, wf;
2453     int (*prepare_out)(AVFilterContext *ctx);
2454
2455     s->input_mirror_modifier[0] = s->ih_flip ? -1.f : 1.f;
2456     s->input_mirror_modifier[1] = s->iv_flip ? -1.f : 1.f;
2457
2458     switch (s->interp) {
2459     case NEAREST:
2460         s->calculate_kernel = nearest_kernel;
2461         s->remap_slice = depth <= 8 ? remap1_8bit_slice : remap1_16bit_slice;
2462         s->elements = 1;
2463         sizeof_uv = sizeof(uint16_t) * s->elements;
2464         sizeof_ker = 0;
2465         break;
2466     case BILINEAR:
2467         s->calculate_kernel = bilinear_kernel;
2468         s->remap_slice = depth <= 8 ? remap2_8bit_slice : remap2_16bit_slice;
2469         s->elements = 2 * 2;
2470         sizeof_uv = sizeof(uint16_t) * s->elements;
2471         sizeof_ker = sizeof(uint16_t) * s->elements;
2472         break;
2473     case BICUBIC:
2474         s->calculate_kernel = bicubic_kernel;
2475         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2476         s->elements = 4 * 4;
2477         sizeof_uv = sizeof(uint16_t) * s->elements;
2478         sizeof_ker = sizeof(uint16_t) * s->elements;
2479         break;
2480     case LANCZOS:
2481         s->calculate_kernel = lanczos_kernel;
2482         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
2483         s->elements = 4 * 4;
2484         sizeof_uv = sizeof(uint16_t) * s->elements;
2485         sizeof_ker = sizeof(uint16_t) * s->elements;
2486         break;
2487     default:
2488         av_assert0(0);
2489     }
2490
2491     ff_v360_init(s, depth);
2492
2493     for (int order = 0; order < NB_RORDERS; order++) {
2494         const char c = s->rorder[order];
2495         int rorder;
2496
2497         if (c == '\0') {
2498             av_log(ctx, AV_LOG_ERROR,
2499                    "Incomplete rorder option. Direction for all 3 rotation orders should be specified.\n");
2500             return AVERROR(EINVAL);
2501         }
2502
2503         rorder = get_rorder(c);
2504         if (rorder == -1) {
2505             av_log(ctx, AV_LOG_ERROR,
2506                    "Incorrect rotation order symbol '%c' in rorder option.\n", c);
2507             return AVERROR(EINVAL);
2508         }
2509
2510         s->rotation_order[order] = rorder;
2511     }
2512
2513     switch (s->in_stereo) {
2514     case STEREO_2D:
2515         w = inlink->w;
2516         h = inlink->h;
2517         in_offset_w = in_offset_h = 0;
2518         break;
2519     case STEREO_SBS:
2520         w = inlink->w / 2;
2521         h = inlink->h;
2522         in_offset_w = w;
2523         in_offset_h = 0;
2524         break;
2525     case STEREO_TB:
2526         w = inlink->w;
2527         h = inlink->h / 2;
2528         in_offset_w = 0;
2529         in_offset_h = h;
2530         break;
2531     default:
2532         av_assert0(0);
2533     }
2534
2535     set_dimensions(s->inplanewidth, s->inplaneheight, w, h, desc);
2536     set_dimensions(s->in_offset_w, s->in_offset_h, in_offset_w, in_offset_h, desc);
2537
2538     s->in_width = s->inplanewidth[0];
2539     s->in_height = s->inplaneheight[0];
2540
2541     if (s->in_transpose)
2542         FFSWAP(int, s->in_width, s->in_height);
2543
2544     switch (s->in) {
2545     case EQUIRECTANGULAR:
2546         s->in_transform = xyz_to_equirect;
2547         err = 0;
2548         wf = w;
2549         hf = h;
2550         break;
2551     case CUBEMAP_3_2:
2552         s->in_transform = xyz_to_cube3x2;
2553         err = prepare_cube_in(ctx);
2554         wf = w / 3.f * 4.f;
2555         hf = h;
2556         break;
2557     case CUBEMAP_1_6:
2558         s->in_transform = xyz_to_cube1x6;
2559         err = prepare_cube_in(ctx);
2560         wf = w * 4.f;
2561         hf = h / 3.f;
2562         break;
2563     case CUBEMAP_6_1:
2564         s->in_transform = xyz_to_cube6x1;
2565         err = prepare_cube_in(ctx);
2566         wf = w / 3.f * 2.f;
2567         hf = h * 2.f;
2568         break;
2569     case EQUIANGULAR:
2570         s->in_transform = xyz_to_eac;
2571         err = prepare_eac_in(ctx);
2572         wf = w;
2573         hf = h / 9.f * 8.f;
2574         break;
2575     case FLAT:
2576         av_log(ctx, AV_LOG_ERROR, "Flat format is not accepted as input.\n");
2577         return AVERROR(EINVAL);
2578     case DUAL_FISHEYE:
2579         s->in_transform = xyz_to_dfisheye;
2580         err = 0;
2581         wf = w;
2582         hf = h;
2583         break;
2584     case BARREL:
2585         s->in_transform = xyz_to_barrel;
2586         err = 0;
2587         wf = w / 5.f * 4.f;
2588         hf = h;
2589         break;
2590     case STEREOGRAPHIC:
2591         s->in_transform = xyz_to_stereographic;
2592         err = 0;
2593         wf = w;
2594         hf = h / 2.f;
2595         break;
2596     case MERCATOR:
2597         s->in_transform = xyz_to_mercator;
2598         err = 0;
2599         wf = w;
2600         hf = h;
2601         break;
2602     case BALL:
2603         s->in_transform = xyz_to_ball;
2604         err = 0;
2605         wf = w;
2606         hf = h / 2.f;
2607         break;
2608     case HAMMER:
2609         s->in_transform = xyz_to_hammer;
2610         err = 0;
2611         wf = w;
2612         hf = h;
2613         break;
2614     default:
2615         av_log(ctx, AV_LOG_ERROR, "Specified input format is not handled.\n");
2616         return AVERROR_BUG;
2617     }
2618
2619     if (err != 0) {
2620         return err;
2621     }
2622
2623     switch (s->out) {
2624     case EQUIRECTANGULAR:
2625         s->out_transform = equirect_to_xyz;
2626         prepare_out = NULL;
2627         w = roundf(wf);
2628         h = roundf(hf);
2629         break;
2630     case CUBEMAP_3_2:
2631         s->out_transform = cube3x2_to_xyz;
2632         prepare_out = prepare_cube_out;
2633         w = roundf(wf / 4.f * 3.f);
2634         h = roundf(hf);
2635         break;
2636     case CUBEMAP_1_6:
2637         s->out_transform = cube1x6_to_xyz;
2638         prepare_out = prepare_cube_out;
2639         w = roundf(wf / 4.f);
2640         h = roundf(hf * 3.f);
2641         break;
2642     case CUBEMAP_6_1:
2643         s->out_transform = cube6x1_to_xyz;
2644         prepare_out = prepare_cube_out;
2645         w = roundf(wf / 2.f * 3.f);
2646         h = roundf(hf / 2.f);
2647         break;
2648     case EQUIANGULAR:
2649         s->out_transform = eac_to_xyz;
2650         prepare_out = prepare_eac_out;
2651         w = roundf(wf);
2652         h = roundf(hf / 8.f * 9.f);
2653         break;
2654     case FLAT:
2655         s->out_transform = flat_to_xyz;
2656         prepare_out = prepare_flat_out;
2657         w = roundf(wf);
2658         h = roundf(hf);
2659         break;
2660     case DUAL_FISHEYE:
2661         s->out_transform = dfisheye_to_xyz;
2662         prepare_out = NULL;
2663         w = roundf(wf);
2664         h = roundf(hf);
2665         break;
2666     case BARREL:
2667         s->out_transform = barrel_to_xyz;
2668         prepare_out = NULL;
2669         w = roundf(wf / 4.f * 5.f);
2670         h = roundf(hf);
2671         break;
2672     case STEREOGRAPHIC:
2673         s->out_transform = stereographic_to_xyz;
2674         prepare_out = prepare_stereographic_out;
2675         w = roundf(wf);
2676         h = roundf(hf * 2.f);
2677         break;
2678     case MERCATOR:
2679         s->out_transform = mercator_to_xyz;
2680         prepare_out = NULL;
2681         w = roundf(wf);
2682         h = roundf(hf);
2683         break;
2684     case BALL:
2685         s->out_transform = ball_to_xyz;
2686         prepare_out = NULL;
2687         w = roundf(wf);
2688         h = roundf(hf * 2.f);
2689         break;
2690     case HAMMER:
2691         s->out_transform = hammer_to_xyz;
2692         prepare_out = NULL;
2693         w = roundf(wf);
2694         h = roundf(hf);
2695         break;
2696     default:
2697         av_log(ctx, AV_LOG_ERROR, "Specified output format is not handled.\n");
2698         return AVERROR_BUG;
2699     }
2700
2701     // Override resolution with user values if specified
2702     if (s->width > 0 && s->height > 0) {
2703         w = s->width;
2704         h = s->height;
2705     } else if (s->width > 0 || s->height > 0) {
2706         av_log(ctx, AV_LOG_ERROR, "Both width and height values should be specified.\n");
2707         return AVERROR(EINVAL);
2708     } else {
2709         if (s->out_transpose)
2710             FFSWAP(int, w, h);
2711
2712         if (s->in_transpose)
2713             FFSWAP(int, w, h);
2714     }
2715
2716     if (s->d_fov > 0.f)
2717         fov_from_dfov(s, w, h);
2718
2719     if (prepare_out) {
2720         err = prepare_out(ctx);
2721         if (err != 0)
2722             return err;
2723     }
2724
2725     set_dimensions(s->pr_width, s->pr_height, w, h, desc);
2726
2727     s->out_width = s->pr_width[0];
2728     s->out_height = s->pr_height[0];
2729
2730     if (s->out_transpose)
2731         FFSWAP(int, s->out_width, s->out_height);
2732
2733     switch (s->out_stereo) {
2734     case STEREO_2D:
2735         out_offset_w = out_offset_h = 0;
2736         break;
2737     case STEREO_SBS:
2738         out_offset_w = w;
2739         out_offset_h = 0;
2740         w *= 2;
2741         break;
2742     case STEREO_TB:
2743         out_offset_w = 0;
2744         out_offset_h = h;
2745         h *= 2;
2746         break;
2747     default:
2748         av_assert0(0);
2749     }
2750
2751     set_dimensions(s->out_offset_w, s->out_offset_h, out_offset_w, out_offset_h, desc);
2752     set_dimensions(s->planewidth, s->planeheight, w, h, desc);
2753
2754     for (int i = 0; i < 4; i++)
2755         s->uv_linesize[i] = FFALIGN(s->pr_width[i], 8);
2756
2757     outlink->h = h;
2758     outlink->w = w;
2759
2760     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
2761
2762     if (desc->log2_chroma_h == desc->log2_chroma_w && desc->log2_chroma_h == 0) {
2763         s->nb_allocated = 1;
2764         s->map[0] = s->map[1] = s->map[2] = s->map[3] = 0;
2765     } else {
2766         s->nb_allocated = 2;
2767         s->map[0] = 0;
2768         s->map[1] = s->map[2] = 1;
2769         s->map[3] = 0;
2770     }
2771
2772     for (int i = 0; i < s->nb_allocated; i++)
2773         allocate_plane(s, sizeof_uv, sizeof_ker, i);
2774
2775     calculate_rotation_matrix(s->yaw, s->pitch, s->roll, s->rot_mat, s->rotation_order);
2776     set_mirror_modifier(s->h_flip, s->v_flip, s->d_flip, s->output_mirror_modifier);
2777
2778     ctx->internal->execute(ctx, v360_slice, NULL, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
2779
2780     return 0;
2781 }
2782
2783 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
2784 {
2785     AVFilterContext *ctx = inlink->dst;
2786     AVFilterLink *outlink = ctx->outputs[0];
2787     V360Context *s = ctx->priv;
2788     AVFrame *out;
2789     ThreadData td;
2790
2791     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
2792     if (!out) {
2793         av_frame_free(&in);
2794         return AVERROR(ENOMEM);
2795     }
2796     av_frame_copy_props(out, in);
2797
2798     td.in = in;
2799     td.out = out;
2800
2801     ctx->internal->execute(ctx, s->remap_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
2802
2803     av_frame_free(&in);
2804     return ff_filter_frame(outlink, out);
2805 }
2806
2807 static av_cold void uninit(AVFilterContext *ctx)
2808 {
2809     V360Context *s = ctx->priv;
2810
2811     for (int p = 0; p < s->nb_allocated; p++) {
2812         av_freep(&s->u[p]);
2813         av_freep(&s->v[p]);
2814         av_freep(&s->ker[p]);
2815     }
2816 }
2817
2818 static const AVFilterPad inputs[] = {
2819     {
2820         .name         = "default",
2821         .type         = AVMEDIA_TYPE_VIDEO,
2822         .filter_frame = filter_frame,
2823     },
2824     { NULL }
2825 };
2826
2827 static const AVFilterPad outputs[] = {
2828     {
2829         .name         = "default",
2830         .type         = AVMEDIA_TYPE_VIDEO,
2831         .config_props = config_output,
2832     },
2833     { NULL }
2834 };
2835
2836 AVFilter ff_vf_v360 = {
2837     .name          = "v360",
2838     .description   = NULL_IF_CONFIG_SMALL("Convert 360 projection of video."),
2839     .priv_size     = sizeof(V360Context),
2840     .uninit        = uninit,
2841     .query_formats = query_formats,
2842     .inputs        = inputs,
2843     .outputs       = outputs,
2844     .priv_class    = &v360_class,
2845     .flags         = AVFILTER_FLAG_SLICE_THREADS,
2846 };