2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 by Chris Robinson
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
40 #include <type_traits>
47 #include "alfstream.h"
49 #include "alnumeric.h"
50 #include "aloptional.h"
52 #include "filters/splitter.h"
54 #include "math_defs.h"
55 #include "opthelpers.h"
56 #include "polyphase_resampler.h"
61 using namespace std::placeholders
;
64 std::string mDispName
;
65 std::string mFilename
;
69 std::string mFilename
;
70 std::unique_ptr
<HrtfStore
> mEntry
;
73 /* Data set limits must be the same as or more flexible than those defined in
74 * the makemhr utility.
76 #define MIN_FD_COUNT (1)
77 #define MAX_FD_COUNT (16)
79 #define MIN_FD_DISTANCE (50)
80 #define MAX_FD_DISTANCE (2500)
82 #define MIN_EV_COUNT (5)
83 #define MAX_EV_COUNT (181)
85 #define MIN_AZ_COUNT (1)
86 #define MAX_AZ_COUNT (255)
88 #define MAX_HRIR_DELAY (HRTF_HISTORY_LENGTH-1)
90 #define HRIR_DELAY_FRACBITS 2
91 #define HRIR_DELAY_FRACONE (1<<HRIR_DELAY_FRACBITS)
92 #define HRIR_DELAY_FRACHALF (HRIR_DELAY_FRACONE>>1)
94 static_assert(MAX_HRIR_DELAY
*HRIR_DELAY_FRACONE
< 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
96 constexpr ALchar magicMarker00
[8]{'M','i','n','P','H','R','0','0'};
97 constexpr ALchar magicMarker01
[8]{'M','i','n','P','H','R','0','1'};
98 constexpr ALchar magicMarker02
[8]{'M','i','n','P','H','R','0','2'};
100 /* First value for pass-through coefficients (remaining are 0), used for omni-
101 * directional sounds. */
102 constexpr ALfloat PassthruCoeff
{0.707106781187f
/*sqrt(0.5)*/};
104 std::mutex LoadedHrtfLock
;
105 al::vector
<LoadedHrtf
> LoadedHrtfs
;
107 std::mutex EnumeratedHrtfLock
;
108 al::vector
<HrtfEntry
> EnumeratedHrtfs
;
111 class databuf final
: public std::streambuf
{
112 int_type
underflow() override
113 { return traits_type::eof(); }
115 pos_type
seekoff(off_type offset
, std::ios_base::seekdir whence
, std::ios_base::openmode mode
) override
117 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
118 return traits_type::eof();
123 case std::ios_base::beg
:
124 if(offset
< 0 || offset
> egptr()-eback())
125 return traits_type::eof();
126 cur
= eback() + offset
;
129 case std::ios_base::cur
:
130 if((offset
>= 0 && offset
> egptr()-gptr()) ||
131 (offset
< 0 && -offset
> gptr()-eback()))
132 return traits_type::eof();
133 cur
= gptr() + offset
;
136 case std::ios_base::end
:
137 if(offset
> 0 || -offset
> egptr()-eback())
138 return traits_type::eof();
139 cur
= egptr() + offset
;
143 return traits_type::eof();
146 setg(eback(), cur
, egptr());
147 return cur
- eback();
150 pos_type
seekpos(pos_type pos
, std::ios_base::openmode mode
) override
152 // Simplified version of seekoff
153 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
154 return traits_type::eof();
156 if(pos
< 0 || pos
> egptr()-eback())
157 return traits_type::eof();
159 setg(eback(), eback() + static_cast<size_t>(pos
), egptr());
164 databuf(const char_type
*start_
, const char_type
*end_
) noexcept
166 setg(const_cast<char_type
*>(start_
), const_cast<char_type
*>(start_
),
167 const_cast<char_type
*>(end_
));
171 class idstream final
: public std::istream
{
175 idstream(const char *start_
, const char *end_
)
176 : std::istream
{nullptr}, mStreamBuf
{start_
, end_
}
177 { init(&mStreamBuf
); }
181 struct IdxBlend
{ ALuint idx
; float blend
; };
182 /* Calculate the elevation index given the polar elevation in radians. This
183 * will return an index between 0 and (evcount - 1).
185 IdxBlend
CalcEvIndex(ALuint evcount
, float ev
)
187 ev
= (al::MathDefs
<float>::Pi()*0.5f
+ ev
) * static_cast<float>(evcount
-1) /
188 al::MathDefs
<float>::Pi();
189 ALuint idx
{float2uint(ev
)};
191 return IdxBlend
{minu(idx
, evcount
-1), ev
-static_cast<float>(idx
)};
194 /* Calculate the azimuth index given the polar azimuth in radians. This will
195 * return an index between 0 and (azcount - 1).
197 IdxBlend
CalcAzIndex(ALuint azcount
, float az
)
199 az
= (al::MathDefs
<float>::Tau()+az
) * static_cast<float>(azcount
) /
200 al::MathDefs
<float>::Tau();
201 ALuint idx
{float2uint(az
)};
203 return IdxBlend
{idx
%azcount
, az
-static_cast<float>(idx
)};
209 /* Calculates static HRIR coefficients and delays for the given polar elevation
210 * and azimuth in radians. The coefficients are normalized.
212 void GetHrtfCoeffs(const HrtfStore
*Hrtf
, float elevation
, float azimuth
, float distance
,
213 float spread
, HrirArray
&coeffs
, ALuint (&delays
)[2])
215 const float dirfact
{1.0f
- (spread
/ al::MathDefs
<float>::Tau())};
217 const auto *field
= Hrtf
->field
;
218 const auto *field_end
= field
+ Hrtf
->fdCount
-1;
220 while(distance
< field
->distance
&& field
!= field_end
)
222 ebase
+= field
->evCount
;
226 /* Claculate the elevation indinces. */
227 const auto elev0
= CalcEvIndex(field
->evCount
, elevation
);
228 const size_t elev1_idx
{minu(elev0
.idx
+1, field
->evCount
-1)};
229 const size_t ir0offset
{Hrtf
->elev
[ebase
+ elev0
.idx
].irOffset
};
230 const size_t ir1offset
{Hrtf
->elev
[ebase
+ elev1_idx
].irOffset
};
232 /* Calculate azimuth indices. */
233 const auto az0
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
, azimuth
);
234 const auto az1
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev1_idx
].azCount
, azimuth
);
236 /* Calculate the HRIR indices to blend. */
239 ir0offset
+ ((az0
.idx
+1) % Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
),
241 ir1offset
+ ((az1
.idx
+1) % Hrtf
->elev
[ebase
+ elev1_idx
].azCount
)
244 /* Calculate bilinear blending weights, attenuated according to the
245 * directional panning factor.
247 const float blend
[4]{
248 (1.0f
-elev0
.blend
) * (1.0f
-az0
.blend
) * dirfact
,
249 (1.0f
-elev0
.blend
) * ( az0
.blend
) * dirfact
,
250 ( elev0
.blend
) * (1.0f
-az1
.blend
) * dirfact
,
251 ( elev0
.blend
) * ( az1
.blend
) * dirfact
254 /* Calculate the blended HRIR delays. */
255 float d
{Hrtf
->delays
[idx
[0]][0]*blend
[0] + Hrtf
->delays
[idx
[1]][0]*blend
[1] +
256 Hrtf
->delays
[idx
[2]][0]*blend
[2] + Hrtf
->delays
[idx
[3]][0]*blend
[3]};
257 delays
[0] = fastf2u(d
* float{1.0f
/HRIR_DELAY_FRACONE
});
258 d
= Hrtf
->delays
[idx
[0]][1]*blend
[0] + Hrtf
->delays
[idx
[1]][1]*blend
[1] +
259 Hrtf
->delays
[idx
[2]][1]*blend
[2] + Hrtf
->delays
[idx
[3]][1]*blend
[3];
260 delays
[1] = fastf2u(d
* float{1.0f
/HRIR_DELAY_FRACONE
});
262 /* Calculate the blended HRIR coefficients. */
263 float *coeffout
{al::assume_aligned
<16>(&coeffs
[0][0])};
264 coeffout
[0] = PassthruCoeff
* (1.0f
-dirfact
);
265 coeffout
[1] = PassthruCoeff
* (1.0f
-dirfact
);
266 std::fill_n(coeffout
+2, size_t{HRIR_LENGTH
-1}*2, 0.0f
);
267 for(size_t c
{0};c
< 4;c
++)
269 const float *srccoeffs
{al::assume_aligned
<16>(Hrtf
->coeffs
[idx
[c
]][0].data())};
270 const float mult
{blend
[c
]};
271 auto blend_coeffs
= [mult
](const float src
, const float coeff
) noexcept
-> float
272 { return src
*mult
+ coeff
; };
273 std::transform(srccoeffs
, srccoeffs
+ HRIR_LENGTH
*2, coeffout
, coeffout
, blend_coeffs
);
278 std::unique_ptr
<DirectHrtfState
> DirectHrtfState::Create(size_t num_chans
)
280 return std::unique_ptr
<DirectHrtfState
>{new (FamCount
{num_chans
}) DirectHrtfState
{num_chans
}};
283 void BuildBFormatHrtf(const HrtfStore
*Hrtf
, DirectHrtfState
*state
,
284 const al::span
<const AngularPoint
> AmbiPoints
, const ALfloat (*AmbiMatrix
)[MAX_AMBI_CHANNELS
],
285 const ALfloat
*AmbiOrderHFGain
)
287 using double2
= std::array
<double,2>;
288 struct ImpulseResponse
{
289 const HrirArray
&hrir
;
290 ALuint ldelay
, rdelay
;
293 /* Set this to true for dual-band HRTF processing. May require better
294 * calculation of the new IR length to deal with the head and tail
295 * generated by the HF scaling.
297 static constexpr bool DualBand
{true};
299 ALuint min_delay
{HRTF_HISTORY_LENGTH
*HRIR_DELAY_FRACONE
};
301 al::vector
<ImpulseResponse
> impres
; impres
.reserve(AmbiPoints
.size());
302 auto calc_res
= [Hrtf
,&max_delay
,&min_delay
](const AngularPoint
&pt
) -> ImpulseResponse
304 auto CalcClosestEvIndex
= [](ALuint evcount
, float ev
) -> ALuint
306 ev
= (al::MathDefs
<float>::Pi()*0.5f
+ ev
) * static_cast<float>(evcount
-1) /
307 al::MathDefs
<float>::Pi();
308 return minu(float2uint(ev
+0.5f
), evcount
-1);
310 auto CalcClosestAzIndex
= [](ALuint azcount
, float az
) -> ALuint
312 az
= (al::MathDefs
<float>::Tau()+az
) * static_cast<float>(azcount
) /
313 al::MathDefs
<float>::Tau();
314 return float2uint(az
+0.5f
) % azcount
;
317 auto &field
= Hrtf
->field
[0];
318 const size_t elevIdx
{CalcClosestEvIndex(field
.evCount
, pt
.Elev
.value
)};
319 const size_t azIdx
{CalcClosestAzIndex(Hrtf
->elev
[elevIdx
].azCount
, pt
.Azim
.value
)};
320 const size_t irOffset
{Hrtf
->elev
[elevIdx
].irOffset
+ azIdx
};
322 ImpulseResponse res
{Hrtf
->coeffs
[irOffset
],
323 Hrtf
->delays
[irOffset
][0], Hrtf
->delays
[irOffset
][1]};
325 min_delay
= minu(min_delay
, minu(res
.ldelay
, res
.rdelay
));
326 max_delay
= maxu(max_delay
, maxu(res
.ldelay
, res
.rdelay
));
330 std::transform(AmbiPoints
.begin(), AmbiPoints
.end(), std::back_inserter(impres
), calc_res
);
331 auto hrir_delay_round
= [](const ALuint d
) noexcept
-> ALuint
332 { return (d
+HRIR_DELAY_FRACHALF
) >> HRIR_DELAY_FRACBITS
; };
334 /* For dual-band processing, add a 16-sample delay to compensate for the HF
335 * scale on the minimum-phase response.
337 static constexpr ALuint base_delay
{DualBand
? 16 : 0};
338 const double xover_norm
{400.0 / Hrtf
->sampleRate
};
339 BandSplitterR
<double> splitter
{xover_norm
};
341 auto tmpres
= al::vector
<std::array
<double2
,HRIR_LENGTH
>>(state
->Coeffs
.size());
342 auto tmpflt
= al::vector
<std::array
<double,HRIR_LENGTH
*4>>(3);
343 const al::span
<double,HRIR_LENGTH
*4> tempir
{tmpflt
[2].data(), tmpflt
[2].size()};
344 for(size_t c
{0u};c
< AmbiPoints
.size();++c
)
346 const HrirArray
&hrir
{impres
[c
].hrir
};
347 const ALuint ldelay
{hrir_delay_round(impres
[c
].ldelay
-min_delay
) + base_delay
};
348 const ALuint rdelay
{hrir_delay_round(impres
[c
].rdelay
-min_delay
) + base_delay
};
350 if /*constexpr*/(!DualBand
)
352 /* For single-band decoding, apply the HF scale to the response. */
353 for(size_t i
{0u};i
< state
->Coeffs
.size();++i
)
355 const size_t order
{AmbiIndex::OrderFromChannel
[i
]};
356 const double mult
{double{AmbiOrderHFGain
[order
]} * AmbiMatrix
[c
][i
]};
357 const ALuint numirs
{HRIR_LENGTH
- maxu(ldelay
, rdelay
)};
358 ALuint lidx
{ldelay
}, ridx
{rdelay
};
359 for(ALuint j
{0};j
< numirs
;++j
)
361 tmpres
[i
][lidx
++][0] += hrir
[j
][0] * mult
;
362 tmpres
[i
][ridx
++][1] += hrir
[j
][1] * mult
;
368 /* For dual-band processing, the HRIR needs to be split into low and
369 * high frequency responses. The band-splitter alone creates frequency-
370 * dependent phase-shifts, which is not ideal. To counteract it,
371 * combine it with a backwards phase-shift.
374 /* Load the (left) HRIR backwards, into a temp buffer with padding. */
375 std::fill(tempir
.begin(), tempir
.end(), 0.0);
376 std::transform(hrir
.cbegin(), hrir
.cend(), tempir
.rbegin() + HRIR_LENGTH
*3,
377 [](const float2
&ir
) noexcept
-> double { return ir
[0]; });
379 /* Apply the all-pass on the reversed signal and reverse the resulting
380 * sample array. This produces the forward response with a backwards
381 * phase-shift (+n degrees becomes -n degrees).
383 splitter
.applyAllpass({tempir
.data(), tempir
.size()});
384 std::reverse(tempir
.begin(), tempir
.end());
386 /* Now apply the band-splitter. This applies the normal phase-shift,
387 * which cancels out with the backwards phase-shift to get the original
388 * phase on the split signal.
391 splitter
.process(tempir
, tmpflt
[0].data(), tmpflt
[1].data());
393 /* Apply left ear response with delay and HF scale. */
394 for(size_t i
{0u};i
< state
->Coeffs
.size();++i
)
396 const double mult
{AmbiMatrix
[c
][i
]};
397 const double hfgain
{AmbiOrderHFGain
[AmbiIndex::OrderFromChannel
[i
]]};
398 ALuint j
{HRIR_LENGTH
*3 - ldelay
};
399 for(ALuint lidx
{0};lidx
< HRIR_LENGTH
;++lidx
,++j
)
400 tmpres
[i
][lidx
][0] += (tmpflt
[0][j
]*hfgain
+ tmpflt
[1][j
]) * mult
;
403 /* Now run the same process on the right HRIR. */
404 std::fill(tempir
.begin(), tempir
.end(), 0.0);
405 std::transform(hrir
.cbegin(), hrir
.cend(), tempir
.rbegin() + HRIR_LENGTH
*3,
406 [](const float2
&ir
) noexcept
-> double { return ir
[1]; });
408 splitter
.applyAllpass({tempir
.data(), tempir
.size()});
409 std::reverse(tempir
.begin(), tempir
.end());
412 splitter
.process(tempir
, tmpflt
[0].data(), tmpflt
[1].data());
414 for(size_t i
{0u};i
< state
->Coeffs
.size();++i
)
416 const double mult
{AmbiMatrix
[c
][i
]};
417 const double hfgain
{AmbiOrderHFGain
[AmbiIndex::OrderFromChannel
[i
]]};
418 ALuint j
{HRIR_LENGTH
*3 - rdelay
};
419 for(ALuint ridx
{0};ridx
< HRIR_LENGTH
;++ridx
,++j
)
420 tmpres
[i
][ridx
][1] += (tmpflt
[0][j
]*hfgain
+ tmpflt
[1][j
]) * mult
;
426 for(size_t i
{0u};i
< state
->Coeffs
.size();++i
)
428 auto copy_arr
= [](const double2
&in
) noexcept
-> float2
429 { return float2
{{static_cast<float>(in
[0]), static_cast<float>(in
[1])}}; };
430 std::transform(tmpres
[i
].cbegin(), tmpres
[i
].cend(), state
->Coeffs
[i
].begin(),
435 max_delay
-= min_delay
;
436 /* Increase the IR size by double the base delay with dual-band processing
437 * to account for the head and tail from the HF response scale.
439 const ALuint irsize
{minu(Hrtf
->irSize
+ base_delay
*2, HRIR_LENGTH
)};
440 const ALuint max_length
{minu(hrir_delay_round(max_delay
) + irsize
, HRIR_LENGTH
)};
442 TRACE("Skipped delay: %.2f, max delay: %.2f, new FIR length: %u\n",
443 min_delay
/double{HRIR_DELAY_FRACONE
}, max_delay
/double{HRIR_DELAY_FRACONE
},
445 state
->IrSize
= max_length
;
451 std::unique_ptr
<HrtfStore
> CreateHrtfStore(ALuint rate
, ALushort irSize
, const ALuint fdCount
,
452 const ALubyte
*evCount
, const ALushort
*distance
, const ALushort
*azCount
,
453 const ALushort
*irOffset
, ALushort irCount
, const HrirArray
*coeffs
, const ubyte2
*delays
,
454 const char *filename
)
456 std::unique_ptr
<HrtfStore
> Hrtf
;
458 ALuint evTotal
{std::accumulate(evCount
, evCount
+fdCount
, 0u)};
459 size_t total
{sizeof(HrtfStore
)};
460 total
= RoundUp(total
, alignof(HrtfStore::Field
)); /* Align for field infos */
461 total
+= sizeof(HrtfStore::Field
)*fdCount
;
462 total
= RoundUp(total
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
463 total
+= sizeof(Hrtf
->elev
[0])*evTotal
;
464 total
= RoundUp(total
, 16); /* Align for coefficients using SIMD */
465 total
+= sizeof(Hrtf
->coeffs
[0])*irCount
;
466 total
+= sizeof(Hrtf
->delays
[0])*irCount
;
468 Hrtf
.reset(new (al_calloc(16, total
)) HrtfStore
{});
470 ERR("Out of memory allocating storage for %s.\n", filename
);
473 InitRef(Hrtf
->mRef
, 1u);
474 Hrtf
->sampleRate
= rate
;
475 Hrtf
->irSize
= irSize
;
476 Hrtf
->fdCount
= fdCount
;
478 /* Set up pointers to storage following the main HRTF struct. */
479 char *base
= reinterpret_cast<char*>(Hrtf
.get());
480 uintptr_t offset
= sizeof(HrtfStore
);
482 offset
= RoundUp(offset
, alignof(HrtfStore::Field
)); /* Align for field infos */
483 auto field_
= reinterpret_cast<HrtfStore::Field
*>(base
+ offset
);
484 offset
+= sizeof(field_
[0])*fdCount
;
486 offset
= RoundUp(offset
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
487 auto elev_
= reinterpret_cast<HrtfStore::Elevation
*>(base
+ offset
);
488 offset
+= sizeof(elev_
[0])*evTotal
;
490 offset
= RoundUp(offset
, 16); /* Align for coefficients using SIMD */
491 auto coeffs_
= reinterpret_cast<HrirArray
*>(base
+ offset
);
492 offset
+= sizeof(coeffs_
[0])*irCount
;
494 auto delays_
= reinterpret_cast<ubyte2
*>(base
+ offset
);
495 offset
+= sizeof(delays_
[0])*irCount
;
497 assert(offset
== total
);
499 /* Copy input data to storage. */
500 for(ALuint i
{0};i
< fdCount
;i
++)
502 field_
[i
].distance
= distance
[i
] / 1000.0f
;
503 field_
[i
].evCount
= evCount
[i
];
505 for(ALuint i
{0};i
< evTotal
;i
++)
507 elev_
[i
].azCount
= azCount
[i
];
508 elev_
[i
].irOffset
= irOffset
[i
];
510 std::copy_n(coeffs
, irCount
, coeffs_
);
511 std::copy_n(delays
, irCount
, delays_
);
513 /* Finally, assign the storage pointers. */
514 Hrtf
->field
= field_
;
516 Hrtf
->coeffs
= coeffs_
;
517 Hrtf
->delays
= delays_
;
523 ALubyte
GetLE_ALubyte(std::istream
&data
)
525 return static_cast<ALubyte
>(data
.get());
528 ALshort
GetLE_ALshort(std::istream
&data
)
530 int ret
= data
.get();
531 ret
|= data
.get() << 8;
532 return static_cast<ALshort
>((ret
^32768) - 32768);
535 ALushort
GetLE_ALushort(std::istream
&data
)
537 int ret
= data
.get();
538 ret
|= data
.get() << 8;
539 return static_cast<ALushort
>(ret
);
542 ALint
GetLE_ALint24(std::istream
&data
)
544 int ret
= data
.get();
545 ret
|= data
.get() << 8;
546 ret
|= data
.get() << 16;
547 return (ret
^8388608) - 8388608;
550 ALuint
GetLE_ALuint(std::istream
&data
)
552 int ret
= data
.get();
553 ret
|= data
.get() << 8;
554 ret
|= data
.get() << 16;
555 ret
|= data
.get() << 24;
556 return static_cast<ALuint
>(ret
);
559 std::unique_ptr
<HrtfStore
> LoadHrtf00(std::istream
&data
, const char *filename
)
561 ALuint rate
{GetLE_ALuint(data
)};
562 ALushort irCount
{GetLE_ALushort(data
)};
563 ALushort irSize
{GetLE_ALushort(data
)};
564 ALubyte evCount
{GetLE_ALubyte(data
)};
565 if(!data
|| data
.eof())
567 ERR("Failed reading %s\n", filename
);
571 ALboolean failed
{AL_FALSE
};
572 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
574 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
577 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
579 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
580 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
586 auto evOffset
= al::vector
<ALushort
>(evCount
);
587 for(auto &val
: evOffset
)
588 val
= GetLE_ALushort(data
);
589 if(!data
|| data
.eof())
591 ERR("Failed reading %s\n", filename
);
594 for(size_t i
{1};i
< evCount
;i
++)
596 if(evOffset
[i
] <= evOffset
[i
-1])
598 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i
, evOffset
[i
], evOffset
[i
-1]);
602 if(irCount
<= evOffset
.back())
604 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
605 evOffset
.size()-1, evOffset
.back(), irCount
);
611 auto azCount
= al::vector
<ALushort
>(evCount
);
612 for(size_t i
{1};i
< evCount
;i
++)
614 azCount
[i
-1] = static_cast<ALushort
>(evOffset
[i
] - evOffset
[i
-1]);
615 if(azCount
[i
-1] < MIN_AZ_COUNT
|| azCount
[i
-1] > MAX_AZ_COUNT
)
617 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
618 i
-1, azCount
[i
-1], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
622 azCount
.back() = static_cast<ALushort
>(irCount
- evOffset
.back());
623 if(azCount
.back() < MIN_AZ_COUNT
|| azCount
.back() > MAX_AZ_COUNT
)
625 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
626 azCount
.size()-1, azCount
.back(), MIN_AZ_COUNT
, MAX_AZ_COUNT
);
632 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
633 auto delays
= al::vector
<ubyte2
>(irCount
);
634 for(auto &hrir
: coeffs
)
636 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
637 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
639 for(auto &val
: delays
)
640 val
[0] = GetLE_ALubyte(data
);
641 if(!data
|| data
.eof())
643 ERR("Failed reading %s\n", filename
);
646 for(size_t i
{0};i
< irCount
;i
++)
648 if(delays
[i
][0] > MAX_HRIR_DELAY
)
650 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
653 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
658 /* Mirror the left ear responses to the right ear. */
659 for(size_t i
{0};i
< evCount
;i
++)
661 const ALushort evoffset
{evOffset
[i
]};
662 const ALushort azcount
{azCount
[i
]};
663 for(size_t j
{0};j
< azcount
;j
++)
665 const size_t lidx
{evoffset
+ j
};
666 const size_t ridx
{evoffset
+ ((azcount
-j
) % azcount
)};
668 for(size_t k
{0};k
< irSize
;k
++)
669 coeffs
[ridx
][k
][1] = coeffs
[lidx
][k
][0];
670 delays
[ridx
][1] = delays
[lidx
][0];
674 static const ALushort distance
{0};
675 return CreateHrtfStore(rate
, irSize
, 1, &evCount
, &distance
, azCount
.data(), evOffset
.data(),
676 irCount
, coeffs
.data(), delays
.data(), filename
);
679 std::unique_ptr
<HrtfStore
> LoadHrtf01(std::istream
&data
, const char *filename
)
681 ALuint rate
{GetLE_ALuint(data
)};
682 ALushort irSize
{GetLE_ALubyte(data
)};
683 ALubyte evCount
{GetLE_ALubyte(data
)};
684 if(!data
|| data
.eof())
686 ERR("Failed reading %s\n", filename
);
690 ALboolean failed
{AL_FALSE
};
691 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
693 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
696 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
698 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
699 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
705 auto azCount
= al::vector
<ALushort
>(evCount
);
706 std::generate(azCount
.begin(), azCount
.end(), std::bind(GetLE_ALubyte
, std::ref(data
)));
707 if(!data
|| data
.eof())
709 ERR("Failed reading %s\n", filename
);
712 for(size_t i
{0};i
< evCount
;++i
)
714 if(azCount
[i
] < MIN_AZ_COUNT
|| azCount
[i
] > MAX_AZ_COUNT
)
716 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i
, azCount
[i
],
717 MIN_AZ_COUNT
, MAX_AZ_COUNT
);
724 auto evOffset
= al::vector
<ALushort
>(evCount
);
726 ALushort irCount
{azCount
[0]};
727 for(size_t i
{1};i
< evCount
;i
++)
729 evOffset
[i
] = static_cast<ALushort
>(evOffset
[i
-1] + azCount
[i
-1]);
730 irCount
= static_cast<ALushort
>(irCount
+ azCount
[i
]);
733 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
734 auto delays
= al::vector
<ubyte2
>(irCount
);
735 for(auto &hrir
: coeffs
)
737 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
738 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
740 for(auto &val
: delays
)
741 val
[0] = GetLE_ALubyte(data
);
742 if(!data
|| data
.eof())
744 ERR("Failed reading %s\n", filename
);
747 for(size_t i
{0};i
< irCount
;i
++)
749 if(delays
[i
][0] > MAX_HRIR_DELAY
)
751 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
754 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
759 /* Mirror the left ear responses to the right ear. */
760 for(size_t i
{0};i
< evCount
;i
++)
762 const ALushort evoffset
{evOffset
[i
]};
763 const ALushort azcount
{azCount
[i
]};
764 for(size_t j
{0};j
< azcount
;j
++)
766 const size_t lidx
{evoffset
+ j
};
767 const size_t ridx
{evoffset
+ ((azcount
-j
) % azcount
)};
769 for(size_t k
{0};k
< irSize
;k
++)
770 coeffs
[ridx
][k
][1] = coeffs
[lidx
][k
][0];
771 delays
[ridx
][1] = delays
[lidx
][0];
775 static const ALushort distance
{0};
776 return CreateHrtfStore(rate
, irSize
, 1, &evCount
, &distance
, azCount
.data(), evOffset
.data(),
777 irCount
, coeffs
.data(), delays
.data(), filename
);
780 std::unique_ptr
<HrtfStore
> LoadHrtf02(std::istream
&data
, const char *filename
)
782 constexpr ALubyte SampleType_S16
{0};
783 constexpr ALubyte SampleType_S24
{1};
784 constexpr ALubyte ChanType_LeftOnly
{0};
785 constexpr ALubyte ChanType_LeftRight
{1};
787 ALuint rate
{GetLE_ALuint(data
)};
788 ALubyte sampleType
{GetLE_ALubyte(data
)};
789 ALubyte channelType
{GetLE_ALubyte(data
)};
790 ALushort irSize
{GetLE_ALubyte(data
)};
791 ALubyte fdCount
{GetLE_ALubyte(data
)};
792 if(!data
|| data
.eof())
794 ERR("Failed reading %s\n", filename
);
798 ALboolean failed
{AL_FALSE
};
799 if(sampleType
> SampleType_S24
)
801 ERR("Unsupported sample type: %d\n", sampleType
);
804 if(channelType
> ChanType_LeftRight
)
806 ERR("Unsupported channel type: %d\n", channelType
);
810 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
812 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
815 if(fdCount
< 1 || fdCount
> MAX_FD_COUNT
)
817 ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
818 fdCount
, MIN_FD_COUNT
, MAX_FD_COUNT
);
824 auto distance
= al::vector
<ALushort
>(fdCount
);
825 auto evCount
= al::vector
<ALubyte
>(fdCount
);
826 auto azCount
= al::vector
<ALushort
>{};
827 for(size_t f
{0};f
< fdCount
;f
++)
829 distance
[f
] = GetLE_ALushort(data
);
830 evCount
[f
] = GetLE_ALubyte(data
);
831 if(!data
|| data
.eof())
833 ERR("Failed reading %s\n", filename
);
837 if(distance
[f
] < MIN_FD_DISTANCE
|| distance
[f
] > MAX_FD_DISTANCE
)
839 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f
, distance
[f
],
840 MIN_FD_DISTANCE
, MAX_FD_DISTANCE
);
843 if(f
> 0 && distance
[f
] <= distance
[f
-1])
845 ERR("Field distance[%zu] is not after previous (%d > %d)\n", f
, distance
[f
],
849 if(evCount
[f
] < MIN_EV_COUNT
|| evCount
[f
] > MAX_EV_COUNT
)
851 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f
, evCount
[f
],
852 MIN_EV_COUNT
, MAX_EV_COUNT
);
858 const size_t ebase
{azCount
.size()};
859 azCount
.resize(ebase
+ evCount
[f
]);
860 std::generate(azCount
.begin()+static_cast<ptrdiff_t>(ebase
), azCount
.end(),
861 std::bind(GetLE_ALubyte
, std::ref(data
)));
862 if(!data
|| data
.eof())
864 ERR("Failed reading %s\n", filename
);
868 for(size_t e
{0};e
< evCount
[f
];e
++)
870 if(azCount
[ebase
+e
] < MIN_AZ_COUNT
|| azCount
[ebase
+e
] > MAX_AZ_COUNT
)
872 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f
, e
,
873 azCount
[ebase
+e
], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
881 auto evOffset
= al::vector
<ALushort
>(azCount
.size());
883 std::partial_sum(azCount
.cbegin(), azCount
.cend()-1, evOffset
.begin()+1);
884 const auto irTotal
= static_cast<ALushort
>(evOffset
.back() + azCount
.back());
886 auto coeffs
= al::vector
<HrirArray
>(irTotal
, HrirArray
{});
887 auto delays
= al::vector
<ubyte2
>(irTotal
);
888 if(channelType
== ChanType_LeftOnly
)
890 if(sampleType
== SampleType_S16
)
892 for(auto &hrir
: coeffs
)
894 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
895 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
898 else if(sampleType
== SampleType_S24
)
900 for(auto &hrir
: coeffs
)
902 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
903 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
906 for(auto &val
: delays
)
907 val
[0] = GetLE_ALubyte(data
);
908 if(!data
|| data
.eof())
910 ERR("Failed reading %s\n", filename
);
913 for(size_t i
{0};i
< irTotal
;++i
)
915 if(delays
[i
][0] > MAX_HRIR_DELAY
)
917 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
920 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
923 else if(channelType
== ChanType_LeftRight
)
925 if(sampleType
== SampleType_S16
)
927 for(auto &hrir
: coeffs
)
929 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
931 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
932 val
[1] = GetLE_ALshort(data
) / 32768.0f
;
936 else if(sampleType
== SampleType_S24
)
938 for(auto &hrir
: coeffs
)
940 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
942 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
943 val
[1] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
947 for(auto &val
: delays
)
949 val
[0] = GetLE_ALubyte(data
);
950 val
[1] = GetLE_ALubyte(data
);
952 if(!data
|| data
.eof())
954 ERR("Failed reading %s\n", filename
);
958 for(size_t i
{0};i
< irTotal
;++i
)
960 if(delays
[i
][0] > MAX_HRIR_DELAY
)
962 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
965 if(delays
[i
][1] > MAX_HRIR_DELAY
)
967 ERR("Invalid delays[%zu][1]: %d (%d)\n", i
, delays
[i
][1], MAX_HRIR_DELAY
);
970 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
971 delays
[i
][1] <<= HRIR_DELAY_FRACBITS
;
977 if(channelType
== ChanType_LeftOnly
)
979 /* Mirror the left ear responses to the right ear. */
981 for(size_t f
{0};f
< fdCount
;f
++)
983 for(size_t e
{0};e
< evCount
[f
];e
++)
985 const ALushort evoffset
{evOffset
[ebase
+e
]};
986 const ALushort azcount
{azCount
[ebase
+e
]};
987 for(size_t a
{0};a
< azcount
;a
++)
989 const size_t lidx
{evoffset
+ a
};
990 const size_t ridx
{evoffset
+ ((azcount
-a
) % azcount
)};
992 for(size_t k
{0};k
< irSize
;k
++)
993 coeffs
[ridx
][k
][1] = coeffs
[lidx
][k
][0];
994 delays
[ridx
][1] = delays
[lidx
][0];
1003 auto distance_
= al::vector
<ALushort
>(distance
.size());
1004 auto evCount_
= al::vector
<ALubyte
>(evCount
.size());
1005 auto azCount_
= al::vector
<ALushort
>(azCount
.size());
1006 auto evOffset_
= al::vector
<ALushort
>(evOffset
.size());
1007 auto coeffs_
= al::vector
<HrirArray
>(coeffs
.size());
1008 auto delays_
= al::vector
<ubyte2
>(delays
.size());
1010 /* Simple reverse for the per-field elements. */
1011 std::reverse_copy(distance
.cbegin(), distance
.cend(), distance_
.begin());
1012 std::reverse_copy(evCount
.cbegin(), evCount
.cend(), evCount_
.begin());
1014 /* Each field has a group of elevations, which each have an azimuth
1015 * count. Reverse the order of the groups, keeping the relative order
1016 * of per-group azimuth counts.
1018 auto azcnt_end
= azCount_
.end();
1019 auto copy_azs
= [&azCount
,&azcnt_end
](const ptrdiff_t ebase
, const ALubyte num_evs
) -> ptrdiff_t
1021 auto azcnt_src
= azCount
.begin()+ebase
;
1022 azcnt_end
= std::copy_backward(azcnt_src
, azcnt_src
+num_evs
, azcnt_end
);
1023 return ebase
+ num_evs
;
1025 std::accumulate(evCount
.cbegin(), evCount
.cend(), ptrdiff_t{0}, copy_azs
);
1026 assert(azCount_
.begin() == azcnt_end
);
1028 /* Reestablish the IR offset for each elevation index, given the new
1029 * ordering of elevations.
1032 std::partial_sum(azCount_
.cbegin(), azCount_
.cend()-1, evOffset_
.begin()+1);
1034 /* Reverse the order of each field's group of IRs. */
1035 auto coeffs_end
= coeffs_
.end();
1036 auto delays_end
= delays_
.end();
1037 auto copy_irs
= [&azCount
,&coeffs
,&delays
,&coeffs_end
,&delays_end
](
1038 const ptrdiff_t ebase
, const ALubyte num_evs
) -> ptrdiff_t
1040 const ALsizei abase
{std::accumulate(azCount
.cbegin(), azCount
.cbegin()+ebase
, 0)};
1041 const ALsizei num_azs
{std::accumulate(azCount
.cbegin()+ebase
,
1042 azCount
.cbegin() + (ebase
+num_evs
), 0)};
1044 coeffs_end
= std::copy_backward(coeffs
.cbegin() + abase
,
1045 coeffs
.cbegin() + (abase
+num_azs
), coeffs_end
);
1046 delays_end
= std::copy_backward(delays
.cbegin() + abase
,
1047 delays
.cbegin() + (abase
+num_azs
), delays_end
);
1049 return ebase
+ num_evs
;
1051 std::accumulate(evCount
.cbegin(), evCount
.cend(), ptrdiff_t{0}, copy_irs
);
1052 assert(coeffs_
.begin() == coeffs_end
);
1053 assert(delays_
.begin() == delays_end
);
1055 distance
= std::move(distance_
);
1056 evCount
= std::move(evCount_
);
1057 azCount
= std::move(azCount_
);
1058 evOffset
= std::move(evOffset_
);
1059 coeffs
= std::move(coeffs_
);
1060 delays
= std::move(delays_
);
1063 return CreateHrtfStore(rate
, irSize
, fdCount
, evCount
.data(), distance
.data(), azCount
.data(),
1064 evOffset
.data(), irTotal
, coeffs
.data(), delays
.data(), filename
);
1068 bool checkName(const std::string
&name
)
1070 auto match_name
= [&name
](const HrtfEntry
&entry
) -> bool { return name
== entry
.mDispName
; };
1071 auto &enum_names
= EnumeratedHrtfs
;
1072 return std::find_if(enum_names
.cbegin(), enum_names
.cend(), match_name
) != enum_names
.cend();
1075 void AddFileEntry(const std::string
&filename
)
1077 /* Check if this file has already been enumerated. */
1078 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1079 [&filename
](const HrtfEntry
&entry
) -> bool
1080 { return entry
.mFilename
== filename
; });
1081 if(enum_iter
!= EnumeratedHrtfs
.cend())
1083 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1087 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1088 * format update). */
1089 size_t namepos
= filename
.find_last_of('/')+1;
1090 if(!namepos
) namepos
= filename
.find_last_of('\\')+1;
1092 size_t extpos
{filename
.find_last_of('.')};
1093 if(extpos
<= namepos
) extpos
= std::string::npos
;
1095 const std::string basename
{(extpos
== std::string::npos
) ?
1096 filename
.substr(namepos
) : filename
.substr(namepos
, extpos
-namepos
)};
1097 std::string newname
{basename
};
1099 while(checkName(newname
))
1103 newname
+= std::to_string(++count
);
1105 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1106 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1108 TRACE("Adding file entry \"%s\"\n", entry
.mFilename
.c_str());
1111 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1112 * for input instead of opening the given filename.
1114 void AddBuiltInEntry(const std::string
&dispname
, ALuint residx
)
1116 const std::string filename
{'!'+std::to_string(residx
)+'_'+dispname
};
1118 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1119 [&filename
](const HrtfEntry
&entry
) -> bool
1120 { return entry
.mFilename
== filename
; });
1121 if(enum_iter
!= EnumeratedHrtfs
.cend())
1123 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1127 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1128 * format update). */
1130 std::string newname
{dispname
};
1132 while(checkName(newname
))
1136 newname
+= std::to_string(++count
);
1138 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1139 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1141 TRACE("Adding built-in entry \"%s\"\n", entry
.mFilename
.c_str());
1145 #define IDR_DEFAULT_HRTF_MHR 1
1147 #ifndef ALSOFT_EMBED_HRTF_DATA
1149 al::span
<const char> GetResource(int /*name*/)
1154 #include "hrtf_default.h"
1156 al::span
<const char> GetResource(int name
)
1158 if(name
== IDR_DEFAULT_HRTF_MHR
)
1159 return {reinterpret_cast<const char*>(hrtf_default
), sizeof(hrtf_default
)};
1167 al::vector
<std::string
> EnumerateHrtf(const char *devname
)
1169 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1170 EnumeratedHrtfs
.clear();
1172 bool usedefaults
{true};
1173 if(auto pathopt
= ConfigValueStr(devname
, nullptr, "hrtf-paths"))
1175 const char *pathlist
{pathopt
->c_str()};
1176 while(pathlist
&& *pathlist
)
1178 const char *next
, *end
;
1180 while(isspace(*pathlist
) || *pathlist
== ',')
1182 if(*pathlist
== '\0')
1185 next
= strchr(pathlist
, ',');
1190 end
= pathlist
+ strlen(pathlist
);
1191 usedefaults
= false;
1194 while(end
!= pathlist
&& isspace(*(end
-1)))
1198 const std::string pname
{pathlist
, end
};
1199 for(const auto &fname
: SearchDataFiles(".mhr", pname
.c_str()))
1200 AddFileEntry(fname
);
1209 for(const auto &fname
: SearchDataFiles(".mhr", "openal/hrtf"))
1210 AddFileEntry(fname
);
1212 if(!GetResource(IDR_DEFAULT_HRTF_MHR
).empty())
1213 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR
);
1216 al::vector
<std::string
> list
;
1217 list
.reserve(EnumeratedHrtfs
.size());
1218 for(auto &entry
: EnumeratedHrtfs
)
1219 list
.emplace_back(entry
.mDispName
);
1221 if(auto defhrtfopt
= ConfigValueStr(devname
, nullptr, "default-hrtf"))
1223 auto iter
= std::find(list
.begin(), list
.end(), *defhrtfopt
);
1224 if(iter
== list
.end())
1225 WARN("Failed to find default HRTF \"%s\"\n", defhrtfopt
->c_str());
1226 else if(iter
!= list
.begin())
1227 std::rotate(list
.begin(), iter
, iter
+1);
1233 HrtfStore
*GetLoadedHrtf(const std::string
&name
, const char *devname
, const ALuint devrate
)
1235 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1236 auto entry_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1237 [&name
](const HrtfEntry
&entry
) -> bool { return entry
.mDispName
== name
; }
1239 if(entry_iter
== EnumeratedHrtfs
.cend())
1241 const std::string
&fname
= entry_iter
->mFilename
;
1243 std::lock_guard
<std::mutex
> __
{LoadedHrtfLock
};
1244 auto hrtf_lt_fname
= [](LoadedHrtf
&hrtf
, const std::string
&filename
) -> bool
1245 { return hrtf
.mFilename
< filename
; };
1246 auto handle
= std::lower_bound(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), fname
, hrtf_lt_fname
);
1247 while(handle
!= LoadedHrtfs
.end() && handle
->mFilename
== fname
)
1249 HrtfStore
*hrtf
{handle
->mEntry
.get()};
1250 if(hrtf
&& hrtf
->sampleRate
== devrate
)
1258 std::unique_ptr
<std::istream
> stream
;
1261 if(sscanf(fname
.c_str(), "!%d%c", &residx
, &ch
) == 2 && ch
== '_')
1263 TRACE("Loading %s...\n", fname
.c_str());
1264 al::span
<const char> res
{GetResource(residx
)};
1267 ERR("Could not get resource %u, %s\n", residx
, name
.c_str());
1270 stream
= al::make_unique
<idstream
>(res
.begin(), res
.end());
1274 TRACE("Loading %s...\n", fname
.c_str());
1275 auto fstr
= al::make_unique
<al::ifstream
>(fname
.c_str(), std::ios::binary
);
1276 if(!fstr
->is_open())
1278 ERR("Could not open %s\n", fname
.c_str());
1281 stream
= std::move(fstr
);
1284 std::unique_ptr
<HrtfStore
> hrtf
;
1285 char magic
[sizeof(magicMarker02
)];
1286 stream
->read(magic
, sizeof(magic
));
1287 if(stream
->gcount() < static_cast<std::streamsize
>(sizeof(magicMarker02
)))
1288 ERR("%s data is too short (%zu bytes)\n", name
.c_str(), stream
->gcount());
1289 else if(memcmp(magic
, magicMarker02
, sizeof(magicMarker02
)) == 0)
1291 TRACE("Detected data set format v2\n");
1292 hrtf
= LoadHrtf02(*stream
, name
.c_str());
1294 else if(memcmp(magic
, magicMarker01
, sizeof(magicMarker01
)) == 0)
1296 TRACE("Detected data set format v1\n");
1297 hrtf
= LoadHrtf01(*stream
, name
.c_str());
1299 else if(memcmp(magic
, magicMarker00
, sizeof(magicMarker00
)) == 0)
1301 TRACE("Detected data set format v0\n");
1302 hrtf
= LoadHrtf00(*stream
, name
.c_str());
1305 ERR("Invalid header in %s: \"%.8s\"\n", name
.c_str(), magic
);
1310 ERR("Failed to load %s\n", name
.c_str());
1314 if(hrtf
->sampleRate
!= devrate
)
1316 /* Calculate the last elevation's index and get the total IR count. */
1317 const size_t lastEv
{std::accumulate(hrtf
->field
, hrtf
->field
+hrtf
->fdCount
, size_t{0},
1318 [](const size_t curval
, const HrtfStore::Field
&field
) noexcept
-> size_t
1319 { return curval
+ field
.evCount
; }
1321 const size_t irCount
{size_t{hrtf
->elev
[lastEv
].irOffset
} + hrtf
->elev
[lastEv
].azCount
};
1323 /* Resample all the IRs. */
1324 std::array
<std::array
<double,HRIR_LENGTH
>,2> inout
;
1326 rs
.init(hrtf
->sampleRate
, devrate
);
1327 for(size_t i
{0};i
< irCount
;++i
)
1329 HrirArray
&coeffs
= const_cast<HrirArray
&>(hrtf
->coeffs
[i
]);
1330 for(size_t j
{0};j
< 2;++j
)
1332 std::transform(coeffs
.cbegin(), coeffs
.cend(), inout
[0].begin(),
1333 [j
](const float2
&in
) noexcept
-> double { return in
[j
]; });
1334 rs
.process(HRIR_LENGTH
, inout
[0].data(), HRIR_LENGTH
, inout
[1].data());
1335 for(size_t k
{0};k
< HRIR_LENGTH
;++k
)
1336 coeffs
[k
][j
] = static_cast<float>(inout
[1][k
]);
1341 /* Scale the delays for the new sample rate. */
1342 float max_delay
{0.0f
};
1343 auto new_delays
= al::vector
<float2
>(irCount
);
1344 const float rate_scale
{static_cast<float>(devrate
)/static_cast<float>(hrtf
->sampleRate
)};
1345 for(size_t i
{0};i
< irCount
;++i
)
1347 for(size_t j
{0};j
< 2;++j
)
1349 const float new_delay
{std::round(hrtf
->delays
[i
][j
] * rate_scale
) /
1350 float{HRIR_DELAY_FRACONE
}};
1351 max_delay
= maxf(max_delay
, new_delay
);
1352 new_delays
[i
][j
] = new_delay
;
1356 /* If the new delays exceed the max, scale it down to fit (essentially
1357 * shrinking the head radius; not ideal but better than a per-delay
1360 float delay_scale
{HRIR_DELAY_FRACONE
};
1361 if(max_delay
> MAX_HRIR_DELAY
)
1363 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay
, MAX_HRIR_DELAY
);
1364 delay_scale
*= float{MAX_HRIR_DELAY
} / max_delay
;
1367 for(size_t i
{0};i
< irCount
;++i
)
1369 ubyte2
&delays
= const_cast<ubyte2
&>(hrtf
->delays
[i
]);
1370 for(size_t j
{0};j
< 2;++j
)
1371 delays
[j
] = static_cast<ALubyte
>(float2int(new_delays
[i
][j
] * delay_scale
));
1374 /* Scale the IR size for the new sample rate and update the stored
1377 const float newIrSize
{std::round(static_cast<float>(hrtf
->irSize
) * rate_scale
)};
1378 hrtf
->irSize
= static_cast<ALuint
>(minf(HRIR_LENGTH
, newIrSize
));
1379 hrtf
->sampleRate
= devrate
;
1382 if(auto hrtfsizeopt
= ConfigValueUInt(devname
, nullptr, "hrtf-size"))
1384 if(*hrtfsizeopt
> 0 && *hrtfsizeopt
< hrtf
->irSize
)
1385 hrtf
->irSize
= maxu(*hrtfsizeopt
, MIN_IR_LENGTH
);
1388 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name
.c_str(),
1389 hrtf
->sampleRate
, hrtf
->irSize
);
1390 handle
= LoadedHrtfs
.emplace(handle
, LoadedHrtf
{fname
, std::move(hrtf
)});
1392 return handle
->mEntry
.get();
1396 void HrtfStore::IncRef()
1398 auto ref
= IncrementRef(mRef
);
1399 TRACE("HrtfEntry %p increasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1402 void HrtfStore::DecRef()
1404 auto ref
= DecrementRef(mRef
);
1405 TRACE("HrtfEntry %p decreasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1408 std::lock_guard
<std::mutex
> _
{LoadedHrtfLock
};
1410 /* Go through and remove all unused HRTFs. */
1411 auto remove_unused
= [](LoadedHrtf
&hrtf
) -> bool
1413 HrtfStore
*entry
{hrtf
.mEntry
.get()};
1414 if(entry
&& ReadRef(entry
->mRef
) == 0)
1416 TRACE("Unloading unused HRTF %s\n", hrtf
.mFilename
.data());
1417 hrtf
.mEntry
= nullptr;
1422 auto iter
= std::remove_if(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), remove_unused
);
1423 LoadedHrtfs
.erase(iter
, LoadedHrtfs
.end());