aboutsummaryrefslogtreecommitdiffstats
path: root/utils/sofa-info.cpp
blob: 32bef938cbb183e3a25f0d08849c7e4ef87a5323 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
 * SOFA info utility for inspecting SOFA file metrics and determining HRTF
 * utility compatible layouts.
 *
 * Copyright (C) 2018-2019  Christopher Fitzgerald
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Or visit:  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 */

#include <stdio.h>

#include <cmath>
#include <memory>
#include <vector>

#include <mysofa.h>

#include "win_main_utf8.h"


using uint = unsigned int;

struct MySofaDeleter {
    void operator()(MYSOFA_HRTF *sofa) { mysofa_free(sofa); }
};
using MySofaHrtfPtr = std::unique_ptr<MYSOFA_HRTF,MySofaDeleter>;

// Per-field measurement info.
struct HrirFdT {
    float mDistance{0.0f};
    uint mEvCount{0u};
    uint mEvStart{0u};
    std::vector<uint> mAzCounts;
};

static const char *SofaErrorStr(int err)
{
    switch(err)
    {
    case MYSOFA_OK: return "OK";
    case MYSOFA_INVALID_FORMAT: return "Invalid format";
    case MYSOFA_UNSUPPORTED_FORMAT: return "Unsupported format";
    case MYSOFA_INTERNAL_ERROR: return "Internal error";
    case MYSOFA_NO_MEMORY: return "Out of memory";
    case MYSOFA_READ_ERROR: return "Read error";
    }
    return "Unknown";
}

static void PrintSofaAttributes(const char *prefix, struct MYSOFA_ATTRIBUTE *attribute)
{
    while(attribute)
    {
        fprintf(stdout, "%s.%s: %s\n", prefix, attribute->name, attribute->value);
        attribute = attribute->next;
    }
}

static void PrintSofaArray(const char *prefix, struct MYSOFA_ARRAY *array)
{
    PrintSofaAttributes(prefix, array->attributes);

    for(uint i{0u};i < array->elements;i++)
        fprintf(stdout, "%s[%u]: %.6f\n", prefix, i, array->values[i]);
}

/* Produces a sorted array of unique elements from a particular axis of the
 * triplets array.  The filters are used to focus on particular coordinates
 * of other axes as necessary.  The epsilons are used to constrain the
 * equality of unique elements.
 */
static uint GetUniquelySortedElems(const uint m, const float *triplets, const uint axis,
                                   const float *const (&filters)[3], const float (&epsilons)[3],
                                   float *elems)
{
    uint count{0u};
    for(uint i{0u};i < 3*m;i += 3)
    {
        float elem = triplets[i + axis];

        uint j;
        for(j = 0;j < 3;j++)
        {
            if(filters[j] && std::fabs(triplets[i + j] - *filters[j]) > epsilons[j])
                break;
        }
        if(j < 3)
            continue;

        for(j = 0;j < count;j++)
        {
            const float delta{elem - elems[j]};

            if(delta > epsilons[axis])
                continue;

            if(delta >= -epsilons[axis])
                break;

            for(uint k{count};k > j;k--)
                elems[k] = elems[k - 1];

            elems[j] = elem;
            count++;
            break;
        }

        if(j >= count)
            elems[count++] = elem;
    }

    return count;
}

/* Given a list of elements, this will produce the smallest step size that
 * can uniformly cover a fair portion of the list.  Ideally this will be over
 * half, but in degenerate cases this can fall to a minimum of 5 (the lower
 * limit on elevations necessary to build a layout).
 */
static float GetUniformStepSize(const float epsilon, const uint m, const float *elems)
{
    std::vector<float> steps(m, 0.0f);
    std::vector<uint> counts(m, 0u);
    uint count{0u};

    for(uint stride{1u};stride < m/2;stride++)
    {
        for(uint i{0u};i < m-stride;i++)
        {
            const float step{elems[i + stride] - elems[i]};

            uint j;
            for(j = 0;j < count;j++)
            {
                if(std::fabs(step - steps[j]) < epsilon)
                {
                    counts[j]++;
                    break;
                }
            }

            if(j >= count)
            {
                steps[j] = step;
                counts[j] = 1;
                count++;
            }
        }

        for(uint i{1u};i < count;i++)
        {
            if(counts[i] > counts[0])
            {
                steps[0] = steps[i];
                counts[0] = counts[i];
            }
        }

        count = 1;

        if(counts[0] > m/2)
            return steps[0];
    }

    if(counts[0] > 5)
        return steps[0];
    return 0.0f;
}

/* Attempts to produce a compatible layout.  Most data sets tend to be
 * uniform and have the same major axis as used by OpenAL Soft's HRTF model.
 * This will remove outliers and produce a maximally dense layout when
 * possible.  Those sets that contain purely random measurements or use
 * different major axes will fail.
 */
static void PrintCompatibleLayout(const uint m, const float *xyzs)
{
    std::vector<float> aers(3*m, 0.0f);
    std::vector<float> elems(m, 0.0f);

    fprintf(stdout, "\n");

    for(uint i{0u};i < 3*m;i += 3)
    {
        aers[i] = xyzs[i];
        aers[i + 1] = xyzs[i + 1];
        aers[i + 2] = xyzs[i + 2];
        mysofa_c2s(&aers[i]);
    }

    uint fdCount{GetUniquelySortedElems(m, aers.data(), 2, { nullptr, nullptr, nullptr }, { 0.1f, 0.1f, 0.001f }, elems.data())};
    if(fdCount > (m / 3))
    {
        fprintf(stdout, "Incompatible layout (inumerable radii).\n");
        return;
    }

    std::vector<HrirFdT> fds(fdCount);
    for(uint fi{0u};fi < fdCount;fi++)
        fds[fi].mDistance = elems[fi];

    for(uint fi{0u};fi < fdCount;fi++)
    {
        float dist{fds[fi].mDistance};
        uint evCount{GetUniquelySortedElems(m, aers.data(), 1, { nullptr, nullptr, &dist }, { 0.1f, 0.1f, 0.001f }, elems.data())};

        if(evCount > (m / 3))
        {
            fprintf(stdout, "Incompatible layout (innumerable elevations).\n");
            return;
        }

        float step{GetUniformStepSize(0.1f, evCount, elems.data())};
        if(step <= 0.0f)
        {
            fprintf(stdout, "Incompatible layout (non-uniform elevations).\n");
            return;
        }

        uint evStart{0u};
        for(uint ei{0u};ei < evCount;ei++)
        {
            float ev{90.0f + elems[ei]};
            float eif{std::round(ev / step)};
            const uint ev_start{static_cast<uint>(eif)};

            if(std::fabs(eif - static_cast<float>(ev_start)) < (0.1f/step))
            {
                evStart = ev_start;
                break;
            }
        }

        evCount = static_cast<uint>(std::round(180.0f / step)) + 1;
        if(evCount < 5)
        {
            fprintf(stdout, "Incompatible layout (too few uniform elevations).\n");
            return;
        }

        fds[fi].mEvCount = evCount;
        fds[fi].mEvStart = evStart;
        fds[fi].mAzCounts.resize(evCount);
        auto &azCounts = fds[fi].mAzCounts;

        for(uint ei{evStart};ei < evCount;ei++)
        {
            float ev{-90.0f + static_cast<float>(ei)*180.0f/static_cast<float>(evCount - 1)};
            uint azCount{GetUniquelySortedElems(m, aers.data(), 0, { nullptr, &ev, &dist }, { 0.1f, 0.1f, 0.001f }, elems.data())};

            if(azCount > (m / 3))
            {
                fprintf(stdout, "Incompatible layout (innumerable azimuths).\n");
                return;
            }

            if(ei > 0 && ei < (evCount - 1))
            {
                step = GetUniformStepSize(0.1f, azCount, elems.data());
                if(step <= 0.0f)
                {
                    fprintf(stdout, "Incompatible layout (non-uniform azimuths).\n");
                    return;
                }

                azCounts[ei] = static_cast<uint>(std::round(360.0f / step));
            }
            else if(azCount != 1)
            {
                fprintf(stdout, "Incompatible layout (non-singular poles).\n");
                return;
            }
            else
            {
                azCounts[ei] = 1;
            }
        }

        for(uint ei{0u};ei < evStart;ei++)
            azCounts[ei] = azCounts[evCount - ei - 1];
    }

    fprintf(stdout, "Compatible Layout:\n\ndistance = %.3f", fds[0].mDistance);

    for(uint fi{1u};fi < fdCount;fi++)
        fprintf(stdout, ", %.3f", fds[fi].mDistance);

    fprintf(stdout, "\nazimuths = ");
    for(uint fi{0u};fi < fdCount;fi++)
    {
        for(uint ei{0u};ei < fds[fi].mEvCount;ei++)
            fprintf(stdout, "%d%s", fds[fi].mAzCounts[ei],
                (ei < (fds[fi].mEvCount - 1)) ? ", " :
                (fi < (fdCount - 1)) ? ";\n           " : "\n");
    }
}

// Load and inspect the given SOFA file.
static void SofaInfo(const char *filename)
{
    int err;
    MySofaHrtfPtr sofa{mysofa_load(filename, &err)};
    if(!sofa)
    {
        fprintf(stdout, "Error: Could not load source file '%s'.\n", filename);
        return;
    }

    /* NOTE: Some valid SOFA files are failing this check. */
    err = mysofa_check(sofa.get());
    if(err != MYSOFA_OK)
        fprintf(stdout, "Warning: Supposedly malformed source file '%s' (%s).\n", filename,
            SofaErrorStr(err));

    mysofa_tocartesian(sofa.get());

    PrintSofaAttributes("Info", sofa->attributes);

    fprintf(stdout, "Measurements: %u\n", sofa->M);
    fprintf(stdout, "Receivers: %u\n", sofa->R);
    fprintf(stdout, "Emitters: %u\n", sofa->E);
    fprintf(stdout, "Samples: %u\n", sofa->N);

    PrintSofaArray("SampleRate", &sofa->DataSamplingRate);
    PrintSofaArray("DataDelay", &sofa->DataDelay);

    PrintCompatibleLayout(sofa->M, sofa->SourcePosition.values);
}

int main(int argc, char *argv[])
{
    GET_UNICODE_ARGS(&argc, &argv);

    if(argc != 2)
    {
        fprintf(stdout, "Usage: %s <sofa-file>\n", argv[0]);
        return 0;
    }

    SofaInfo(argv[1]);

    return 0;
}