2 * 2-channel UHJ Decoder
4 * Copyright (c) Chris Robinson <chris.kcat@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
38 #include "alcomplex.h"
40 #include "alnumbers.h"
43 #include "opthelpers.h"
44 #include "phase_shifter.h"
48 #include "win_main_utf8.h"
52 void operator()(FILE *file
) { fclose(file
); }
54 using FilePtr
= std::unique_ptr
<FILE,FileDeleter
>;
56 struct SndFileDeleter
{
57 void operator()(SNDFILE
*sndfile
) { sf_close(sndfile
); }
59 using SndFilePtr
= std::unique_ptr
<SNDFILE
,SndFileDeleter
>;
62 using ubyte
= unsigned char;
63 using ushort
= unsigned short;
64 using uint
= unsigned int;
65 using complex_d
= std::complex<double>;
67 using byte4
= std::array
<al::byte
,4>;
70 constexpr ubyte SUBTYPE_BFORMAT_FLOAT
[]{
71 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1,
72 0xca, 0x00, 0x00, 0x00
75 void fwrite16le(ushort val
, FILE *f
)
77 ubyte data
[2]{ static_cast<ubyte
>(val
&0xff), static_cast<ubyte
>((val
>>8)&0xff) };
78 fwrite(data
, 1, 2, f
);
81 void fwrite32le(uint val
, FILE *f
)
83 ubyte data
[4]{ static_cast<ubyte
>(val
&0xff), static_cast<ubyte
>((val
>>8)&0xff),
84 static_cast<ubyte
>((val
>>16)&0xff), static_cast<ubyte
>((val
>>24)&0xff) };
85 fwrite(data
, 1, 4, f
);
88 template<al::endian
= al::endian::native
>
89 byte4
f32AsLEBytes(const float &value
) = delete;
92 byte4 f32AsLEBytes
<al::endian::little
>(const float &value
)
95 std::memcpy(ret
.data(), &value
, 4);
99 byte4 f32AsLEBytes
<al::endian::big
>(const float &value
)
102 std::memcpy(ret
.data(), &value
, 4);
103 std::swap(ret
[0], ret
[3]);
104 std::swap(ret
[1], ret
[2]);
109 constexpr uint BufferLineSize
{1024};
111 using FloatBufferLine
= std::array
<float,BufferLineSize
>;
112 using FloatBufferSpan
= al::span
<float,BufferLineSize
>;
116 constexpr static size_t sFilterDelay
{1024};
118 alignas(16) std::array
<float,BufferLineSize
+sFilterDelay
> mS
{};
119 alignas(16) std::array
<float,BufferLineSize
+sFilterDelay
> mD
{};
120 alignas(16) std::array
<float,BufferLineSize
+sFilterDelay
> mT
{};
121 alignas(16) std::array
<float,BufferLineSize
+sFilterDelay
> mQ
{};
123 /* History for the FIR filter. */
124 alignas(16) std::array
<float,sFilterDelay
-1> mDTHistory
{};
125 alignas(16) std::array
<float,sFilterDelay
-1> mSHistory
{};
127 alignas(16) std::array
<float,BufferLineSize
+ sFilterDelay
*2> mTemp
{};
129 void decode(const float *RESTRICT InSamples
, const size_t InChannels
,
130 const al::span
<FloatBufferLine
> OutSamples
, const size_t SamplesToDo
);
131 void decode2(const float *RESTRICT InSamples
, const al::span
<FloatBufferLine
,3> OutSamples
,
132 const size_t SamplesToDo
);
134 DEF_NEWDEL(UhjDecoder
)
137 const PhaseShifterT
<UhjDecoder::sFilterDelay
*2> PShift
{};
140 /* Decoding UHJ is done as:
145 * W = 0.981532*S + 0.197484*j(0.828331*D + 0.767820*T)
146 * X = 0.418496*S - j(0.828331*D + 0.767820*T)
147 * Y = 0.795968*D - 0.676392*T + j(0.186633*S)
150 * where j is a +90 degree phase shift. 3-channel UHJ excludes Q, while 2-
151 * channel excludes Q and T. The B-Format signal reconstructed from 2-channel
152 * UHJ should not be run through a normal B-Format decoder, as it needs
153 * different shelf filters.
155 * NOTE: Some sources specify
157 * S = (Left + Right)/2
158 * D = (Left - Right)/2
160 * However, this is incorrect. It's halving Left and Right even though they
161 * were already halved during encoding, causing S and D to be half what they
162 * initially were at the encoding stage. This division is not present in
163 * Gerzon's original paper for deriving Sigma (S) or Delta (D) from the L and R
164 * signals. As proof, taking Y for example:
166 * Y = 0.795968*D - 0.676392*T + j(0.186633*S)
168 * * Plug in the encoding parameters, using ? as a placeholder for whether S
169 * and D should receive an extra 0.5 factor
170 * Y = 0.795968*(j(-0.3420201*W + 0.5098604*X) + 0.6554516*Y)*? -
171 * 0.676392*(j(-0.1432*W + 0.6512*X) - 0.7071068*Y) +
172 * 0.186633*j(0.9396926*W + 0.1855740*X)*?
174 * * Move common factors in
175 * Y = (j(-0.3420201*0.795968*?*W + 0.5098604*0.795968*?*X) + 0.6554516*0.795968*?*Y) -
176 * (j(-0.1432*0.676392*W + 0.6512*0.676392*X) - 0.7071068*0.676392*Y) +
177 * j(0.9396926*0.186633*?*W + 0.1855740*0.186633*?*X)
179 * * Clean up extraneous groupings
180 * Y = j(-0.3420201*0.795968*?*W + 0.5098604*0.795968*?*X) + 0.6554516*0.795968*?*Y -
181 * j(-0.1432*0.676392*W + 0.6512*0.676392*X) + 0.7071068*0.676392*Y +
182 * j*(0.9396926*0.186633*?*W + 0.1855740*0.186633*?*X)
184 * * Move phase shifts together and combine them
185 * Y = j(-0.3420201*0.795968*?*W + 0.5098604*0.795968*?*X - -0.1432*0.676392*W -
186 * 0.6512*0.676392*X + 0.9396926*0.186633*?*W + 0.1855740*0.186633*?*X) +
187 * 0.6554516*0.795968*?*Y + 0.7071068*0.676392*Y
190 * Y = j(-0.3420201*0.795968*?*W + 0.1432*0.676392*W + 0.9396926*0.186633*?*W +
191 * 0.5098604*0.795968*?*X + -0.6512*0.676392*X + 0.1855740*0.186633*?*X) +
192 * 0.7071068*0.676392*Y + 0.6554516*0.795968*?*Y
194 * * Move common factors out
195 * Y = j((-0.3420201*0.795968*? + 0.1432*0.676392 + 0.9396926*0.186633*?)*W +
196 * ( 0.5098604*0.795968*? + -0.6512*0.676392 + 0.1855740*0.186633*?)*X) +
197 * (0.7071068*0.676392 + 0.6554516*0.795968*?)*Y
199 * * Result w/ 0.5 factor:
200 * -0.3420201*0.795968*0.5 + 0.1432*0.676392 + 0.9396926*0.186633*0.5 = 0.04843*W
201 * 0.5098604*0.795968*0.5 + -0.6512*0.676392 + 0.1855740*0.186633*0.5 = -0.22023*X
202 * 0.7071068*0.676392 + 0.6554516*0.795968*0.5 = 0.73914*Y
203 * -> Y = j(0.04843*W + -0.22023*X) + 0.73914*Y
205 * * Result w/o 0.5 factor:
206 * -0.3420201*0.795968 + 0.1432*0.676392 + 0.9396926*0.186633 = 0.00000*W
207 * 0.5098604*0.795968 + -0.6512*0.676392 + 0.1855740*0.186633 = 0.00000*X
208 * 0.7071068*0.676392 + 0.6554516*0.795968 = 1.00000*Y
209 * -> Y = j(0.00000*W + 0.00000*X) + 1.00000*Y
211 * Not halving produces a result matching the original input.
213 void UhjDecoder::decode(const float *RESTRICT InSamples
, const size_t InChannels
,
214 const al::span
<FloatBufferLine
> OutSamples
, const size_t SamplesToDo
)
216 ASSUME(SamplesToDo
> 0);
218 float *woutput
{OutSamples
[0].data()};
219 float *xoutput
{OutSamples
[1].data()};
220 float *youtput
{OutSamples
[2].data()};
222 /* Add a delay to the input channels, to align it with the all-passed
226 /* S = Left + Right */
227 for(size_t i
{0};i
< SamplesToDo
;++i
)
228 mS
[sFilterDelay
+i
] = InSamples
[i
*InChannels
+ 0] + InSamples
[i
*InChannels
+ 1];
230 /* D = Left - Right */
231 for(size_t i
{0};i
< SamplesToDo
;++i
)
232 mD
[sFilterDelay
+i
] = InSamples
[i
*InChannels
+ 0] - InSamples
[i
*InChannels
+ 1];
237 for(size_t i
{0};i
< SamplesToDo
;++i
)
238 mT
[sFilterDelay
+i
] = InSamples
[i
*InChannels
+ 2];
243 for(size_t i
{0};i
< SamplesToDo
;++i
)
244 mQ
[sFilterDelay
+i
] = InSamples
[i
*InChannels
+ 3];
247 /* Precompute j(0.828331*D + 0.767820*T) and store in xoutput. */
248 auto tmpiter
= std::copy(mDTHistory
.cbegin(), mDTHistory
.cend(), mTemp
.begin());
249 std::transform(mD
.cbegin(), mD
.cbegin()+SamplesToDo
+sFilterDelay
, mT
.cbegin(), tmpiter
,
250 [](const float d
, const float t
) noexcept
{ return 0.828331f
*d
+ 0.767820f
*t
; });
251 std::copy_n(mTemp
.cbegin()+SamplesToDo
, mDTHistory
.size(), mDTHistory
.begin());
252 PShift
.process({xoutput
, SamplesToDo
}, mTemp
.data());
254 for(size_t i
{0};i
< SamplesToDo
;++i
)
256 /* W = 0.981532*S + 0.197484*j(0.828331*D + 0.767820*T) */
257 woutput
[i
] = 0.981532f
*mS
[i
] + 0.197484f
*xoutput
[i
];
258 /* X = 0.418496*S - j(0.828331*D + 0.767820*T) */
259 xoutput
[i
] = 0.418496f
*mS
[i
] - xoutput
[i
];
262 /* Precompute j*S and store in youtput. */
263 tmpiter
= std::copy(mSHistory
.cbegin(), mSHistory
.cend(), mTemp
.begin());
264 std::copy_n(mS
.cbegin(), SamplesToDo
+sFilterDelay
, tmpiter
);
265 std::copy_n(mTemp
.cbegin()+SamplesToDo
, mSHistory
.size(), mSHistory
.begin());
266 PShift
.process({youtput
, SamplesToDo
}, mTemp
.data());
268 for(size_t i
{0};i
< SamplesToDo
;++i
)
270 /* Y = 0.795968*D - 0.676392*T + j(0.186633*S) */
271 youtput
[i
] = 0.795968f
*mD
[i
] - 0.676392f
*mT
[i
] + 0.186633f
*youtput
[i
];
274 if(OutSamples
.size() > 3)
276 float *zoutput
{OutSamples
[3].data()};
278 for(size_t i
{0};i
< SamplesToDo
;++i
)
279 zoutput
[i
] = 1.023332f
*mQ
[i
];
282 std::copy(mS
.begin()+SamplesToDo
, mS
.begin()+SamplesToDo
+sFilterDelay
, mS
.begin());
283 std::copy(mD
.begin()+SamplesToDo
, mD
.begin()+SamplesToDo
+sFilterDelay
, mD
.begin());
284 std::copy(mT
.begin()+SamplesToDo
, mT
.begin()+SamplesToDo
+sFilterDelay
, mT
.begin());
285 std::copy(mQ
.begin()+SamplesToDo
, mQ
.begin()+SamplesToDo
+sFilterDelay
, mQ
.begin());
288 /* This is an alternative equation for decoding 2-channel UHJ. Not sure what
289 * the intended benefit is over the above equation as this slightly reduces the
290 * amount of the original left response and has more of the phase-shifted
291 * forward response on the left response.
293 * This decoding is done as:
298 * W = 0.981530*S + j*0.163585*D
299 * X = 0.418504*S - j*0.828347*D
300 * Y = 0.762956*D + j*0.384230*S
302 * where j is a +90 degree phase shift.
304 * NOTE: As above, S and D should not be halved. The only consequence of
305 * halving here is merely a -6dB reduction in output, but it's still incorrect.
307 void UhjDecoder::decode2(const float *RESTRICT InSamples
,
308 const al::span
<FloatBufferLine
,3> OutSamples
, const size_t SamplesToDo
)
310 ASSUME(SamplesToDo
> 0);
312 float *woutput
{OutSamples
[0].data()};
313 float *xoutput
{OutSamples
[1].data()};
314 float *youtput
{OutSamples
[2].data()};
316 /* S = Left + Right */
317 for(size_t i
{0};i
< SamplesToDo
;++i
)
318 mS
[sFilterDelay
+i
] = InSamples
[i
*2 + 0] + InSamples
[i
*2 + 1];
320 /* D = Left - Right */
321 for(size_t i
{0};i
< SamplesToDo
;++i
)
322 mD
[sFilterDelay
+i
] = InSamples
[i
*2 + 0] - InSamples
[i
*2 + 1];
324 /* Precompute j*D and store in xoutput. */
325 auto tmpiter
= std::copy(mDTHistory
.cbegin(), mDTHistory
.cend(), mTemp
.begin());
326 std::copy_n(mD
.cbegin(), SamplesToDo
+sFilterDelay
, tmpiter
);
327 std::copy_n(mTemp
.cbegin()+SamplesToDo
, mDTHistory
.size(), mDTHistory
.begin());
328 PShift
.process({xoutput
, SamplesToDo
}, mTemp
.data());
330 for(size_t i
{0};i
< SamplesToDo
;++i
)
332 /* W = 0.981530*S + j*0.163585*D */
333 woutput
[i
] = 0.981530f
*mS
[i
] + 0.163585f
*xoutput
[i
];
334 /* X = 0.418504*S - j*0.828347*D */
335 xoutput
[i
] = 0.418504f
*mS
[i
] - 0.828347f
*xoutput
[i
];
338 /* Precompute j*S and store in youtput. */
339 tmpiter
= std::copy(mSHistory
.cbegin(), mSHistory
.cend(), mTemp
.begin());
340 std::copy_n(mS
.cbegin(), SamplesToDo
+sFilterDelay
, tmpiter
);
341 std::copy_n(mTemp
.cbegin()+SamplesToDo
, mSHistory
.size(), mSHistory
.begin());
342 PShift
.process({youtput
, SamplesToDo
}, mTemp
.data());
344 for(size_t i
{0};i
< SamplesToDo
;++i
)
346 /* Y = 0.762956*D + j*0.384230*S */
347 youtput
[i
] = 0.762956f
*mD
[i
] + 0.384230f
*youtput
[i
];
350 std::copy(mS
.begin()+SamplesToDo
, mS
.begin()+SamplesToDo
+sFilterDelay
, mS
.begin());
351 std::copy(mD
.begin()+SamplesToDo
, mD
.begin()+SamplesToDo
+sFilterDelay
, mD
.begin());
355 int main(int argc
, char **argv
)
357 if(argc
< 2 || std::strcmp(argv
[1], "-h") == 0 || std::strcmp(argv
[1], "--help") == 0)
359 printf("Usage: %s <[options] filename.wav...>\n\n"
361 " --general Use the general equations for 2-channel UHJ (default).\n"
362 " --alternative Use the alternative equations for 2-channel UHJ.\n"
364 "Note: When decoding 2-channel UHJ to an .amb file, the result should not use\n"
365 "the normal B-Format shelf filters! Only 3- and 4-channel UHJ can accurately\n"
366 "reconstruct the original B-Format signal.",
371 size_t num_files
{0}, num_decoded
{0};
372 bool use_general
{true};
373 for(int fidx
{1};fidx
< argc
;++fidx
)
375 if(std::strcmp(argv
[fidx
], "--general") == 0)
380 if(std::strcmp(argv
[fidx
], "--alternative") == 0)
387 SndFilePtr infile
{sf_open(argv
[fidx
], SFM_READ
, &ininfo
)};
390 fprintf(stderr
, "Failed to open %s\n", argv
[fidx
]);
393 if(sf_command(infile
.get(), SFC_WAVEX_GET_AMBISONIC
, NULL
, 0) == SF_AMBISONIC_B_FORMAT
)
395 fprintf(stderr
, "%s is already B-Format\n", argv
[fidx
]);
399 if(ininfo
.channels
== 2)
401 else if(ininfo
.channels
== 3 || ininfo
.channels
== 4)
402 outchans
= static_cast<uint
>(ininfo
.channels
);
405 fprintf(stderr
, "%s is not a 2-, 3-, or 4-channel file\n", argv
[fidx
]);
408 printf("Converting %s from %d-channel UHJ%s...\n", argv
[fidx
], ininfo
.channels
,
409 (ininfo
.channels
== 2) ? use_general
? " (general)" : " (alternative)" : "");
411 std::string outname
{argv
[fidx
]};
412 auto lastslash
= outname
.find_last_of('/');
413 if(lastslash
!= std::string::npos
)
414 outname
.erase(0, lastslash
+1);
415 auto lastdot
= outname
.find_last_of('.');
416 if(lastdot
!= std::string::npos
)
417 outname
.resize(lastdot
+1);
420 FilePtr outfile
{fopen(outname
.c_str(), "wb")};
423 fprintf(stderr
, "Failed to create %s\n", outname
.c_str());
427 fputs("RIFF", outfile
.get());
428 fwrite32le(0xFFFFFFFF, outfile
.get()); // 'RIFF' header len; filled in at close
430 fputs("WAVE", outfile
.get());
432 fputs("fmt ", outfile
.get());
433 fwrite32le(40, outfile
.get()); // 'fmt ' header len; 40 bytes for EXTENSIBLE
435 // 16-bit val, format type id (extensible: 0xFFFE)
436 fwrite16le(0xFFFE, outfile
.get());
437 // 16-bit val, channel count
438 fwrite16le(static_cast<ushort
>(outchans
), outfile
.get());
439 // 32-bit val, frequency
440 fwrite32le(static_cast<uint
>(ininfo
.samplerate
), outfile
.get());
441 // 32-bit val, bytes per second
442 fwrite32le(static_cast<uint
>(ininfo
.samplerate
)*sizeof(float)*outchans
, outfile
.get());
443 // 16-bit val, frame size
444 fwrite16le(static_cast<ushort
>(sizeof(float)*outchans
), outfile
.get());
445 // 16-bit val, bits per sample
446 fwrite16le(static_cast<ushort
>(sizeof(float)*8), outfile
.get());
447 // 16-bit val, extra byte count
448 fwrite16le(22, outfile
.get());
449 // 16-bit val, valid bits per sample
450 fwrite16le(static_cast<ushort
>(sizeof(float)*8), outfile
.get());
451 // 32-bit val, channel mask
452 fwrite32le(0, outfile
.get());
453 // 16 byte GUID, sub-type format
454 fwrite(SUBTYPE_BFORMAT_FLOAT
, 1, 16, outfile
.get());
456 fputs("data", outfile
.get());
457 fwrite32le(0xFFFFFFFF, outfile
.get()); // 'data' header len; filled in at close
458 if(ferror(outfile
.get()))
460 fprintf(stderr
, "Error writing wave file header: %s (%d)\n", strerror(errno
), errno
);
464 auto DataStart
= ftell(outfile
.get());
466 auto decoder
= std::make_unique
<UhjDecoder
>();
467 auto inmem
= std::make_unique
<float[]>(BufferLineSize
*static_cast<uint
>(ininfo
.channels
));
468 auto decmem
= al::vector
<std::array
<float,BufferLineSize
>, 16>(outchans
);
469 auto outmem
= std::make_unique
<byte4
[]>(BufferLineSize
*outchans
);
471 /* A number of initial samples need to be skipped to cut the lead-in
472 * from the all-pass filter delay. The same number of samples need to
473 * be fed through the decoder after reaching the end of the input file
474 * to ensure none of the original input is lost.
476 size_t LeadIn
{UhjDecoder::sFilterDelay
};
477 sf_count_t LeadOut
{UhjDecoder::sFilterDelay
};
480 sf_count_t sgot
{sf_readf_float(infile
.get(), inmem
.get(), BufferLineSize
)};
481 sgot
= std::max
<sf_count_t
>(sgot
, 0);
482 if(sgot
< BufferLineSize
)
484 const sf_count_t remaining
{std::min(BufferLineSize
- sgot
, LeadOut
)};
485 std::fill_n(inmem
.get() + sgot
*ininfo
.channels
, remaining
*ininfo
.channels
, 0.0f
);
487 LeadOut
-= remaining
;
490 auto got
= static_cast<size_t>(sgot
);
491 if(ininfo
.channels
> 2 || use_general
)
492 decoder
->decode(inmem
.get(), static_cast<uint
>(ininfo
.channels
), decmem
, got
);
494 decoder
->decode2(inmem
.get(), decmem
, got
);
502 for(size_t i
{0};i
< got
;++i
)
504 /* Attenuate by -3dB for FuMa output levels. */
505 constexpr auto inv_sqrt2
= static_cast<float>(1.0/al::numbers::sqrt2
);
506 for(size_t j
{0};j
< outchans
;++j
)
507 outmem
[i
*outchans
+ j
] = f32AsLEBytes(decmem
[j
][LeadIn
+i
] * inv_sqrt2
);
511 size_t wrote
{fwrite(outmem
.get(), sizeof(byte4
)*outchans
, got
, outfile
.get())};
514 fprintf(stderr
, "Error writing wave data: %s (%d)\n", strerror(errno
), errno
);
519 auto DataEnd
= ftell(outfile
.get());
520 if(DataEnd
> DataStart
)
522 long dataLen
{DataEnd
- DataStart
};
523 if(fseek(outfile
.get(), 4, SEEK_SET
) == 0)
524 fwrite32le(static_cast<uint
>(DataEnd
-8), outfile
.get()); // 'WAVE' header len
525 if(fseek(outfile
.get(), DataStart
-4, SEEK_SET
) == 0)
526 fwrite32le(static_cast<uint
>(dataLen
), outfile
.get()); // 'data' header len
528 fflush(outfile
.get());
532 fprintf(stderr
, "Failed to decode any input files\n");
533 else if(num_decoded
< num_files
)
534 fprintf(stderr
, "Decoded %zu of %zu files\n", num_decoded
, num_files
);
536 printf("Decoded %zu file%s\n", num_decoded
, (num_decoded
==1)?"":"s");