🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

507 lines
20 KiB

  1. /*
  2. * 2-channel UHJ Encoder
  3. *
  4. * Copyright (c) Chris Robinson <chris.kcat@gmail.com>
  5. *
  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:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  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
  22. * THE SOFTWARE.
  23. */
  24. #include "config.h"
  25. #include <array>
  26. #include <cstring>
  27. #include <inttypes.h>
  28. #include <memory>
  29. #include <stddef.h>
  30. #include <string>
  31. #include <utility>
  32. #include <vector>
  33. #include "almalloc.h"
  34. #include "alnumbers.h"
  35. #include "alspan.h"
  36. #include "opthelpers.h"
  37. #include "phase_shifter.h"
  38. #include "vector.h"
  39. #include "sndfile.h"
  40. #include "win_main_utf8.h"
  41. namespace {
  42. struct SndFileDeleter {
  43. void operator()(SNDFILE *sndfile) { sf_close(sndfile); }
  44. };
  45. using SndFilePtr = std::unique_ptr<SNDFILE,SndFileDeleter>;
  46. using uint = unsigned int;
  47. constexpr uint BufferLineSize{1024};
  48. using FloatBufferLine = std::array<float,BufferLineSize>;
  49. using FloatBufferSpan = al::span<float,BufferLineSize>;
  50. struct UhjEncoder {
  51. constexpr static size_t sFilterDelay{1024};
  52. /* Delays and processing storage for the unfiltered signal. */
  53. alignas(16) std::array<float,BufferLineSize+sFilterDelay> mS{};
  54. alignas(16) std::array<float,BufferLineSize+sFilterDelay> mD{};
  55. alignas(16) std::array<float,BufferLineSize+sFilterDelay> mT{};
  56. alignas(16) std::array<float,BufferLineSize+sFilterDelay> mQ{};
  57. /* History for the FIR filter. */
  58. alignas(16) std::array<float,sFilterDelay*2 - 1> mWXHistory1{};
  59. alignas(16) std::array<float,sFilterDelay*2 - 1> mWXHistory2{};
  60. alignas(16) std::array<float,BufferLineSize + sFilterDelay*2> mTemp{};
  61. void encode(const al::span<FloatBufferLine> OutSamples,
  62. const al::span<FloatBufferLine,4> InSamples, const size_t SamplesToDo);
  63. DEF_NEWDEL(UhjEncoder)
  64. };
  65. const PhaseShifterT<UhjEncoder::sFilterDelay*2> PShift{};
  66. /* Encoding UHJ from B-Format is done as:
  67. *
  68. * S = 0.9396926*W + 0.1855740*X
  69. * D = j(-0.3420201*W + 0.5098604*X) + 0.6554516*Y
  70. *
  71. * Left = (S + D)/2.0
  72. * Right = (S - D)/2.0
  73. * T = j(-0.1432*W + 0.6512*X) - 0.7071068*Y
  74. * Q = 0.9772*Z
  75. *
  76. * where j is a wide-band +90 degree phase shift. T is excluded from 2-channel
  77. * output, and Q is excluded from 2- and 3-channel output.
  78. */
  79. void UhjEncoder::encode(const al::span<FloatBufferLine> OutSamples,
  80. const al::span<FloatBufferLine,4> InSamples, const size_t SamplesToDo)
  81. {
  82. const float *RESTRICT winput{al::assume_aligned<16>(InSamples[0].data())};
  83. const float *RESTRICT xinput{al::assume_aligned<16>(InSamples[1].data())};
  84. const float *RESTRICT yinput{al::assume_aligned<16>(InSamples[2].data())};
  85. const float *RESTRICT zinput{al::assume_aligned<16>(InSamples[3].data())};
  86. /* Combine the previously delayed S/D signal with the input. */
  87. /* S = 0.9396926*W + 0.1855740*X */
  88. auto miditer = mS.begin() + sFilterDelay;
  89. std::transform(winput, winput+SamplesToDo, xinput, miditer,
  90. [](const float w, const float x) noexcept -> float
  91. { return 0.9396926f*w + 0.1855740f*x; });
  92. /* D = 0.6554516*Y */
  93. auto sideiter = mD.begin() + sFilterDelay;
  94. std::transform(yinput, yinput+SamplesToDo, sideiter,
  95. [](const float y) noexcept -> float { return 0.6554516f*y; });
  96. /* D += j(-0.3420201*W + 0.5098604*X) */
  97. auto tmpiter = std::copy(mWXHistory1.cbegin(), mWXHistory1.cend(), mTemp.begin());
  98. std::transform(winput, winput+SamplesToDo, xinput, tmpiter,
  99. [](const float w, const float x) noexcept -> float
  100. { return -0.3420201f*w + 0.5098604f*x; });
  101. std::copy_n(mTemp.cbegin()+SamplesToDo, mWXHistory1.size(), mWXHistory1.begin());
  102. PShift.processAccum({mD.data(), SamplesToDo}, mTemp.data());
  103. /* Left = (S + D)/2.0 */
  104. float *RESTRICT left{al::assume_aligned<16>(OutSamples[0].data())};
  105. for(size_t i{0};i < SamplesToDo;i++)
  106. left[i] = (mS[i] + mD[i]) * 0.5f;
  107. /* Right = (S - D)/2.0 */
  108. float *RESTRICT right{al::assume_aligned<16>(OutSamples[1].data())};
  109. for(size_t i{0};i < SamplesToDo;i++)
  110. right[i] = (mS[i] - mD[i]) * 0.5f;
  111. if(OutSamples.size() > 2)
  112. {
  113. /* T = -0.7071068*Y */
  114. sideiter = mT.begin() + sFilterDelay;
  115. std::transform(yinput, yinput+SamplesToDo, sideiter,
  116. [](const float y) noexcept -> float { return -0.7071068f*y; });
  117. /* T += j(-0.1432*W + 0.6512*X) */
  118. tmpiter = std::copy(mWXHistory2.cbegin(), mWXHistory2.cend(), mTemp.begin());
  119. std::transform(winput, winput+SamplesToDo, xinput, tmpiter,
  120. [](const float w, const float x) noexcept -> float
  121. { return -0.1432f*w + 0.6512f*x; });
  122. std::copy_n(mTemp.cbegin()+SamplesToDo, mWXHistory2.size(), mWXHistory2.begin());
  123. PShift.processAccum({mT.data(), SamplesToDo}, mTemp.data());
  124. float *RESTRICT t{al::assume_aligned<16>(OutSamples[2].data())};
  125. for(size_t i{0};i < SamplesToDo;i++)
  126. t[i] = mT[i];
  127. }
  128. if(OutSamples.size() > 3)
  129. {
  130. /* Q = 0.9772*Z */
  131. sideiter = mQ.begin() + sFilterDelay;
  132. std::transform(zinput, zinput+SamplesToDo, sideiter,
  133. [](const float z) noexcept -> float { return 0.9772f*z; });
  134. float *RESTRICT q{al::assume_aligned<16>(OutSamples[3].data())};
  135. for(size_t i{0};i < SamplesToDo;i++)
  136. q[i] = mQ[i];
  137. }
  138. /* Copy the future samples to the front for next time. */
  139. std::copy(mS.cbegin()+SamplesToDo, mS.cbegin()+SamplesToDo+sFilterDelay, mS.begin());
  140. std::copy(mD.cbegin()+SamplesToDo, mD.cbegin()+SamplesToDo+sFilterDelay, mD.begin());
  141. std::copy(mT.cbegin()+SamplesToDo, mT.cbegin()+SamplesToDo+sFilterDelay, mT.begin());
  142. std::copy(mQ.cbegin()+SamplesToDo, mQ.cbegin()+SamplesToDo+sFilterDelay, mQ.begin());
  143. }
  144. struct SpeakerPos {
  145. int mChannelID;
  146. float mAzimuth;
  147. float mElevation;
  148. };
  149. /* Azimuth is counter-clockwise. */
  150. constexpr SpeakerPos StereoMap[2]{
  151. { SF_CHANNEL_MAP_LEFT, 30.0f, 0.0f },
  152. { SF_CHANNEL_MAP_RIGHT, -30.0f, 0.0f },
  153. }, QuadMap[4]{
  154. { SF_CHANNEL_MAP_LEFT, 45.0f, 0.0f },
  155. { SF_CHANNEL_MAP_RIGHT, -45.0f, 0.0f },
  156. { SF_CHANNEL_MAP_REAR_LEFT, 135.0f, 0.0f },
  157. { SF_CHANNEL_MAP_REAR_RIGHT, -135.0f, 0.0f },
  158. }, X51Map[6]{
  159. { SF_CHANNEL_MAP_LEFT, 30.0f, 0.0f },
  160. { SF_CHANNEL_MAP_RIGHT, -30.0f, 0.0f },
  161. { SF_CHANNEL_MAP_CENTER, 0.0f, 0.0f },
  162. { SF_CHANNEL_MAP_LFE, 0.0f, 0.0f },
  163. { SF_CHANNEL_MAP_SIDE_LEFT, 110.0f, 0.0f },
  164. { SF_CHANNEL_MAP_SIDE_RIGHT, -110.0f, 0.0f },
  165. }, X51RearMap[6]{
  166. { SF_CHANNEL_MAP_LEFT, 30.0f, 0.0f },
  167. { SF_CHANNEL_MAP_RIGHT, -30.0f, 0.0f },
  168. { SF_CHANNEL_MAP_CENTER, 0.0f, 0.0f },
  169. { SF_CHANNEL_MAP_LFE, 0.0f, 0.0f },
  170. { SF_CHANNEL_MAP_REAR_LEFT, 110.0f, 0.0f },
  171. { SF_CHANNEL_MAP_REAR_RIGHT, -110.0f, 0.0f },
  172. }, X71Map[8]{
  173. { SF_CHANNEL_MAP_LEFT, 30.0f, 0.0f },
  174. { SF_CHANNEL_MAP_RIGHT, -30.0f, 0.0f },
  175. { SF_CHANNEL_MAP_CENTER, 0.0f, 0.0f },
  176. { SF_CHANNEL_MAP_LFE, 0.0f, 0.0f },
  177. { SF_CHANNEL_MAP_REAR_LEFT, 150.0f, 0.0f },
  178. { SF_CHANNEL_MAP_REAR_RIGHT, -150.0f, 0.0f },
  179. { SF_CHANNEL_MAP_SIDE_LEFT, 90.0f, 0.0f },
  180. { SF_CHANNEL_MAP_SIDE_RIGHT, -90.0f, 0.0f },
  181. }, X714Map[12]{
  182. { SF_CHANNEL_MAP_LEFT, 30.0f, 0.0f },
  183. { SF_CHANNEL_MAP_RIGHT, -30.0f, 0.0f },
  184. { SF_CHANNEL_MAP_CENTER, 0.0f, 0.0f },
  185. { SF_CHANNEL_MAP_LFE, 0.0f, 0.0f },
  186. { SF_CHANNEL_MAP_REAR_LEFT, 150.0f, 0.0f },
  187. { SF_CHANNEL_MAP_REAR_RIGHT, -150.0f, 0.0f },
  188. { SF_CHANNEL_MAP_SIDE_LEFT, 90.0f, 0.0f },
  189. { SF_CHANNEL_MAP_SIDE_RIGHT, -90.0f, 0.0f },
  190. { SF_CHANNEL_MAP_TOP_FRONT_LEFT, 45.0f, 35.0f },
  191. { SF_CHANNEL_MAP_TOP_FRONT_RIGHT, -45.0f, 35.0f },
  192. { SF_CHANNEL_MAP_TOP_REAR_LEFT, 135.0f, 35.0f },
  193. { SF_CHANNEL_MAP_TOP_REAR_RIGHT, -135.0f, 35.0f },
  194. };
  195. constexpr auto GenCoeffs(double x /*+front*/, double y /*+left*/, double z /*+up*/) noexcept
  196. {
  197. /* Coefficients are +3dB of FuMa. */
  198. return std::array<float,4>{{
  199. 1.0f,
  200. static_cast<float>(al::numbers::sqrt2 * x),
  201. static_cast<float>(al::numbers::sqrt2 * y),
  202. static_cast<float>(al::numbers::sqrt2 * z)
  203. }};
  204. }
  205. } // namespace
  206. int main(int argc, char **argv)
  207. {
  208. if(argc < 2 || std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0)
  209. {
  210. printf("Usage: %s <infile...>\n\n", argv[0]);
  211. return 1;
  212. }
  213. uint uhjchans{2};
  214. size_t num_files{0}, num_encoded{0};
  215. for(int fidx{1};fidx < argc;++fidx)
  216. {
  217. if(strcmp(argv[fidx], "-bhj") == 0)
  218. {
  219. uhjchans = 2;
  220. continue;
  221. }
  222. if(strcmp(argv[fidx], "-thj") == 0)
  223. {
  224. uhjchans = 3;
  225. continue;
  226. }
  227. if(strcmp(argv[fidx], "-phj") == 0)
  228. {
  229. uhjchans = 4;
  230. continue;
  231. }
  232. ++num_files;
  233. std::string outname{argv[fidx]};
  234. size_t lastslash{outname.find_last_of('/')};
  235. if(lastslash != std::string::npos)
  236. outname.erase(0, lastslash+1);
  237. size_t extpos{outname.find_last_of('.')};
  238. if(extpos != std::string::npos)
  239. outname.resize(extpos);
  240. outname += ".uhj.flac";
  241. SF_INFO ininfo{};
  242. SndFilePtr infile{sf_open(argv[fidx], SFM_READ, &ininfo)};
  243. if(!infile)
  244. {
  245. fprintf(stderr, "Failed to open %s\n", argv[fidx]);
  246. continue;
  247. }
  248. printf("Converting %s to %s...\n", argv[fidx], outname.c_str());
  249. /* Work out the channel map, preferably using the actual channel map
  250. * from the file/format, but falling back to assuming WFX order.
  251. *
  252. * TODO: Map indices when the channel order differs from the virtual
  253. * speaker position maps.
  254. */
  255. al::span<const SpeakerPos> spkrs;
  256. auto chanmap = std::vector<int>(static_cast<uint>(ininfo.channels), SF_CHANNEL_MAP_INVALID);
  257. if(sf_command(infile.get(), SFC_GET_CHANNEL_MAP_INFO, chanmap.data(),
  258. ininfo.channels*int{sizeof(int)}) == SF_TRUE)
  259. {
  260. static const std::array<int,2> stereomap{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT}};
  261. static const std::array<int,4> quadmap{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT,
  262. SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT}};
  263. static const std::array<int,6> x51map{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT,
  264. SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE,
  265. SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT}};
  266. static const std::array<int,6> x51rearmap{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT,
  267. SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE,
  268. SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT}};
  269. static const std::array<int,8> x71map{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT,
  270. SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE,
  271. SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT,
  272. SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT}};
  273. static const std::array<int,12> x714map{{SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT,
  274. SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE,
  275. SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT,
  276. SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT,
  277. SF_CHANNEL_MAP_TOP_FRONT_LEFT, SF_CHANNEL_MAP_TOP_FRONT_RIGHT,
  278. SF_CHANNEL_MAP_TOP_REAR_LEFT, SF_CHANNEL_MAP_TOP_REAR_RIGHT}};
  279. static const std::array<int,3> ambi2dmap{{SF_CHANNEL_MAP_AMBISONIC_B_W,
  280. SF_CHANNEL_MAP_AMBISONIC_B_X, SF_CHANNEL_MAP_AMBISONIC_B_Y}};
  281. static const std::array<int,4> ambi3dmap{{SF_CHANNEL_MAP_AMBISONIC_B_W,
  282. SF_CHANNEL_MAP_AMBISONIC_B_X, SF_CHANNEL_MAP_AMBISONIC_B_Y,
  283. SF_CHANNEL_MAP_AMBISONIC_B_Z}};
  284. auto match_chanmap = [](const al::span<int> a, const al::span<const int> b) -> bool
  285. {
  286. return a.size() == b.size()
  287. && std::mismatch(a.begin(), a.end(), b.begin(), b.end()).first == a.end();
  288. };
  289. if(match_chanmap(chanmap, stereomap))
  290. spkrs = StereoMap;
  291. else if(match_chanmap(chanmap, quadmap))
  292. spkrs = QuadMap;
  293. else if(match_chanmap(chanmap, x51map))
  294. spkrs = X51Map;
  295. else if(match_chanmap(chanmap, x51rearmap))
  296. spkrs = X51RearMap;
  297. else if(match_chanmap(chanmap, x71map))
  298. spkrs = X71Map;
  299. else if(match_chanmap(chanmap, x714map))
  300. spkrs = X714Map;
  301. else if(match_chanmap(chanmap, ambi2dmap) || match_chanmap(chanmap, ambi3dmap))
  302. {
  303. /* Do nothing. */
  304. }
  305. else
  306. {
  307. std::string mapstr;
  308. if(chanmap.size() > 0)
  309. {
  310. mapstr = std::to_string(chanmap[0]);
  311. for(int idx : al::span<int>{chanmap}.subspan<1>())
  312. {
  313. mapstr += ',';
  314. mapstr += std::to_string(idx);
  315. }
  316. }
  317. fprintf(stderr, " ... %zu channels not supported (map: %s)\n", chanmap.size(),
  318. mapstr.c_str());
  319. continue;
  320. }
  321. }
  322. else if(ininfo.channels == 2)
  323. {
  324. fprintf(stderr, " ... assuming WFX order stereo\n");
  325. spkrs = StereoMap;
  326. }
  327. else if(ininfo.channels == 6)
  328. {
  329. fprintf(stderr, " ... assuming WFX order 5.1\n");
  330. spkrs = X51Map;
  331. }
  332. else if(ininfo.channels == 8)
  333. {
  334. fprintf(stderr, " ... assuming WFX order 7.1\n");
  335. spkrs = X71Map;
  336. }
  337. else
  338. {
  339. fprintf(stderr, " ... unmapped %d-channel audio not supported\n", ininfo.channels);
  340. continue;
  341. }
  342. SF_INFO outinfo{};
  343. outinfo.frames = ininfo.frames;
  344. outinfo.samplerate = ininfo.samplerate;
  345. outinfo.channels = static_cast<int>(uhjchans);
  346. outinfo.format = SF_FORMAT_PCM_24 | SF_FORMAT_FLAC;
  347. SndFilePtr outfile{sf_open(outname.c_str(), SFM_WRITE, &outinfo)};
  348. if(!outfile)
  349. {
  350. fprintf(stderr, " ... failed to create %s\n", outname.c_str());
  351. continue;
  352. }
  353. auto encoder = std::make_unique<UhjEncoder>();
  354. auto splbuf = al::vector<FloatBufferLine, 16>(static_cast<uint>(9+ininfo.channels)+uhjchans);
  355. auto ambmem = al::span<FloatBufferLine,4>{&splbuf[0], 4};
  356. auto encmem = al::span<FloatBufferLine,4>{&splbuf[4], 4};
  357. auto srcmem = al::span<float,BufferLineSize>{splbuf[8].data(), BufferLineSize};
  358. auto outmem = al::span<float>{splbuf[9].data(), BufferLineSize*uhjchans};
  359. /* A number of initial samples need to be skipped to cut the lead-in
  360. * from the all-pass filter delay. The same number of samples need to
  361. * be fed through the encoder after reaching the end of the input file
  362. * to ensure none of the original input is lost.
  363. */
  364. size_t total_wrote{0};
  365. size_t LeadIn{UhjEncoder::sFilterDelay};
  366. sf_count_t LeadOut{UhjEncoder::sFilterDelay};
  367. while(LeadIn > 0 || LeadOut > 0)
  368. {
  369. auto inmem = outmem.data() + outmem.size();
  370. auto sgot = sf_readf_float(infile.get(), inmem, BufferLineSize);
  371. sgot = std::max<sf_count_t>(sgot, 0);
  372. if(sgot < BufferLineSize)
  373. {
  374. const sf_count_t remaining{std::min(BufferLineSize - sgot, LeadOut)};
  375. std::fill_n(inmem + sgot*ininfo.channels, remaining*ininfo.channels, 0.0f);
  376. sgot += remaining;
  377. LeadOut -= remaining;
  378. }
  379. for(auto&& buf : ambmem)
  380. buf.fill(0.0f);
  381. auto got = static_cast<size_t>(sgot);
  382. if(spkrs.empty())
  383. {
  384. /* B-Format is already in the correct order. It just needs a
  385. * +3dB boost.
  386. */
  387. constexpr float scale{al::numbers::sqrt2_v<float>};
  388. const size_t chans{std::min<size_t>(static_cast<uint>(ininfo.channels), 4u)};
  389. for(size_t c{0};c < chans;++c)
  390. {
  391. for(size_t i{0};i < got;++i)
  392. ambmem[c][i] = inmem[i*static_cast<uint>(ininfo.channels)] * scale;
  393. ++inmem;
  394. }
  395. }
  396. else for(auto&& spkr : spkrs)
  397. {
  398. /* Skip LFE. Or mix directly into W? Or W+X? */
  399. if(spkr.mChannelID == SF_CHANNEL_MAP_LFE)
  400. {
  401. ++inmem;
  402. continue;
  403. }
  404. for(size_t i{0};i < got;++i)
  405. srcmem[i] = inmem[i * static_cast<uint>(ininfo.channels)];
  406. ++inmem;
  407. constexpr auto Deg2Rad = al::numbers::pi / 180.0;
  408. const auto coeffs = GenCoeffs(
  409. std::cos(spkr.mAzimuth*Deg2Rad) * std::cos(spkr.mElevation*Deg2Rad),
  410. std::sin(spkr.mAzimuth*Deg2Rad) * std::cos(spkr.mElevation*Deg2Rad),
  411. std::sin(spkr.mElevation*Deg2Rad));
  412. for(size_t c{0};c < 4;++c)
  413. {
  414. for(size_t i{0};i < got;++i)
  415. ambmem[c][i] += srcmem[i] * coeffs[c];
  416. }
  417. }
  418. encoder->encode(encmem.subspan(0, uhjchans), ambmem, got);
  419. if(LeadIn >= got)
  420. {
  421. LeadIn -= got;
  422. continue;
  423. }
  424. got -= LeadIn;
  425. for(size_t c{0};c < uhjchans;++c)
  426. {
  427. constexpr float max_val{8388607.0f / 8388608.0f};
  428. auto clamp = [](float v, float mn, float mx) noexcept
  429. { return std::min(std::max(v, mn), mx); };
  430. for(size_t i{0};i < got;++i)
  431. outmem[i*uhjchans + c] = clamp(encmem[c][LeadIn+i], -1.0f, max_val);
  432. }
  433. LeadIn = 0;
  434. sf_count_t wrote{sf_writef_float(outfile.get(), outmem.data(),
  435. static_cast<sf_count_t>(got))};
  436. if(wrote < 0)
  437. fprintf(stderr, " ... failed to write samples: %d\n", sf_error(outfile.get()));
  438. else
  439. total_wrote += static_cast<size_t>(wrote);
  440. }
  441. printf(" ... wrote %zu samples (%" PRId64 ").\n", total_wrote, int64_t{ininfo.frames});
  442. ++num_encoded;
  443. }
  444. if(num_encoded == 0)
  445. fprintf(stderr, "Failed to encode any input files\n");
  446. else if(num_encoded < num_files)
  447. fprintf(stderr, "Encoded %zu of %zu files\n", num_encoded, num_files);
  448. else
  449. printf("Encoded %s%zu file%s\n", (num_encoded > 1) ? "all " : "", num_encoded,
  450. (num_encoded == 1) ? "" : "s");
  451. return 0;
  452. }