]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_v360.c
e8ce4e790d77ea1d9b5f898c59717ae11116ff74
[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)\n
27  * 1) Calculate OpenGL-like coordinates (x, y, z) for pixel position (i, j)\n
28  * 2) Apply 360 operations (rotation, mirror) to (x, y, z)\n
29  * 3) Calculate pixel position (u, v) in input frame\n
30  * 4) Calculate interpolation window and weight for each pixel
31  *
32  * (for each frame)\n
33  * 5) Remap input frame to output frame using precalculated data\n
34  */
35
36 #include "libavutil/eval.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/pixdesc.h"
39 #include "libavutil/opt.h"
40 #include "avfilter.h"
41 #include "formats.h"
42 #include "internal.h"
43 #include "video.h"
44
45 enum Projections {
46     EQUIRECTANGULAR,
47     CUBEMAP_3_2,
48     CUBEMAP_6_1,
49     EQUIANGULAR,
50     FLAT,
51     DUAL_FISHEYE,
52     NB_PROJECTIONS,
53 };
54
55 enum InterpMethod {
56     NEAREST,
57     BILINEAR,
58     BICUBIC,
59     LANCZOS,
60     NB_INTERP_METHODS,
61 };
62
63 enum Faces {
64     TOP_LEFT,
65     TOP_MIDDLE,
66     TOP_RIGHT,
67     BOTTOM_LEFT,
68     BOTTOM_MIDDLE,
69     BOTTOM_RIGHT,
70     NB_FACES,
71 };
72
73 enum Direction {
74     RIGHT,  ///< Axis +X
75     LEFT,   ///< Axis -X
76     UP,     ///< Axis +Y
77     DOWN,   ///< Axis -Y
78     FRONT,  ///< Axis -Z
79     BACK,   ///< Axis +Z
80     NB_DIRECTIONS,
81 };
82
83 enum Rotation {
84     ROT_0,
85     ROT_90,
86     ROT_180,
87     ROT_270,
88     NB_ROTATIONS,
89 };
90
91 typedef struct V360Context {
92     const AVClass *class;
93     int in, out;
94     int interp;
95     int width, height;
96     char* in_forder;
97     char* out_forder;
98     char* in_frot;
99     char* out_frot;
100
101     int in_cubemap_face_order[6];
102     int out_cubemap_direction_order[6];
103     int in_cubemap_face_rotation[6];
104     int out_cubemap_face_rotation[6];
105
106     float in_pad, out_pad;
107
108     float yaw, pitch, roll;
109
110     int h_flip, v_flip, d_flip;
111
112     float h_fov, v_fov;
113     float flat_range[3];
114
115     int planewidth[4], planeheight[4];
116     int inplanewidth[4], inplaneheight[4];
117     int nb_planes;
118
119     void *remap[4];
120
121     int (*remap_slice)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs);
122 } V360Context;
123
124 typedef struct ThreadData {
125     V360Context *s;
126     AVFrame *in;
127     AVFrame *out;
128     int nb_planes;
129 } ThreadData;
130
131 #define OFFSET(x) offsetof(V360Context, x)
132 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
133
134 static const AVOption v360_options[] = {
135     {     "input", "set input projection",              OFFSET(in), AV_OPT_TYPE_INT,    {.i64=EQUIRECTANGULAR}, 0,    NB_PROJECTIONS-1, FLAGS, "in" },
136     {         "e", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "in" },
137     {      "c3x2", "cubemap3x2",                                 0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_3_2},     0,                   0, FLAGS, "in" },
138     {      "c6x1", "cubemap6x1",                                 0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_6_1},     0,                   0, FLAGS, "in" },
139     {       "eac", "equi-angular",                               0, AV_OPT_TYPE_CONST,  {.i64=EQUIANGULAR},     0,                   0, FLAGS, "in" },
140     {  "dfisheye", "dual fisheye",                               0, AV_OPT_TYPE_CONST,  {.i64=DUAL_FISHEYE},    0,                   0, FLAGS, "in" },
141     {    "output", "set output projection",            OFFSET(out), AV_OPT_TYPE_INT,    {.i64=CUBEMAP_3_2},     0,    NB_PROJECTIONS-1, FLAGS, "out" },
142     {         "e", "equirectangular",                            0, AV_OPT_TYPE_CONST,  {.i64=EQUIRECTANGULAR}, 0,                   0, FLAGS, "out" },
143     {      "c3x2", "cubemap3x2",                                 0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_3_2},     0,                   0, FLAGS, "out" },
144     {      "c6x1", "cubemap6x1",                                 0, AV_OPT_TYPE_CONST,  {.i64=CUBEMAP_6_1},     0,                   0, FLAGS, "out" },
145     {       "eac", "equi-angular",                               0, AV_OPT_TYPE_CONST,  {.i64=EQUIANGULAR},     0,                   0, FLAGS, "out" },
146     {      "flat", "regular video",                              0, AV_OPT_TYPE_CONST,  {.i64=FLAT},            0,                   0, FLAGS, "out" },
147     {    "interp", "set interpolation method",      OFFSET(interp), AV_OPT_TYPE_INT,    {.i64=BILINEAR},        0, NB_INTERP_METHODS-1, FLAGS, "interp" },
148     {      "near", "nearest neighbour",                          0, AV_OPT_TYPE_CONST,  {.i64=NEAREST},         0,                   0, FLAGS, "interp" },
149     {   "nearest", "nearest neighbour",                          0, AV_OPT_TYPE_CONST,  {.i64=NEAREST},         0,                   0, FLAGS, "interp" },
150     {      "line", "bilinear interpolation",                     0, AV_OPT_TYPE_CONST,  {.i64=BILINEAR},        0,                   0, FLAGS, "interp" },
151     {    "linear", "bilinear interpolation",                     0, AV_OPT_TYPE_CONST,  {.i64=BILINEAR},        0,                   0, FLAGS, "interp" },
152     {      "cube", "bicubic interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=BICUBIC},         0,                   0, FLAGS, "interp" },
153     {     "cubic", "bicubic interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=BICUBIC},         0,                   0, FLAGS, "interp" },
154     {      "lanc", "lanczos interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=LANCZOS},         0,                   0, FLAGS, "interp" },
155     {   "lanczos", "lanczos interpolation",                      0, AV_OPT_TYPE_CONST,  {.i64=LANCZOS},         0,                   0, FLAGS, "interp" },
156     {         "w", "output width",                   OFFSET(width), AV_OPT_TYPE_INT,    {.i64=0},               0,             INT_MAX, FLAGS, "w"},
157     {         "h", "output height",                 OFFSET(height), AV_OPT_TYPE_INT,    {.i64=0},               0,             INT_MAX, FLAGS, "h"},
158     { "in_forder", "input cubemap face order",   OFFSET(in_forder), AV_OPT_TYPE_STRING, {.str="rludfb"},        0,     NB_DIRECTIONS-1, FLAGS, "in_forder"},
159     {"out_forder", "output cubemap face order", OFFSET(out_forder), AV_OPT_TYPE_STRING, {.str="rludfb"},        0,     NB_DIRECTIONS-1, FLAGS, "out_forder"},
160     {   "in_frot", "input cubemap face rotation",  OFFSET(in_frot), AV_OPT_TYPE_STRING, {.str="000000"},        0,     NB_DIRECTIONS-1, FLAGS, "in_frot"},
161     {  "out_frot", "output cubemap face rotation",OFFSET(out_frot), AV_OPT_TYPE_STRING, {.str="000000"},        0,     NB_DIRECTIONS-1, FLAGS, "out_frot"},
162     {    "in_pad", "input cubemap pads",            OFFSET(in_pad), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},           0.f,                 1.f, FLAGS, "in_pad"},
163     {   "out_pad", "output cubemap pads",          OFFSET(out_pad), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},           0.f,                 1.f, FLAGS, "out_pad"},
164     {       "yaw", "yaw rotation",                     OFFSET(yaw), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "yaw"},
165     {     "pitch", "pitch rotation",                 OFFSET(pitch), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "pitch"},
166     {      "roll", "roll rotation",                   OFFSET(roll), AV_OPT_TYPE_FLOAT,  {.dbl=0.f},        -180.f,               180.f, FLAGS, "roll"},
167     {     "h_fov", "horizontal field of view",       OFFSET(h_fov), AV_OPT_TYPE_FLOAT,  {.dbl=90.f},          0.f,               180.f, FLAGS, "h_fov"},
168     {     "v_fov", "vertical field of view",         OFFSET(v_fov), AV_OPT_TYPE_FLOAT,  {.dbl=45.f},          0.f,                90.f, FLAGS, "v_fov"},
169     {    "h_flip", "flip video horizontally",       OFFSET(h_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "h_flip"},
170     {    "v_flip", "flip video vertically",         OFFSET(v_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "v_flip"},
171     {    "d_flip", "flip video indepth",            OFFSET(d_flip), AV_OPT_TYPE_BOOL,   {.i64=0},               0,                   1, FLAGS, "d_flip"},
172     { NULL }
173 };
174
175 AVFILTER_DEFINE_CLASS(v360);
176
177 static int query_formats(AVFilterContext *ctx)
178 {
179     static const enum AVPixelFormat pix_fmts[] = {
180         // YUVA444
181         AV_PIX_FMT_YUVA444P,   AV_PIX_FMT_YUVA444P9,
182         AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12,
183         AV_PIX_FMT_YUVA444P16,
184
185         // YUVA422
186         AV_PIX_FMT_YUVA422P,   AV_PIX_FMT_YUVA422P9,
187         AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12,
188         AV_PIX_FMT_YUVA422P16,
189
190         // YUVA420
191         AV_PIX_FMT_YUVA420P,   AV_PIX_FMT_YUVA420P9,
192         AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
193
194         // YUVJ
195         AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
196         AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
197         AV_PIX_FMT_YUVJ411P,
198
199         // YUV444
200         AV_PIX_FMT_YUV444P,   AV_PIX_FMT_YUV444P9,
201         AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12,
202         AV_PIX_FMT_YUV444P14, AV_PIX_FMT_YUV444P16,
203
204         // YUV440
205         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV440P10,
206         AV_PIX_FMT_YUV440P12,
207
208         // YUV422
209         AV_PIX_FMT_YUV422P,   AV_PIX_FMT_YUV422P9,
210         AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12,
211         AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV422P16,
212
213         // YUV420
214         AV_PIX_FMT_YUV420P,   AV_PIX_FMT_YUV420P9,
215         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12,
216         AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV420P16,
217
218         // YUV411
219         AV_PIX_FMT_YUV411P,
220
221         // YUV410
222         AV_PIX_FMT_YUV410P,
223
224         // GBR
225         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRP9,
226         AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12,
227         AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
228
229         // GBRA
230         AV_PIX_FMT_GBRAP,   AV_PIX_FMT_GBRAP10,
231         AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
232
233         // GRAY
234         AV_PIX_FMT_GRAY8,  AV_PIX_FMT_GRAY9,
235         AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12,
236         AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
237
238         AV_PIX_FMT_NONE
239     };
240
241     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
242     if (!fmts_list)
243         return AVERROR(ENOMEM);
244     return ff_set_common_formats(ctx, fmts_list);
245 }
246
247 typedef struct XYRemap1 {
248     uint16_t u;
249     uint16_t v;
250 } XYRemap1;
251
252 /**
253  * Generate no-interpolation remapping function with a given pixel depth.
254  *
255  * @param bits number of bits per pixel
256  * @param div number of bytes per pixel
257  */
258 #define DEFINE_REMAP1(bits, div)                                                             \
259 static int remap1_##bits##bit_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) \
260 {                                                                                            \
261     ThreadData *td = (ThreadData*)arg;                                                       \
262     const V360Context *s = td->s;                                                            \
263     const AVFrame *in = td->in;                                                              \
264     AVFrame *out = td->out;                                                                  \
265                                                                                              \
266     int plane, x, y;                                                                         \
267                                                                                              \
268     for (plane = 0; plane < td->nb_planes; plane++) {                                        \
269         const int in_linesize  = in->linesize[plane]  / div;                                 \
270         const int out_linesize = out->linesize[plane] / div;                                 \
271         const uint##bits##_t *src = (const uint##bits##_t *)in->data[plane];                 \
272         uint##bits##_t *dst = (uint##bits##_t *)out->data[plane];                            \
273         const XYRemap1 *remap = s->remap[plane];                                             \
274         const int width = s->planewidth[plane];                                              \
275         const int height = s->planeheight[plane];                                            \
276                                                                                              \
277         const int slice_start = (height *  jobnr     ) / nb_jobs;                            \
278         const int slice_end   = (height * (jobnr + 1)) / nb_jobs;                            \
279                                                                                              \
280         for (y = slice_start; y < slice_end; y++) {                                          \
281             uint##bits##_t *d = dst + y * out_linesize;                                      \
282             for (x = 0; x < width; x++) {                                                    \
283                 const XYRemap1 *r = &remap[y * width + x];                                   \
284                                                                                              \
285                 *d++ = src[r->v * in_linesize + r->u];                                       \
286             }                                                                                \
287         }                                                                                    \
288     }                                                                                        \
289                                                                                              \
290     return 0;                                                                                \
291 }
292
293 DEFINE_REMAP1( 8, 1)
294 DEFINE_REMAP1(16, 2)
295
296 typedef struct XYRemap2 {
297     uint16_t u[2][2];
298     uint16_t v[2][2];
299     float ker[2][2];
300 } XYRemap2;
301
302 typedef struct XYRemap4 {
303     uint16_t u[4][4];
304     uint16_t v[4][4];
305     float ker[4][4];
306 } XYRemap4;
307
308 /**
309  * Generate remapping function with a given window size and pixel depth.
310  *
311  * @param window_size size of interpolation window
312  * @param bits number of bits per pixel
313  * @param div number of bytes per pixel
314  */
315 #define DEFINE_REMAP(window_size, bits, div)                                                               \
316 static int remap##window_size##_##bits##bit_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) \
317 {                                                                                                          \
318     ThreadData *td = (ThreadData*)arg;                                                                     \
319     const V360Context *s = td->s;                                                                          \
320     const AVFrame *in = td->in;                                                                            \
321     AVFrame *out = td->out;                                                                                \
322                                                                                                            \
323     int plane, x, y, i, j;                                                                                 \
324                                                                                                            \
325     for (plane = 0; plane < td->nb_planes; plane++) {                                                      \
326         const int in_linesize  = in->linesize[plane]  / div;                                               \
327         const int out_linesize = out->linesize[plane] / div;                                               \
328         const uint##bits##_t *src = (const uint##bits##_t *)in->data[plane];                               \
329         uint##bits##_t *dst = (uint##bits##_t *)out->data[plane];                                          \
330         const XYRemap##window_size *remap = s->remap[plane];                                               \
331         const int width = s->planewidth[plane];                                                            \
332         const int height = s->planeheight[plane];                                                          \
333                                                                                                            \
334         const int slice_start = (height *  jobnr     ) / nb_jobs;                                          \
335         const int slice_end   = (height * (jobnr + 1)) / nb_jobs;                                          \
336                                                                                                            \
337         for (y = slice_start; y < slice_end; y++) {                                                        \
338             uint##bits##_t *d = dst + y * out_linesize;                                                    \
339             for (x = 0; x < width; x++) {                                                                  \
340                 const XYRemap##window_size *r = &remap[y * width + x];                                     \
341                 float tmp = 0.f;                                                                           \
342                                                                                                            \
343                 for (i = 0; i < window_size; i++) {                                                        \
344                     for (j = 0; j < window_size; j++) {                                                    \
345                         tmp += r->ker[i][j] * src[r->v[i][j] * in_linesize + r->u[i][j]];                  \
346                     }                                                                                      \
347                 }                                                                                          \
348                                                                                                            \
349                 *d++ = av_clip_uint##bits(roundf(tmp));                                                    \
350             }                                                                                              \
351         }                                                                                                  \
352     }                                                                                                      \
353                                                                                                            \
354     return 0;                                                                                              \
355 }
356
357 DEFINE_REMAP(2,  8, 1)
358 DEFINE_REMAP(4,  8, 1)
359 DEFINE_REMAP(2, 16, 2)
360 DEFINE_REMAP(4, 16, 2)
361
362 /**
363  * Save nearest pixel coordinates for remapping.
364  *
365  * @param du horizontal relative coordinate
366  * @param dv vertical relative coordinate
367  * @param shift shift for remap array
368  * @param r_tmp calculated 4x4 window
369  * @param r_void remap data
370  */
371 static void nearest_kernel(float du, float dv, int shift, const XYRemap4 *r_tmp, void *r_void)
372 {
373     XYRemap1 *r = (XYRemap1*)r_void + shift;
374     const int i = roundf(dv) + 1;
375     const int j = roundf(du) + 1;
376
377     r->u = r_tmp->u[i][j];
378     r->v = r_tmp->v[i][j];
379 }
380
381 /**
382  * Calculate kernel for bilinear interpolation.
383  *
384  * @param du horizontal relative coordinate
385  * @param dv vertical relative coordinate
386  * @param shift shift for remap array
387  * @param r_tmp calculated 4x4 window
388  * @param r_void remap data
389  */
390 static void bilinear_kernel(float du, float dv, int shift, const XYRemap4 *r_tmp, void *r_void)
391 {
392     XYRemap2 *r = (XYRemap2*)r_void + shift;
393     int i, j;
394
395     for (i = 0; i < 2; i++) {
396         for (j = 0; j < 2; j++) {
397             r->u[i][j] = r_tmp->u[i + 1][j + 1];
398             r->v[i][j] = r_tmp->v[i + 1][j + 1];
399         }
400     }
401
402     r->ker[0][0] = (1.f - du) * (1.f - dv);
403     r->ker[0][1] =        du  * (1.f - dv);
404     r->ker[1][0] = (1.f - du) *        dv;
405     r->ker[1][1] =        du  *        dv;
406 }
407
408 /**
409  * Calculate 1-dimensional cubic coefficients.
410  *
411  * @param t relative coordinate
412  * @param coeffs coefficients
413  */
414 static inline void calculate_bicubic_coeffs(float t, float *coeffs)
415 {
416     const float tt  = t * t;
417     const float ttt = t * t * t;
418
419     coeffs[0] =     - t / 3.f + tt / 2.f - ttt / 6.f;
420     coeffs[1] = 1.f - t / 2.f - tt       + ttt / 2.f;
421     coeffs[2] =       t       + tt / 2.f - ttt / 2.f;
422     coeffs[3] =     - t / 6.f            + ttt / 6.f;
423 }
424
425 /**
426  * Calculate kernel for bicubic interpolation.
427  *
428  * @param du horizontal relative coordinate
429  * @param dv vertical relative coordinate
430  * @param shift shift for remap array
431  * @param r_tmp calculated 4x4 window
432  * @param r_void remap data
433  */
434 static void bicubic_kernel(float du, float dv, int shift, const XYRemap4 *r_tmp, void *r_void)
435 {
436     XYRemap4 *r = (XYRemap4*)r_void + shift;
437     int i, j;
438     float du_coeffs[4];
439     float dv_coeffs[4];
440
441     calculate_bicubic_coeffs(du, du_coeffs);
442     calculate_bicubic_coeffs(dv, dv_coeffs);
443
444     for (i = 0; i < 4; i++) {
445         for (j = 0; j < 4; j++) {
446             r->u[i][j] = r_tmp->u[i][j];
447             r->v[i][j] = r_tmp->v[i][j];
448             r->ker[i][j] = du_coeffs[j] * dv_coeffs[i];
449         }
450     }
451 }
452
453 /**
454  * Calculate 1-dimensional lanczos coefficients.
455  *
456  * @param t relative coordinate
457  * @param coeffs coefficients
458  */
459 static inline void calculate_lanczos_coeffs(float t, float *coeffs)
460 {
461     int i;
462     float sum = 0.f;
463
464     for (i = 0; i < 4; i++) {
465         const float x = M_PI * (t - i + 1);
466         if (x == 0.f) {
467             coeffs[i] = 1.f;
468         } else {
469             coeffs[i] = sinf(x) * sinf(x / 2.f) / (x * x / 2.f);
470         }
471         sum += coeffs[i];
472     }
473
474     for (i = 0; i < 4; i++) {
475         coeffs[i] /= sum;
476     }
477 }
478
479 /**
480  * Calculate kernel for lanczos interpolation.
481  *
482  * @param du horizontal relative coordinate
483  * @param dv vertical relative coordinate
484  * @param shift shift for remap array
485  * @param r_tmp calculated 4x4 window
486  * @param r_void remap data
487  */
488 static void lanczos_kernel(float du, float dv, int shift, const XYRemap4 *r_tmp, void *r_void)
489 {
490     XYRemap4 *r = (XYRemap4*)r_void + shift;
491     int i, j;
492     float du_coeffs[4];
493     float dv_coeffs[4];
494
495     calculate_lanczos_coeffs(du, du_coeffs);
496     calculate_lanczos_coeffs(dv, dv_coeffs);
497
498     for (i = 0; i < 4; i++) {
499         for (j = 0; j < 4; j++) {
500             r->u[i][j] = r_tmp->u[i][j];
501             r->v[i][j] = r_tmp->v[i][j];
502             r->ker[i][j] = du_coeffs[j] * dv_coeffs[i];
503         }
504     }
505 }
506
507 /**
508  * Modulo operation with only positive remainders.
509  *
510  * @param a dividend
511  * @param b divisor
512  *
513  * @return positive remainder of (a / b)
514  */
515 static inline int mod(int a, int b)
516 {
517     const int res = a % b;
518     if (res < 0) {
519         return res + b;
520     } else {
521         return res;
522     }
523 }
524
525 /**
526  * Convert char to corresponding direction.
527  * Used for cubemap options.
528  */
529 static int get_direction(char c)
530 {
531     switch (c) {
532     case 'r':
533         return RIGHT;
534     case 'l':
535         return LEFT;
536     case 'u':
537         return UP;
538     case 'd':
539         return DOWN;
540     case 'f':
541         return FRONT;
542     case 'b':
543         return BACK;
544     default:
545         return -1;
546     }
547 }
548
549 /**
550  * Convert char to corresponding rotation angle.
551  * Used for cubemap options.
552  */
553 static int get_rotation(char c)
554 {
555     switch (c) {
556     case '0':
557         return ROT_0;
558     case '1':
559         return ROT_90;
560     case '2':
561         return ROT_180;
562     case '3':
563         return ROT_270;
564     default:
565         return -1;
566     }
567 }
568
569 /**
570  * Prepare data for processing cubemap input format.
571  *
572  * @param ctx filter context
573  *
574  * @return error code
575  */
576 static int prepare_cube_in(AVFilterContext *ctx)
577 {
578     V360Context *s = ctx->priv;
579
580     for (int face = 0; face < NB_FACES; face++) {
581         const char c = s->in_forder[face];
582         int direction;
583
584         if (c == '\0') {
585             av_log(ctx, AV_LOG_ERROR,
586                    "Incomplete in_forder option. Direction for all 6 faces should be specified.\n");
587             return AVERROR(EINVAL);
588         }
589
590         direction = get_direction(c);
591         if (direction == -1) {
592             av_log(ctx, AV_LOG_ERROR,
593                    "Incorrect direction symbol '%c' in in_forder option.\n", c);
594             return AVERROR(EINVAL);
595         }
596
597         s->in_cubemap_face_order[direction] = face;
598     }
599
600     for (int face = 0; face < NB_FACES; face++) {
601         const char c = s->in_frot[face];
602         int rotation;
603
604         if (c == '\0') {
605             av_log(ctx, AV_LOG_ERROR,
606                    "Incomplete in_frot option. Rotation for all 6 faces should be specified.\n");
607             return AVERROR(EINVAL);
608         }
609
610         rotation = get_rotation(c);
611         if (rotation == -1) {
612             av_log(ctx, AV_LOG_ERROR,
613                    "Incorrect rotation symbol '%c' in in_frot option.\n", c);
614             return AVERROR(EINVAL);
615         }
616
617         s->in_cubemap_face_rotation[face] = rotation;
618     }
619
620     return 0;
621 }
622
623 /**
624  * Prepare data for processing cubemap output format.
625  *
626  * @param ctx filter context
627  *
628  * @return error code
629  */
630 static int prepare_cube_out(AVFilterContext *ctx)
631 {
632     V360Context *s = ctx->priv;
633
634     for (int face = 0; face < NB_FACES; face++) {
635         const char c = s->out_forder[face];
636         int direction;
637
638         if (c == '\0') {
639             av_log(ctx, AV_LOG_ERROR,
640                    "Incomplete out_forder option. Direction for all 6 faces should be specified.\n");
641             return AVERROR(EINVAL);
642         }
643
644         direction = get_direction(c);
645         if (direction == -1) {
646             av_log(ctx, AV_LOG_ERROR,
647                    "Incorrect direction symbol '%c' in out_forder option.\n", c);
648             return AVERROR(EINVAL);
649         }
650
651         s->out_cubemap_direction_order[face] = direction;
652     }
653
654     for (int face = 0; face < NB_FACES; face++) {
655         const char c = s->out_frot[face];
656         int rotation;
657
658         if (c == '\0') {
659             av_log(ctx, AV_LOG_ERROR,
660                    "Incomplete out_frot option. Rotation for all 6 faces should be specified.\n");
661             return AVERROR(EINVAL);
662         }
663
664         rotation = get_rotation(c);
665         if (rotation == -1) {
666             av_log(ctx, AV_LOG_ERROR,
667                    "Incorrect rotation symbol '%c' in out_frot option.\n", c);
668             return AVERROR(EINVAL);
669         }
670
671         s->out_cubemap_face_rotation[face] = rotation;
672     }
673
674     return 0;
675 }
676
677 static inline void rotate_cube_face(float *uf, float *vf, int rotation)
678 {
679     float tmp;
680
681     switch (rotation) {
682     case ROT_0:
683         break;
684     case ROT_90:
685         tmp =  *uf;
686         *uf = -*vf;
687         *vf =  tmp;
688         break;
689     case ROT_180:
690         *uf = -*uf;
691         *vf = -*vf;
692         break;
693     case ROT_270:
694         tmp = -*uf;
695         *uf =  *vf;
696         *vf =  tmp;
697         break;
698     }
699 }
700
701 static inline void rotate_cube_face_inverse(float *uf, float *vf, int rotation)
702 {
703     float tmp;
704
705     switch (rotation) {
706     case ROT_0:
707         break;
708     case ROT_90:
709         tmp = -*uf;
710         *uf =  *vf;
711         *vf =  tmp;
712         break;
713     case ROT_180:
714         *uf = -*uf;
715         *vf = -*vf;
716         break;
717     case ROT_270:
718         tmp =  *uf;
719         *uf = -*vf;
720         *vf =  tmp;
721         break;
722     }
723 }
724
725 /**
726  * Calculate 3D coordinates on sphere for corresponding cubemap position.
727  * Common operation for every cubemap.
728  *
729  * @param s filter context
730  * @param uf horizontal cubemap coordinate [0, 1)
731  * @param vf vertical cubemap coordinate [0, 1)
732  * @param face face of cubemap
733  * @param vec coordinates on sphere
734  */
735 static void cube_to_xyz(const V360Context *s,
736                         float uf, float vf, int face,
737                         float *vec)
738 {
739     const int direction = s->out_cubemap_direction_order[face];
740     float norm;
741     float l_x, l_y, l_z;
742
743     uf /= (1.f - s->out_pad);
744     vf /= (1.f - s->out_pad);
745
746     rotate_cube_face_inverse(&uf, &vf, s->out_cubemap_face_rotation[face]);
747
748     switch (direction) {
749     case RIGHT:
750         l_x =  1.f;
751         l_y = -vf;
752         l_z =  uf;
753         break;
754     case LEFT:
755         l_x = -1.f;
756         l_y = -vf;
757         l_z = -uf;
758         break;
759     case UP:
760         l_x =  uf;
761         l_y =  1.f;
762         l_z = -vf;
763         break;
764     case DOWN:
765         l_x =  uf;
766         l_y = -1.f;
767         l_z =  vf;
768         break;
769     case FRONT:
770         l_x =  uf;
771         l_y = -vf;
772         l_z = -1.f;
773         break;
774     case BACK:
775         l_x = -uf;
776         l_y = -vf;
777         l_z =  1.f;
778         break;
779     }
780
781     norm = sqrtf(l_x * l_x + l_y * l_y + l_z * l_z);
782     vec[0] = l_x / norm;
783     vec[1] = l_y / norm;
784     vec[2] = l_z / norm;
785 }
786
787 /**
788  * Calculate cubemap position for corresponding 3D coordinates on sphere.
789  * Common operation for every cubemap.
790  *
791  * @param s filter context
792  * @param vec coordinated on sphere
793  * @param uf horizontal cubemap coordinate [0, 1)
794  * @param vf vertical cubemap coordinate [0, 1)
795  * @param direction direction of view
796  */
797 static void xyz_to_cube(const V360Context *s,
798                         const float *vec,
799                         float *uf, float *vf, int *direction)
800 {
801     const float phi   = atan2f(vec[0], -vec[2]);
802     const float theta = asinf(-vec[1]);
803     float phi_norm, theta_threshold;
804     int face;
805
806     if (phi >= -M_PI_4 && phi < M_PI_4) {
807         *direction = FRONT;
808         phi_norm = phi;
809     } else if (phi >= -(M_PI_2 + M_PI_4) && phi < -M_PI_4) {
810         *direction = LEFT;
811         phi_norm = phi + M_PI_2;
812     } else if (phi >= M_PI_4 && phi < M_PI_2 + M_PI_4) {
813         *direction = RIGHT;
814         phi_norm = phi - M_PI_2;
815     } else {
816         *direction = BACK;
817         phi_norm = phi + ((phi > 0.f) ? -M_PI : M_PI);
818     }
819
820     theta_threshold = atanf(cosf(phi_norm));
821     if (theta > theta_threshold) {
822         *direction = DOWN;
823     } else if (theta < -theta_threshold) {
824         *direction = UP;
825     }
826
827     switch (*direction) {
828     case RIGHT:
829         *uf =  vec[2] / vec[0];
830         *vf = -vec[1] / vec[0];
831         break;
832     case LEFT:
833         *uf =  vec[2] / vec[0];
834         *vf =  vec[1] / vec[0];
835         break;
836     case UP:
837         *uf =  vec[0] / vec[1];
838         *vf = -vec[2] / vec[1];
839         break;
840     case DOWN:
841         *uf = -vec[0] / vec[1];
842         *vf = -vec[2] / vec[1];
843         break;
844     case FRONT:
845         *uf = -vec[0] / vec[2];
846         *vf =  vec[1] / vec[2];
847         break;
848     case BACK:
849         *uf = -vec[0] / vec[2];
850         *vf = -vec[1] / vec[2];
851         break;
852     }
853
854     face = s->in_cubemap_face_order[*direction];
855     rotate_cube_face(uf, vf, s->in_cubemap_face_rotation[face]);
856 }
857
858 /**
859  * Find position on another cube face in case of overflow/underflow.
860  * Used for calculation of interpolation window.
861  *
862  * @param s filter context
863  * @param uf horizontal cubemap coordinate
864  * @param vf vertical cubemap coordinate
865  * @param direction direction of view
866  * @param new_uf new horizontal cubemap coordinate
867  * @param new_vf new vertical cubemap coordinate
868  * @param face face position on cubemap
869  */
870 static void process_cube_coordinates(const V360Context *s,
871                                 float uf, float vf, int direction,
872                                 float *new_uf, float *new_vf, int *face)
873 {
874     /*
875      *  Cubemap orientation
876      *
877      *           width
878      *         <------->
879      *         +-------+
880      *         |       |                              U
881      *         | up    |                   h       ------->
882      * +-------+-------+-------+-------+ ^ e      |
883      * |       |       |       |       | | i    V |
884      * | left  | front | right | back  | | g      |
885      * +-------+-------+-------+-------+ v h      v
886      *         |       |                   t
887      *         | down  |
888      *         +-------+
889      */
890
891     *face = s->in_cubemap_face_order[direction];
892     rotate_cube_face_inverse(&uf, &vf, s->in_cubemap_face_rotation[*face]);
893
894     if ((uf < -1.f || uf >= 1.f) && (vf < -1.f || vf >= 1.f)) {
895         // There are no pixels to use in this case
896         *new_uf = uf;
897         *new_vf = vf;
898     } else if (uf < -1.f) {
899         uf += 2.f;
900         switch (direction) {
901         case RIGHT:
902             direction = FRONT;
903             *new_uf =  uf;
904             *new_vf =  vf;
905             break;
906         case LEFT:
907             direction = BACK;
908             *new_uf =  uf;
909             *new_vf =  vf;
910             break;
911         case UP:
912             direction = LEFT;
913             *new_uf =  vf;
914             *new_vf = -uf;
915             break;
916         case DOWN:
917             direction = LEFT;
918             *new_uf = -vf;
919             *new_vf =  uf;
920             break;
921         case FRONT:
922             direction = LEFT;
923             *new_uf =  uf;
924             *new_vf =  vf;
925             break;
926         case BACK:
927             direction = RIGHT;
928             *new_uf =  uf;
929             *new_vf =  vf;
930             break;
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         }
966     } else if (vf < -1.f) {
967         vf += 2.f;
968         switch (direction) {
969         case RIGHT:
970             direction = UP;
971             *new_uf =  vf;
972             *new_vf = -uf;
973             break;
974         case LEFT:
975             direction = UP;
976             *new_uf = -vf;
977             *new_vf =  uf;
978             break;
979         case UP:
980             direction = BACK;
981             *new_uf = -uf;
982             *new_vf = -vf;
983             break;
984         case DOWN:
985             direction = FRONT;
986             *new_uf =  uf;
987             *new_vf =  vf;
988             break;
989         case FRONT:
990             direction = UP;
991             *new_uf =  uf;
992             *new_vf =  vf;
993             break;
994         case BACK:
995             direction = UP;
996             *new_uf = -uf;
997             *new_vf = -vf;
998             break;
999         }
1000     } else if (vf >= 1.f) {
1001         vf -= 2.f;
1002         switch (direction) {
1003         case RIGHT:
1004             direction = DOWN;
1005             *new_uf = -vf;
1006             *new_vf =  uf;
1007             break;
1008         case LEFT:
1009             direction = DOWN;
1010             *new_uf =  vf;
1011             *new_vf = -uf;
1012             break;
1013         case UP:
1014             direction = FRONT;
1015             *new_uf =  uf;
1016             *new_vf =  vf;
1017             break;
1018         case DOWN:
1019             direction = BACK;
1020             *new_uf = -uf;
1021             *new_vf = -vf;
1022             break;
1023         case FRONT:
1024             direction = DOWN;
1025             *new_uf =  uf;
1026             *new_vf =  vf;
1027             break;
1028         case BACK:
1029             direction = DOWN;
1030             *new_uf = -uf;
1031             *new_vf = -vf;
1032             break;
1033         }
1034     } else {
1035         // Inside cube face
1036         *new_uf = uf;
1037         *new_vf = vf;
1038     }
1039
1040     *face = s->in_cubemap_face_order[direction];
1041     rotate_cube_face(new_uf, new_vf, s->in_cubemap_face_rotation[*face]);
1042 }
1043
1044 /**
1045  * Calculate 3D coordinates on sphere for corresponding frame position in cubemap3x2 format.
1046  *
1047  * @param s filter context
1048  * @param i horizontal position on frame [0, height)
1049  * @param j vertical position on frame [0, width)
1050  * @param width frame width
1051  * @param height frame height
1052  * @param vec coordinates on sphere
1053  */
1054 static void cube3x2_to_xyz(const V360Context *s,
1055                            int i, int j, int width, int height,
1056                            float *vec)
1057 {
1058     const float ew = width  / 3.f;
1059     const float eh = height / 2.f;
1060
1061     const int u_face = floorf(i / ew);
1062     const int v_face = floorf(j / eh);
1063     const int face = u_face + 3 * v_face;
1064
1065     const int u_shift = ceilf(ew * u_face);
1066     const int v_shift = ceilf(eh * v_face);
1067     const int ewi = ceilf(ew * (u_face + 1)) - u_shift;
1068     const int ehi = ceilf(eh * (v_face + 1)) - v_shift;
1069
1070     const float uf = 2.f * (i - u_shift) / ewi - 1.f;
1071     const float vf = 2.f * (j - v_shift) / ehi - 1.f;
1072
1073     cube_to_xyz(s, uf, vf, face, vec);
1074 }
1075
1076 /**
1077  * Calculate frame position in cubemap3x2 format for corresponding 3D coordinates on sphere.
1078  *
1079  * @param s filter context
1080  * @param vec coordinates on sphere
1081  * @param width frame width
1082  * @param height frame height
1083  * @param us horizontal coordinates for interpolation window
1084  * @param vs vertical coordinates for interpolation window
1085  * @param du horizontal relative coordinate
1086  * @param dv vertical relative coordinate
1087  */
1088 static void xyz_to_cube3x2(const V360Context *s,
1089                            const float *vec, int width, int height,
1090                            uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1091 {
1092     const float ew = width  / 3.f;
1093     const float eh = height / 2.f;
1094     float uf, vf;
1095     int ui, vi;
1096     int ewi, ehi;
1097     int i, j;
1098     int direction, face;
1099     int u_face, v_face;
1100
1101     xyz_to_cube(s, vec, &uf, &vf, &direction);
1102
1103     uf *= (1.f - s->in_pad);
1104     vf *= (1.f - s->in_pad);
1105
1106     face = s->in_cubemap_face_order[direction];
1107     u_face = face % 3;
1108     v_face = face / 3;
1109     ewi = ceilf(ew * (u_face + 1)) - ceilf(ew * u_face);
1110     ehi = ceilf(eh * (v_face + 1)) - ceilf(eh * v_face);
1111
1112     uf = 0.5f * ewi * (uf + 1.f);
1113     vf = 0.5f * ehi * (vf + 1.f);
1114
1115     ui = floorf(uf);
1116     vi = floorf(vf);
1117
1118     *du = uf - ui;
1119     *dv = vf - vi;
1120
1121     for (i = -1; i < 3; i++) {
1122         for (j = -1; j < 3; j++) {
1123             int new_ui = ui + j;
1124             int new_vi = vi + i;
1125             int u_shift, v_shift;
1126             int new_ewi, new_ehi;
1127
1128             if (new_ui >= 0 && new_ui < ewi && new_vi >= 0 && new_vi < ehi) {
1129                 face = s->in_cubemap_face_order[direction];
1130
1131                 u_face = face % 3;
1132                 v_face = face / 3;
1133                 u_shift = ceilf(ew * u_face);
1134                 v_shift = ceilf(eh * v_face);
1135             } else {
1136                 uf = 2.f * new_ui / ewi - 1.f;
1137                 vf = 2.f * new_vi / ehi - 1.f;
1138
1139                 uf /= (1.f - s->in_pad);
1140                 vf /= (1.f - s->in_pad);
1141
1142                 process_cube_coordinates(s, uf, vf, direction, &uf, &vf, &face);
1143
1144                 uf *= (1.f - s->in_pad);
1145                 vf *= (1.f - s->in_pad);
1146
1147                 u_face = face % 3;
1148                 v_face = face / 3;
1149                 u_shift = ceilf(ew * u_face);
1150                 v_shift = ceilf(eh * v_face);
1151                 new_ewi = ceilf(ew * (u_face + 1)) - u_shift;
1152                 new_ehi = ceilf(eh * (v_face + 1)) - v_shift;
1153
1154                 new_ui = av_clip(roundf(0.5f * new_ewi * (uf + 1.f)), 0, new_ewi - 1);
1155                 new_vi = av_clip(roundf(0.5f * new_ehi * (vf + 1.f)), 0, new_ehi - 1);
1156             }
1157
1158
1159             us[i + 1][j + 1] = u_shift + new_ui;
1160             vs[i + 1][j + 1] = v_shift + new_vi;
1161         }
1162     }
1163 }
1164
1165 /**
1166  * Calculate 3D coordinates on sphere for corresponding frame position in cubemap6x1 format.
1167  *
1168  * @param s filter context
1169  * @param i horizontal position on frame [0, height)
1170  * @param j vertical position on frame [0, width)
1171  * @param width frame width
1172  * @param height frame height
1173  * @param vec coordinates on sphere
1174  */
1175 static void cube6x1_to_xyz(const V360Context *s,
1176                            int i, int j, int width, int height,
1177                            float *vec)
1178 {
1179     const float ew = width / 6.f;
1180     const float eh = height;
1181
1182     const int face = floorf(i / ew);
1183
1184     const int u_shift = ceilf(ew * face);
1185     const int ewi = ceilf(ew * (face + 1)) - u_shift;
1186
1187     const float uf = 2.f * (i - u_shift) / ewi - 1.f;
1188     const float vf = 2.f *  j            / eh  - 1.f;
1189
1190     cube_to_xyz(s, uf, vf, face, vec);
1191 }
1192
1193 /**
1194  * Calculate frame position in cubemap6x1 format for corresponding 3D coordinates on sphere.
1195  *
1196  * @param s filter context
1197  * @param vec coordinates on sphere
1198  * @param width frame width
1199  * @param height frame height
1200  * @param us horizontal coordinates for interpolation window
1201  * @param vs vertical coordinates for interpolation window
1202  * @param du horizontal relative coordinate
1203  * @param dv vertical relative coordinate
1204  */
1205 static void xyz_to_cube6x1(const V360Context *s,
1206                            const float *vec, int width, int height,
1207                            uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1208 {
1209     const float ew = width / 6.f;
1210     const int ehi = height;
1211     float uf, vf;
1212     int ui, vi;
1213     int ewi;
1214     int i, j;
1215     int direction, face;
1216
1217     xyz_to_cube(s, vec, &uf, &vf, &direction);
1218
1219     uf *= (1.f - s->in_pad);
1220     vf *= (1.f - s->in_pad);
1221
1222     face = s->in_cubemap_face_order[direction];
1223     ewi = ceilf(ew * (face + 1)) - ceilf(ew * face);
1224
1225     uf = 0.5f * ewi * (uf + 1.f);
1226     vf = 0.5f * ehi * (vf + 1.f);
1227
1228     ui = floorf(uf);
1229     vi = floorf(vf);
1230
1231     *du = uf - ui;
1232     *dv = vf - vi;
1233
1234     for (i = -1; i < 3; i++) {
1235         for (j = -1; j < 3; j++) {
1236             int new_ui = ui + j;
1237             int new_vi = vi + i;
1238             int u_shift;
1239             int new_ewi;
1240
1241             if (new_ui >= 0 && new_ui < ewi && new_vi >= 0 && new_vi < ehi) {
1242                 face = s->in_cubemap_face_order[direction];
1243
1244                 u_shift = ceilf(ew * face);
1245             } else {
1246                 uf = 2.f * new_ui / ewi - 1.f;
1247                 vf = 2.f * new_vi / ehi - 1.f;
1248
1249                 uf /= (1.f - s->in_pad);
1250                 vf /= (1.f - s->in_pad);
1251
1252                 process_cube_coordinates(s, uf, vf, direction, &uf, &vf, &face);
1253
1254                 uf *= (1.f - s->in_pad);
1255                 vf *= (1.f - s->in_pad);
1256
1257                 u_shift = ceilf(ew * face);
1258                 new_ewi = ceilf(ew * (face + 1)) - u_shift;
1259
1260                 new_ui = av_clip(roundf(0.5f * new_ewi * (uf + 1.f)), 0, new_ewi - 1);
1261                 new_vi = av_clip(roundf(0.5f *     ehi * (vf + 1.f)), 0,     ehi - 1);
1262             }
1263
1264
1265             us[i + 1][j + 1] = u_shift + new_ui;
1266             vs[i + 1][j + 1] =           new_vi;
1267         }
1268     }
1269 }
1270
1271 /**
1272  * Calculate 3D coordinates on sphere for corresponding frame position in equirectangular format.
1273  *
1274  * @param s filter context
1275  * @param i horizontal position on frame [0, height)
1276  * @param j vertical position on frame [0, width)
1277  * @param width frame width
1278  * @param height frame height
1279  * @param vec coordinates on sphere
1280  */
1281 static void equirect_to_xyz(const V360Context *s,
1282                             int i, int j, int width, int height,
1283                             float *vec)
1284 {
1285     const float phi   = ((2.f * i) / width  - 1.f) * M_PI;
1286     const float theta = ((2.f * j) / height - 1.f) * M_PI_2;
1287
1288     const float sin_phi   = sinf(phi);
1289     const float cos_phi   = cosf(phi);
1290     const float sin_theta = sinf(theta);
1291     const float cos_theta = cosf(theta);
1292
1293     vec[0] =  cos_theta * sin_phi;
1294     vec[1] = -sin_theta;
1295     vec[2] = -cos_theta * cos_phi;
1296 }
1297
1298 /**
1299  * Calculate frame position in equirectangular format for corresponding 3D coordinates on sphere.
1300  *
1301  * @param s filter context
1302  * @param vec coordinates on sphere
1303  * @param width frame width
1304  * @param height frame height
1305  * @param us horizontal coordinates for interpolation window
1306  * @param vs vertical coordinates for interpolation window
1307  * @param du horizontal relative coordinate
1308  * @param dv vertical relative coordinate
1309  */
1310 static void xyz_to_equirect(const V360Context *s,
1311                             const float *vec, int width, int height,
1312                             uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1313 {
1314     const float phi   = atan2f(vec[0], -vec[2]);
1315     const float theta = asinf(-vec[1]);
1316     float uf, vf;
1317     int ui, vi;
1318     int i, j;
1319
1320     uf = (phi   / M_PI   + 1.f) * width  / 2.f;
1321     vf = (theta / M_PI_2 + 1.f) * height / 2.f;
1322     ui = floorf(uf);
1323     vi = floorf(vf);
1324
1325     *du = uf - ui;
1326     *dv = vf - vi;
1327
1328     for (i = -1; i < 3; i++) {
1329         for (j = -1; j < 3; j++) {
1330             us[i + 1][j + 1] = mod(ui + j, width);
1331             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1332         }
1333     }
1334 }
1335
1336 /**
1337  * Prepare data for processing equi-angular cubemap input format.
1338  *
1339  * @param ctx filter context
1340
1341  * @return error code
1342  */
1343 static int prepare_eac_in(AVFilterContext *ctx)
1344 {
1345     V360Context *s = ctx->priv;
1346
1347     s->in_cubemap_face_order[RIGHT] = TOP_RIGHT;
1348     s->in_cubemap_face_order[LEFT]  = TOP_LEFT;
1349     s->in_cubemap_face_order[UP]    = BOTTOM_RIGHT;
1350     s->in_cubemap_face_order[DOWN]  = BOTTOM_LEFT;
1351     s->in_cubemap_face_order[FRONT] = TOP_MIDDLE;
1352     s->in_cubemap_face_order[BACK]  = BOTTOM_MIDDLE;
1353
1354     s->in_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1355     s->in_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1356     s->in_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1357     s->in_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1358     s->in_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1359     s->in_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1360
1361     return 0;
1362 }
1363
1364 /**
1365  * Prepare data for processing equi-angular cubemap output format.
1366  *
1367  * @param ctx filter context
1368  *
1369  * @return error code
1370  */
1371 static int prepare_eac_out(AVFilterContext *ctx)
1372 {
1373     V360Context *s = ctx->priv;
1374
1375     s->out_cubemap_direction_order[TOP_LEFT]      = LEFT;
1376     s->out_cubemap_direction_order[TOP_MIDDLE]    = FRONT;
1377     s->out_cubemap_direction_order[TOP_RIGHT]     = RIGHT;
1378     s->out_cubemap_direction_order[BOTTOM_LEFT]   = DOWN;
1379     s->out_cubemap_direction_order[BOTTOM_MIDDLE] = BACK;
1380     s->out_cubemap_direction_order[BOTTOM_RIGHT]  = UP;
1381
1382     s->out_cubemap_face_rotation[TOP_LEFT]      = ROT_0;
1383     s->out_cubemap_face_rotation[TOP_MIDDLE]    = ROT_0;
1384     s->out_cubemap_face_rotation[TOP_RIGHT]     = ROT_0;
1385     s->out_cubemap_face_rotation[BOTTOM_LEFT]   = ROT_270;
1386     s->out_cubemap_face_rotation[BOTTOM_MIDDLE] = ROT_90;
1387     s->out_cubemap_face_rotation[BOTTOM_RIGHT]  = ROT_270;
1388
1389     return 0;
1390 }
1391
1392 /**
1393  * Calculate 3D coordinates on sphere for corresponding frame position in equi-angular cubemap format.
1394  *
1395  * @param s filter context
1396  * @param i horizontal position on frame [0, height)
1397  * @param j vertical position on frame [0, width)
1398  * @param width frame width
1399  * @param height frame height
1400  * @param vec coordinates on sphere
1401  */
1402 static void eac_to_xyz(const V360Context *s,
1403                        int i, int j, int width, int height,
1404                        float *vec)
1405 {
1406     const float pixel_pad = 2;
1407     const float u_pad = pixel_pad / width;
1408     const float v_pad = pixel_pad / height;
1409
1410     int u_face, v_face, face;
1411
1412     float l_x, l_y, l_z;
1413     float norm;
1414
1415     float uf = (float)i / width;
1416     float vf = (float)j / height;
1417
1418     // EAC has 2-pixel padding on faces except between faces on the same row
1419     // Padding pixels seems not to be stretched with tangent as regular pixels
1420     // Formulas below approximate original padding as close as I could get experimentally
1421
1422     // Horizontal padding
1423     uf = 3.f * (uf - u_pad) / (1.f - 2.f * u_pad);
1424     if (uf < 0.f) {
1425         u_face = 0;
1426         uf -= 0.5f;
1427     } else if (uf >= 3.f) {
1428         u_face = 2;
1429         uf -= 2.5f;
1430     } else {
1431         u_face = floorf(uf);
1432         uf = fmodf(uf, 1.f) - 0.5f;
1433     }
1434
1435     // Vertical padding
1436     v_face = floorf(vf * 2.f);
1437     vf = (vf - v_pad - 0.5f * v_face) / (0.5f - 2.f * v_pad) - 0.5f;
1438
1439     if (uf >= -0.5f && uf < 0.5f) {
1440         uf = tanf(M_PI_2 * uf);
1441     } else {
1442         uf = 2.f * uf;
1443     }
1444     if (vf >= -0.5f && vf < 0.5f) {
1445         vf = tanf(M_PI_2 * vf);
1446     } else {
1447         vf = 2.f * vf;
1448     }
1449
1450     face = u_face + 3 * v_face;
1451
1452     switch (face) {
1453     case TOP_LEFT:
1454         l_x = -1.f;
1455         l_y = -vf;
1456         l_z = -uf;
1457         break;
1458     case TOP_MIDDLE:
1459         l_x =  uf;
1460         l_y = -vf;
1461         l_z = -1.f;
1462         break;
1463     case TOP_RIGHT:
1464         l_x =  1.f;
1465         l_y = -vf;
1466         l_z =  uf;
1467         break;
1468     case BOTTOM_LEFT:
1469         l_x = -vf;
1470         l_y = -1.f;
1471         l_z =  uf;
1472         break;
1473     case BOTTOM_MIDDLE:
1474         l_x = -vf;
1475         l_y =  uf;
1476         l_z =  1.f;
1477         break;
1478     case BOTTOM_RIGHT:
1479         l_x = -vf;
1480         l_y =  1.f;
1481         l_z = -uf;
1482         break;
1483     }
1484
1485     norm = sqrtf(l_x * l_x + l_y * l_y + l_z * l_z);
1486     vec[0] = l_x / norm;
1487     vec[1] = l_y / norm;
1488     vec[2] = l_z / norm;
1489 }
1490
1491 /**
1492  * Calculate frame position in equi-angular cubemap format for corresponding 3D coordinates on sphere.
1493  *
1494  * @param s filter context
1495  * @param vec coordinates on sphere
1496  * @param width frame width
1497  * @param height frame height
1498  * @param us horizontal coordinates for interpolation window
1499  * @param vs vertical coordinates for interpolation window
1500  * @param du horizontal relative coordinate
1501  * @param dv vertical relative coordinate
1502  */
1503 static void xyz_to_eac(const V360Context *s,
1504                        const float *vec, int width, int height,
1505                        uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1506 {
1507     const float pixel_pad = 2;
1508     const float u_pad = pixel_pad / width;
1509     const float v_pad = pixel_pad / height;
1510
1511     float uf, vf;
1512     int ui, vi;
1513     int i, j;
1514     int direction, face;
1515     int u_face, v_face;
1516
1517     xyz_to_cube(s, vec, &uf, &vf, &direction);
1518
1519     face = s->in_cubemap_face_order[direction];
1520     u_face = face % 3;
1521     v_face = face / 3;
1522
1523     uf = M_2_PI * atanf(uf) + 0.5f;
1524     vf = M_2_PI * atanf(vf) + 0.5f;
1525
1526     // These formulas are inversed from eac_to_xyz ones
1527     uf = (uf + u_face) * (1.f - 2.f * u_pad) / 3.f + u_pad;
1528     vf = vf * (0.5f - 2.f * v_pad) + v_pad + 0.5f * v_face;
1529
1530     uf *= width;
1531     vf *= height;
1532
1533     ui = floorf(uf);
1534     vi = floorf(vf);
1535
1536     *du = uf - ui;
1537     *dv = vf - vi;
1538
1539     for (i = -1; i < 3; i++) {
1540         for (j = -1; j < 3; j++) {
1541             us[i + 1][j + 1] = av_clip(ui + j, 0, width  - 1);
1542             vs[i + 1][j + 1] = av_clip(vi + i, 0, height - 1);
1543         }
1544     }
1545 }
1546
1547 /**
1548  * Prepare data for processing flat output format.
1549  *
1550  * @param ctx filter context
1551  *
1552  * @return error code
1553  */
1554 static int prepare_flat_out(AVFilterContext *ctx)
1555 {
1556     V360Context *s = ctx->priv;
1557
1558     const float h_angle = 0.5f * s->h_fov * M_PI / 180.f;
1559     const float v_angle = 0.5f * s->v_fov * M_PI / 180.f;
1560
1561     const float sin_phi   = sinf(h_angle);
1562     const float cos_phi   = cosf(h_angle);
1563     const float sin_theta = sinf(v_angle);
1564     const float cos_theta = cosf(v_angle);
1565
1566     s->flat_range[0] =  cos_theta * sin_phi;
1567     s->flat_range[1] =  sin_theta;
1568     s->flat_range[2] = -cos_theta * cos_phi;
1569
1570     return 0;
1571 }
1572
1573 /**
1574  * Calculate 3D coordinates on sphere for corresponding frame position in flat format.
1575  *
1576  * @param s filter context
1577  * @param i horizontal position on frame [0, height)
1578  * @param j vertical position on frame [0, width)
1579  * @param width frame width
1580  * @param height frame height
1581  * @param vec coordinates on sphere
1582  */
1583 static void flat_to_xyz(const V360Context *s,
1584                         int i, int j, int width, int height,
1585                         float *vec)
1586 {
1587     const float l_x =  s->flat_range[0] * (2.f * i / width  - 1.f);
1588     const float l_y = -s->flat_range[1] * (2.f * j / height - 1.f);
1589     const float l_z =  s->flat_range[2];
1590
1591     const float norm = sqrtf(l_x * l_x + l_y * l_y + l_z * l_z);
1592
1593     vec[0] = l_x / norm;
1594     vec[1] = l_y / norm;
1595     vec[2] = l_z / norm;
1596 }
1597
1598 /**
1599  * Calculate frame position in dual fisheye format for corresponding 3D coordinates on sphere.
1600  *
1601  * @param s filter context
1602  * @param vec coordinates on sphere
1603  * @param width frame width
1604  * @param height frame height
1605  * @param us horizontal coordinates for interpolation window
1606  * @param vs vertical coordinates for interpolation window
1607  * @param du horizontal relative coordinate
1608  * @param dv vertical relative coordinate
1609  */
1610 static void xyz_to_dfisheye(const V360Context *s,
1611                             const float *vec, int width, int height,
1612                             uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv)
1613 {
1614     const float scale = 1.f - s->in_pad;
1615
1616     const float ew = width / 2.f;
1617     const float eh = height;
1618
1619     const float phi   = atan2f(-vec[1], -vec[0]);
1620     const float theta = acosf(fabsf(vec[2])) / M_PI;
1621
1622     float uf = (theta * cosf(phi) * scale + 0.5f) * ew;
1623     float vf = (theta * sinf(phi) * scale + 0.5f) * eh;
1624
1625     int ui, vi;
1626     int u_shift;
1627     int i, j;
1628
1629     if (vec[2] >= 0) {
1630         u_shift = 0;
1631     } else {
1632         u_shift = ceilf(ew);
1633         uf = ew - uf;
1634     }
1635
1636     ui = floorf(uf);
1637     vi = floorf(vf);
1638
1639     *du = uf - ui;
1640     *dv = vf - vi;
1641
1642     for (i = -1; i < 3; i++) {
1643         for (j = -1; j < 3; j++) {
1644             us[i + 1][j + 1] = av_clip(u_shift + ui + j, 0, width  - 1);
1645             vs[i + 1][j + 1] = av_clip(          vi + i, 0, height - 1);
1646         }
1647     }
1648 }
1649
1650 /**
1651  * Calculate rotation matrix for yaw/pitch/roll angles.
1652  */
1653 static inline void calculate_rotation_matrix(float yaw, float pitch, float roll,
1654                                              float rot_mat[3][3])
1655 {
1656     const float yaw_rad   = yaw   * M_PI / 180.f;
1657     const float pitch_rad = pitch * M_PI / 180.f;
1658     const float roll_rad  = roll  * M_PI / 180.f;
1659
1660     const float sin_yaw   = sinf(-yaw_rad);
1661     const float cos_yaw   = cosf(-yaw_rad);
1662     const float sin_pitch = sinf(pitch_rad);
1663     const float cos_pitch = cosf(pitch_rad);
1664     const float sin_roll  = sinf(roll_rad);
1665     const float cos_roll  = cosf(roll_rad);
1666
1667     rot_mat[0][0] = sin_yaw * sin_pitch * sin_roll + cos_yaw * cos_roll;
1668     rot_mat[0][1] = sin_yaw * sin_pitch * cos_roll - cos_yaw * sin_roll;
1669     rot_mat[0][2] = sin_yaw * cos_pitch;
1670
1671     rot_mat[1][0] = cos_pitch * sin_roll;
1672     rot_mat[1][1] = cos_pitch * cos_roll;
1673     rot_mat[1][2] = -sin_pitch;
1674
1675     rot_mat[2][0] = cos_yaw * sin_pitch * sin_roll - sin_yaw * cos_roll;
1676     rot_mat[2][1] = cos_yaw * sin_pitch * cos_roll + sin_yaw * sin_roll;
1677     rot_mat[2][2] = cos_yaw * cos_pitch;
1678 }
1679
1680 /**
1681  * Rotate vector with given rotation matrix.
1682  *
1683  * @param rot_mat rotation matrix
1684  * @param vec vector
1685  */
1686 static inline void rotate(const float rot_mat[3][3],
1687                           float *vec)
1688 {
1689     const float x_tmp = vec[0] * rot_mat[0][0] + vec[1] * rot_mat[0][1] + vec[2] * rot_mat[0][2];
1690     const float y_tmp = vec[0] * rot_mat[1][0] + vec[1] * rot_mat[1][1] + vec[2] * rot_mat[1][2];
1691     const float z_tmp = vec[0] * rot_mat[2][0] + vec[1] * rot_mat[2][1] + vec[2] * rot_mat[2][2];
1692
1693     vec[0] = x_tmp;
1694     vec[1] = y_tmp;
1695     vec[2] = z_tmp;
1696 }
1697
1698 static inline void set_mirror_modifier(int h_flip, int v_flip, int d_flip,
1699                                        float *modifier)
1700 {
1701     modifier[0] = h_flip ? -1.f : 1.f;
1702     modifier[1] = v_flip ? -1.f : 1.f;
1703     modifier[2] = d_flip ? -1.f : 1.f;
1704 }
1705
1706 static inline void mirror(const float *modifier,
1707                           float *vec)
1708 {
1709     vec[0] *= modifier[0];
1710     vec[1] *= modifier[1];
1711     vec[2] *= modifier[2];
1712 }
1713
1714 static int config_output(AVFilterLink *outlink)
1715 {
1716     AVFilterContext *ctx = outlink->src;
1717     AVFilterLink *inlink = ctx->inputs[0];
1718     V360Context *s = ctx->priv;
1719     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1720     const int depth = desc->comp[0].depth;
1721     float remap_data_size = 0.f;
1722     int sizeof_remap;
1723     int err;
1724     int p, h, w;
1725     float hf, wf;
1726     float mirror_modifier[3];
1727     void (*in_transform)(const V360Context *s,
1728                          const float *vec, int width, int height,
1729                          uint16_t us[4][4], uint16_t vs[4][4], float *du, float *dv);
1730     void (*out_transform)(const V360Context *s,
1731                           int i, int j, int width, int height,
1732                           float *vec);
1733     void (*calculate_kernel)(float du, float dv, int shift, const XYRemap4 *r_tmp, void *r);
1734     float rot_mat[3][3];
1735
1736     switch (s->interp) {
1737     case NEAREST:
1738         calculate_kernel = nearest_kernel;
1739         s->remap_slice = depth <= 8 ? remap1_8bit_slice : remap1_16bit_slice;
1740         sizeof_remap = sizeof(XYRemap1);
1741         break;
1742     case BILINEAR:
1743         calculate_kernel = bilinear_kernel;
1744         s->remap_slice = depth <= 8 ? remap2_8bit_slice : remap2_16bit_slice;
1745         sizeof_remap = sizeof(XYRemap2);
1746         break;
1747     case BICUBIC:
1748         calculate_kernel = bicubic_kernel;
1749         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
1750         sizeof_remap = sizeof(XYRemap4);
1751         break;
1752     case LANCZOS:
1753         calculate_kernel = lanczos_kernel;
1754         s->remap_slice = depth <= 8 ? remap4_8bit_slice : remap4_16bit_slice;
1755         sizeof_remap = sizeof(XYRemap4);
1756         break;
1757     }
1758
1759     switch (s->in) {
1760     case EQUIRECTANGULAR:
1761         in_transform = xyz_to_equirect;
1762         err = 0;
1763         wf = inlink->w;
1764         hf = inlink->h;
1765         break;
1766     case CUBEMAP_3_2:
1767         in_transform = xyz_to_cube3x2;
1768         err = prepare_cube_in(ctx);
1769         wf = inlink->w / 3.f * 4.f;
1770         hf = inlink->h;
1771         break;
1772     case CUBEMAP_6_1:
1773         in_transform = xyz_to_cube6x1;
1774         err = prepare_cube_in(ctx);
1775         wf = inlink->w / 3.f * 2.f;
1776         hf = inlink->h * 2.f;
1777         break;
1778     case EQUIANGULAR:
1779         in_transform = xyz_to_eac;
1780         err = prepare_eac_in(ctx);
1781         wf = inlink->w;
1782         hf = inlink->h / 9.f * 8.f;
1783         break;
1784     case FLAT:
1785         av_log(ctx, AV_LOG_ERROR, "Flat format is not accepted as input.\n");
1786         return AVERROR(EINVAL);
1787     case DUAL_FISHEYE:
1788         in_transform = xyz_to_dfisheye;
1789         err = 0;
1790         wf = inlink->w;
1791         hf = inlink->h;
1792         break;
1793     default:
1794         av_log(ctx, AV_LOG_ERROR, "Specified input format is not handled.\n");
1795         return AVERROR_BUG;
1796     }
1797
1798     if (err != 0) {
1799         return err;
1800     }
1801
1802     switch (s->out) {
1803     case EQUIRECTANGULAR:
1804         out_transform = equirect_to_xyz;
1805         err = 0;
1806         w = roundf(wf);
1807         h = roundf(hf);
1808         break;
1809     case CUBEMAP_3_2:
1810         out_transform = cube3x2_to_xyz;
1811         err = prepare_cube_out(ctx);
1812         w = roundf(wf / 4.f * 3.f);
1813         h = roundf(hf);
1814         break;
1815     case CUBEMAP_6_1:
1816         out_transform = cube6x1_to_xyz;
1817         err = prepare_cube_out(ctx);
1818         w = roundf(wf / 2.f * 3.f);
1819         h = roundf(hf / 2.f);
1820         break;
1821     case EQUIANGULAR:
1822         out_transform = eac_to_xyz;
1823         err = prepare_eac_out(ctx);
1824         w = roundf(wf);
1825         h = roundf(hf / 8.f * 9.f);
1826         break;
1827     case FLAT:
1828         out_transform = flat_to_xyz;
1829         err = prepare_flat_out(ctx);
1830         w = roundf(wf * s->flat_range[0] / s->flat_range[1] / 2.f);
1831         h = roundf(hf);
1832         break;
1833     case DUAL_FISHEYE:
1834         av_log(ctx, AV_LOG_ERROR, "Dual fisheye format is not accepted as output.\n");
1835         return AVERROR(EINVAL);
1836     default:
1837         av_log(ctx, AV_LOG_ERROR, "Specified output format is not handled.\n");
1838         return AVERROR_BUG;
1839     }
1840
1841     if (err != 0) {
1842         return err;
1843     }
1844
1845     // Override resolution with user values if specified
1846     if (s->width > 0 && s->height > 0) {
1847         w = s->width;
1848         h = s->height;
1849     } else if (s->width > 0 || s->height > 0) {
1850         av_log(ctx, AV_LOG_ERROR, "Both width and height values should be specified.\n");
1851         return AVERROR(EINVAL);
1852     }
1853
1854     s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(h, desc->log2_chroma_h);
1855     s->planeheight[0] = s->planeheight[3] = h;
1856     s->planewidth[1]  = s->planewidth[2] = FF_CEIL_RSHIFT(w, desc->log2_chroma_w);
1857     s->planewidth[0]  = s->planewidth[3] = w;
1858
1859     outlink->h = h;
1860     outlink->w = w;
1861
1862     s->inplaneheight[1] = s->inplaneheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
1863     s->inplaneheight[0] = s->inplaneheight[3] = inlink->h;
1864     s->inplanewidth[1]  = s->inplanewidth[2]  = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
1865     s->inplanewidth[0]  = s->inplanewidth[3]  = inlink->w;
1866     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
1867
1868     for (p = 0; p < s->nb_planes; p++) {
1869         remap_data_size += (float)s->planewidth[p] * s->planeheight[p] * sizeof_remap;
1870     }
1871
1872     for (p = 0; p < s->nb_planes; p++) {
1873         s->remap[p] = av_calloc(s->planewidth[p] * s->planeheight[p], sizeof_remap);
1874         if (!s->remap[p]) {
1875             av_log(ctx, AV_LOG_ERROR,
1876                    "Not enough memory to allocate remap data. Need at least %.3f GiB.\n",
1877                    remap_data_size / (1024 * 1024 * 1024));
1878             return AVERROR(ENOMEM);
1879         }
1880     }
1881
1882     calculate_rotation_matrix(s->yaw, s->pitch, s->roll, rot_mat);
1883     set_mirror_modifier(s->h_flip, s->v_flip, s->d_flip, mirror_modifier);
1884
1885     // Calculate remap data
1886     for (p = 0; p < s->nb_planes; p++) {
1887         const int width = s->planewidth[p];
1888         const int height = s->planeheight[p];
1889         const int in_width = s->inplanewidth[p];
1890         const int in_height = s->inplaneheight[p];
1891         void *r = s->remap[p];
1892         float du, dv;
1893         float vec[3];
1894         XYRemap4 r_tmp;
1895         int i, j;
1896
1897         for (i = 0; i < width; i++) {
1898             for (j = 0; j < height; j++) {
1899                 out_transform(s, i, j, width, height, vec);
1900                 rotate(rot_mat, vec);
1901                 mirror(mirror_modifier, vec);
1902                 in_transform(s, vec, in_width, in_height, r_tmp.u, r_tmp.v, &du, &dv);
1903                 calculate_kernel(du, dv, j * width + i, &r_tmp, r);
1904             }
1905         }
1906     }
1907
1908     return 0;
1909 }
1910
1911 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
1912 {
1913     AVFilterContext *ctx = inlink->dst;
1914     AVFilterLink *outlink = ctx->outputs[0];
1915     V360Context *s = ctx->priv;
1916     AVFrame *out;
1917     ThreadData td;
1918
1919     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1920     if (!out) {
1921         av_frame_free(&in);
1922         return AVERROR(ENOMEM);
1923     }
1924     av_frame_copy_props(out, in);
1925
1926     td.s = s;
1927     td.in = in;
1928     td.out = out;
1929     td.nb_planes = s->nb_planes;
1930
1931     ctx->internal->execute(ctx, s->remap_slice, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
1932
1933     av_frame_free(&in);
1934     return ff_filter_frame(outlink, out);
1935 }
1936
1937 static av_cold void uninit(AVFilterContext *ctx)
1938 {
1939     V360Context *s = ctx->priv;
1940     int p;
1941
1942     for (p = 0; p < s->nb_planes; p++)
1943         av_freep(&s->remap[p]);
1944 }
1945
1946 static const AVFilterPad inputs[] = {
1947     {
1948         .name         = "default",
1949         .type         = AVMEDIA_TYPE_VIDEO,
1950         .filter_frame = filter_frame,
1951     },
1952     { NULL }
1953 };
1954
1955 static const AVFilterPad outputs[] = {
1956     {
1957         .name         = "default",
1958         .type         = AVMEDIA_TYPE_VIDEO,
1959         .config_props = config_output,
1960     },
1961     { NULL }
1962 };
1963
1964 AVFilter ff_vf_v360 = {
1965     .name          = "v360",
1966     .description   = NULL_IF_CONFIG_SMALL("Convert 360 projection of video."),
1967     .priv_size     = sizeof(V360Context),
1968     .uninit        = uninit,
1969     .query_formats = query_formats,
1970     .inputs        = inputs,
1971     .outputs       = outputs,
1972     .priv_class    = &v360_class,
1973     .flags         = AVFILTER_FLAG_SLICE_THREADS,
1974 };