2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2018-2019 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
40 #include "polyphase_resampler.h"
41 #include "sofa-support.h"
46 using uint
= unsigned int;
48 /* Attempts to produce a compatible layout. Most data sets tend to be
49 * uniform and have the same major axis as used by OpenAL Soft's HRTF model.
50 * This will remove outliers and produce a maximally dense layout when
51 * possible. Those sets that contain purely random measurements or use
52 * different major axes will fail.
54 static bool PrepareLayout(const uint m
, const float *xyzs
, HrirDataT
*hData
)
56 fprintf(stdout
, "Detecting compatible layout...\n");
58 auto fds
= GetCompatibleLayout(m
, xyzs
);
59 if(fds
.size() > MAX_FD_COUNT
)
61 fprintf(stdout
, "Incompatible layout (inumerable radii).\n");
65 double distances
[MAX_FD_COUNT
]{};
66 uint evCounts
[MAX_FD_COUNT
]{};
67 auto azCounts
= std::vector
<uint
>(MAX_FD_COUNT
*MAX_EV_COUNT
, 0u);
69 uint fi
{0u}, ir_total
{0u};
70 for(const auto &field
: fds
)
72 distances
[fi
] = field
.mDistance
;
73 evCounts
[fi
] = field
.mEvCount
;
75 for(uint ei
{0u};ei
< field
.mEvStart
;ei
++)
76 azCounts
[fi
*MAX_EV_COUNT
+ ei
] = field
.mAzCounts
[field
.mEvCount
-ei
-1];
77 for(uint ei
{field
.mEvStart
};ei
< field
.mEvCount
;ei
++)
79 azCounts
[fi
*MAX_EV_COUNT
+ ei
] = field
.mAzCounts
[ei
];
80 ir_total
+= field
.mAzCounts
[ei
];
85 fprintf(stdout
, "Using %u of %u IRs.\n", ir_total
, m
);
86 return PrepareHrirData(fi
, distances
, evCounts
, azCounts
.data(), hData
) != 0;
90 bool PrepareSampleRate(MYSOFA_HRTF
*sofaHrtf
, HrirDataT
*hData
)
92 const char *srate_dim
{nullptr};
93 const char *srate_units
{nullptr};
94 MYSOFA_ARRAY
*srate_array
{&sofaHrtf
->DataSamplingRate
};
95 MYSOFA_ATTRIBUTE
*srate_attrs
{srate_array
->attributes
};
98 if(std::string
{"DIMENSION_LIST"} == srate_attrs
->name
)
102 fprintf(stderr
, "Duplicate SampleRate.DIMENSION_LIST\n");
105 srate_dim
= srate_attrs
->value
;
107 else if(std::string
{"Units"} == srate_attrs
->name
)
111 fprintf(stderr
, "Duplicate SampleRate.Units\n");
114 srate_units
= srate_attrs
->value
;
117 fprintf(stderr
, "Unexpected sample rate attribute: %s = %s\n", srate_attrs
->name
,
119 srate_attrs
= srate_attrs
->next
;
123 fprintf(stderr
, "Missing sample rate dimensions\n");
126 if(srate_dim
!= std::string
{"I"})
128 fprintf(stderr
, "Unsupported sample rate dimensions: %s\n", srate_dim
);
133 fprintf(stderr
, "Missing sample rate unit type\n");
136 if(srate_units
!= std::string
{"hertz"})
138 fprintf(stderr
, "Unsupported sample rate unit type: %s\n", srate_units
);
141 /* I dimensions guarantees 1 element, so just extract it. */
142 hData
->mIrRate
= static_cast<uint
>(srate_array
->values
[0] + 0.5f
);
143 if(hData
->mIrRate
< MIN_RATE
|| hData
->mIrRate
> MAX_RATE
)
145 fprintf(stderr
, "Sample rate out of range: %u (expected %u to %u)", hData
->mIrRate
,
152 bool PrepareDelay(MYSOFA_HRTF
*sofaHrtf
, HrirDataT
*hData
)
154 const char *delay_dim
{nullptr};
155 MYSOFA_ARRAY
*delay_array
{&sofaHrtf
->DataDelay
};
156 MYSOFA_ATTRIBUTE
*delay_attrs
{delay_array
->attributes
};
159 if(std::string
{"DIMENSION_LIST"} == delay_attrs
->name
)
163 fprintf(stderr
, "Duplicate Delay.DIMENSION_LIST\n");
166 delay_dim
= delay_attrs
->value
;
169 fprintf(stderr
, "Unexpected delay attribute: %s = %s\n", delay_attrs
->name
,
171 delay_attrs
= delay_attrs
->next
;
175 fprintf(stderr
, "Missing delay dimensions\n");
178 else if(delay_dim
!= std::string
{"I,R"})
180 fprintf(stderr
, "Unsupported delay dimensions: %s\n", delay_dim
);
183 else if(hData
->mChannelType
== CT_STEREO
)
185 /* I,R is 1xChannelCount. Makemhr currently removes any delay constant,
186 * so we can ignore this as long as it's equal.
188 if(delay_array
->values
[0] != delay_array
->values
[1])
190 fprintf(stderr
, "Mismatched delays not supported: %f, %f\n", delay_array
->values
[0],
191 delay_array
->values
[1]);
198 bool CheckIrData(MYSOFA_HRTF
*sofaHrtf
)
200 const char *ir_dim
{nullptr};
201 MYSOFA_ARRAY
*ir_array
{&sofaHrtf
->DataIR
};
202 MYSOFA_ATTRIBUTE
*ir_attrs
{ir_array
->attributes
};
205 if(std::string
{"DIMENSION_LIST"} == ir_attrs
->name
)
209 fprintf(stderr
, "Duplicate IR.DIMENSION_LIST\n");
212 ir_dim
= ir_attrs
->value
;
215 fprintf(stderr
, "Unexpected IR attribute: %s = %s\n", ir_attrs
->name
,
217 ir_attrs
= ir_attrs
->next
;
221 fprintf(stderr
, "Missing IR dimensions\n");
224 if(ir_dim
!= std::string
{"M,R,N"})
226 fprintf(stderr
, "Unsupported IR dimensions: %s\n", ir_dim
);
233 /* Calculate the onset time of a HRIR. */
234 static constexpr int OnsetRateMultiple
{10};
235 static double CalcHrirOnset(PPhaseResampler
&rs
, const uint rate
, const uint n
,
236 std::vector
<double> &upsampled
, const double *hrir
)
238 rs
.process(n
, hrir
, static_cast<uint
>(upsampled
.size()), upsampled
.data());
240 auto abs_lt
= [](const double &lhs
, const double &rhs
) -> bool
241 { return std::abs(lhs
) < std::abs(rhs
); };
242 auto iter
= std::max_element(upsampled
.cbegin(), upsampled
.cend(), abs_lt
);
243 return static_cast<double>(std::distance(upsampled
.cbegin(), iter
)) /
244 (double{OnsetRateMultiple
}*rate
);
247 /* Calculate the magnitude response of a HRIR. */
248 static void CalcHrirMagnitude(const uint points
, const uint n
, std::vector
<complex_d
> &h
,
251 auto iter
= std::copy_n(hrir
, points
, h
.begin());
252 std::fill(iter
, h
.end(), complex_d
{0.0, 0.0});
254 FftForward(n
, h
.data());
255 MagnitudeResponse(n
, h
.data(), hrir
);
258 static bool LoadResponses(MYSOFA_HRTF
*sofaHrtf
, HrirDataT
*hData
)
260 std::atomic
<uint
> loaded_count
{0u};
262 auto load_proc
= [sofaHrtf
,hData
,&loaded_count
]() -> bool
264 const uint channels
{(hData
->mChannelType
== CT_STEREO
) ? 2u : 1u};
265 hData
->mHrirsBase
.resize(channels
* hData
->mIrCount
* hData
->mIrSize
, 0.0);
266 double *hrirs
= hData
->mHrirsBase
.data();
268 for(uint si
{0u};si
< sofaHrtf
->M
;++si
)
270 loaded_count
.fetch_add(1u);
273 sofaHrtf
->SourcePosition
.values
[3*si
],
274 sofaHrtf
->SourcePosition
.values
[3*si
+ 1],
275 sofaHrtf
->SourcePosition
.values
[3*si
+ 2]
279 if(std::abs(aer
[1]) >= 89.999f
)
282 aer
[0] = std::fmod(360.0f
- aer
[0], 360.0f
);
284 auto field
= std::find_if(hData
->mFds
.cbegin(), hData
->mFds
.cend(),
285 [&aer
](const HrirFdT
&fld
) -> bool
287 double delta
= aer
[2] - fld
.mDistance
;
288 return (std::abs(delta
) < 0.001);
290 if(field
== hData
->mFds
.cend())
293 double ef
{(90.0+aer
[1]) / 180.0 * (field
->mEvCount
-1)};
294 auto ei
= static_cast<int>(std::round(ef
));
295 ef
= (ef
-ei
) * 180.0 / (field
->mEvCount
-1);
296 if(std::abs(ef
) >= 0.1) continue;
298 double af
{aer
[0] / 360.0 * field
->mEvs
[ei
].mAzCount
};
299 auto ai
= static_cast<int>(std::round(af
));
300 af
= (af
-ai
) * 360.0 / field
->mEvs
[ei
].mAzCount
;
301 ai
%= field
->mEvs
[ei
].mAzCount
;
302 if(std::abs(af
) >= 0.1) continue;
304 HrirAzT
*azd
= &field
->mEvs
[ei
].mAzs
[ai
];
305 if(azd
->mIrs
[0] != nullptr)
307 fprintf(stderr
, "\nMultiple measurements near [ a=%f, e=%f, r=%f ].\n",
308 aer
[0], aer
[1], aer
[2]);
312 for(uint ti
{0u};ti
< channels
;++ti
)
314 azd
->mIrs
[ti
] = &hrirs
[hData
->mIrSize
* (hData
->mIrCount
*ti
+ azd
->mIndex
)];
315 std::copy_n(&sofaHrtf
->DataIR
.values
[(si
*sofaHrtf
->R
+ ti
)*sofaHrtf
->N
],
316 hData
->mIrPoints
, azd
->mIrs
[ti
]);
319 /* TODO: Since some SOFA files contain minimum phase HRIRs,
320 * it would be beneficial to check for per-measurement delays
321 * (when available) to reconstruct the HRTDs.
327 std::future_status load_status
{};
328 auto load_future
= std::async(std::launch::async
, load_proc
);
330 load_status
= load_future
.wait_for(std::chrono::milliseconds
{50});
331 printf("\rLoading HRIRs... %u of %u", loaded_count
.load(), sofaHrtf
->M
);
333 } while(load_status
!= std::future_status::ready
);
335 return load_future
.get();
339 /* Calculates the frequency magnitudes of the HRIR set. Work is delegated to
340 * this struct, which runs asynchronously on one or more threads (sharing the
341 * same calculator object).
343 struct MagCalculator
{
344 const uint mFftSize
{};
345 const uint mIrPoints
{};
346 std::vector
<double*> mIrs
{};
347 std::atomic
<size_t> mCurrent
{};
348 std::atomic
<size_t> mDone
{};
352 auto htemp
= std::vector
<complex_d
>(mFftSize
);
356 /* Load the current index to process. */
357 size_t idx
{mCurrent
.load()};
359 /* If the index is at the end, we're done. */
360 if(idx
>= mIrs
.size())
362 /* Otherwise, increment the current index atomically so other
363 * threads know to go to the next one. If this call fails, the
364 * current index was just changed by another thread and the new
365 * value is loaded into idx, which we'll recheck.
367 } while(!mCurrent
.compare_exchange_weak(idx
, idx
+1, std::memory_order_relaxed
));
369 CalcHrirMagnitude(mIrPoints
, mFftSize
, htemp
, mIrs
[idx
]);
371 /* Increment the number of IRs done. */
377 bool LoadSofaFile(const char *filename
, const uint numThreads
, const uint fftSize
,
378 const uint truncSize
, const ChannelModeT chanMode
, HrirDataT
*hData
)
381 MySofaHrtfPtr sofaHrtf
{mysofa_load(filename
, &err
)};
384 fprintf(stdout
, "Error: Could not load %s: %s\n", filename
, SofaErrorStr(err
));
388 /* NOTE: Some valid SOFA files are failing this check. */
389 err
= mysofa_check(sofaHrtf
.get());
391 fprintf(stderr
, "Warning: Supposedly malformed source file '%s' (%s).\n", filename
,
394 mysofa_tocartesian(sofaHrtf
.get());
396 /* Make sure emitter and receiver counts are sane. */
399 fprintf(stderr
, "%u emitters not supported\n", sofaHrtf
->E
);
402 if(sofaHrtf
->R
> 2 || sofaHrtf
->R
< 1)
404 fprintf(stderr
, "%u receivers not supported\n", sofaHrtf
->R
);
407 /* Assume R=2 is a stereo measurement, and R=1 is mono left-ear-only. */
408 if(sofaHrtf
->R
== 2 && chanMode
== CM_AllowStereo
)
409 hData
->mChannelType
= CT_STEREO
;
411 hData
->mChannelType
= CT_MONO
;
413 /* Check and set the FFT and IR size. */
414 if(sofaHrtf
->N
> fftSize
)
416 fprintf(stderr
, "Sample points exceeds the FFT size.\n");
419 if(sofaHrtf
->N
< truncSize
)
421 fprintf(stderr
, "Sample points is below the truncation size.\n");
424 hData
->mIrPoints
= sofaHrtf
->N
;
425 hData
->mFftSize
= fftSize
;
426 hData
->mIrSize
= std::max(1u + (fftSize
/2u), sofaHrtf
->N
);
428 /* Assume a default head radius of 9cm. */
429 hData
->mRadius
= 0.09;
431 if(!PrepareSampleRate(sofaHrtf
.get(), hData
) || !PrepareDelay(sofaHrtf
.get(), hData
)
432 || !CheckIrData(sofaHrtf
.get()))
434 if(!PrepareLayout(sofaHrtf
->M
, sofaHrtf
->SourcePosition
.values
, hData
))
437 if(!LoadResponses(sofaHrtf
.get(), hData
))
441 for(uint fi
{0u};fi
< hData
->mFdCount
;fi
++)
444 for(;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
447 for(;ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
449 HrirAzT
&azd
= hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
450 if(azd
.mIrs
[0] != nullptr) break;
452 if(ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
)
455 if(ei
>= hData
->mFds
[fi
].mEvCount
)
457 fprintf(stderr
, "Missing source references [ %d, *, * ].\n", fi
);
460 hData
->mFds
[fi
].mEvStart
= ei
;
461 for(;ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
463 for(uint ai
{0u};ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
465 HrirAzT
&azd
= hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
466 if(azd
.mIrs
[0] == nullptr)
468 fprintf(stderr
, "Missing source reference [ %d, %d, %d ].\n", fi
, ei
, ai
);
476 size_t hrir_total
{0};
477 const uint channels
{(hData
->mChannelType
== CT_STEREO
) ? 2u : 1u};
478 double *hrirs
= hData
->mHrirsBase
.data();
479 for(uint fi
{0u};fi
< hData
->mFdCount
;fi
++)
481 for(uint ei
{0u};ei
< hData
->mFds
[fi
].mEvStart
;ei
++)
483 for(uint ai
{0u};ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
485 HrirAzT
&azd
= hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
486 for(uint ti
{0u};ti
< channels
;ti
++)
487 azd
.mIrs
[ti
] = &hrirs
[hData
->mIrSize
* (hData
->mIrCount
*ti
+ azd
.mIndex
)];
491 for(uint ei
{hData
->mFds
[fi
].mEvStart
};ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
492 hrir_total
+= hData
->mFds
[fi
].mEvs
[ei
].mAzCount
* channels
;
495 std::atomic
<size_t> hrir_done
{0};
496 auto onset_proc
= [hData
,channels
,&hrir_done
]() -> bool
498 /* Temporary buffer used to calculate the IR's onset. */
499 auto upsampled
= std::vector
<double>(OnsetRateMultiple
* hData
->mIrPoints
);
500 /* This resampler is used to help detect the response onset. */
502 rs
.init(hData
->mIrRate
, OnsetRateMultiple
*hData
->mIrRate
);
504 for(uint fi
{0u};fi
< hData
->mFdCount
;fi
++)
506 for(uint ei
{hData
->mFds
[fi
].mEvStart
};ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
508 for(uint ai
{0};ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
510 HrirAzT
&azd
= hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
511 for(uint ti
{0};ti
< channels
;ti
++)
513 hrir_done
.fetch_add(1u, std::memory_order_acq_rel
);
514 azd
.mDelays
[ti
] = CalcHrirOnset(rs
, hData
->mIrRate
, hData
->mIrPoints
,
515 upsampled
, azd
.mIrs
[ti
]);
523 std::future_status load_status
{};
524 auto load_future
= std::async(std::launch::async
, onset_proc
);
526 load_status
= load_future
.wait_for(std::chrono::milliseconds
{50});
527 printf("\rCalculating HRIR onsets... %zu of %zu", hrir_done
.load(), hrir_total
);
529 } while(load_status
!= std::future_status::ready
);
531 if(!load_future
.get())
534 MagCalculator calculator
{hData
->mFftSize
, hData
->mIrPoints
};
535 for(uint fi
{0u};fi
< hData
->mFdCount
;fi
++)
537 for(uint ei
{hData
->mFds
[fi
].mEvStart
};ei
< hData
->mFds
[fi
].mEvCount
;ei
++)
539 for(uint ai
{0};ai
< hData
->mFds
[fi
].mEvs
[ei
].mAzCount
;ai
++)
541 HrirAzT
&azd
= hData
->mFds
[fi
].mEvs
[ei
].mAzs
[ai
];
542 for(uint ti
{0};ti
< channels
;ti
++)
543 calculator
.mIrs
.push_back(azd
.mIrs
[ti
]);
548 std::vector
<std::thread
> thrds
;
549 thrds
.reserve(numThreads
);
550 for(size_t i
{0};i
< numThreads
;++i
)
551 thrds
.emplace_back(std::mem_fn(&MagCalculator::Worker
), &calculator
);
554 std::this_thread::sleep_for(std::chrono::milliseconds
{50});
555 count
= calculator
.mDone
.load();
557 printf("\rCalculating HRIR magnitudes... %zu of %zu", count
, calculator
.mIrs
.size());
559 } while(count
!= calculator
.mIrs
.size());
562 for(auto &thrd
: thrds
)