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