fix: correct WAV RIFF length and padding (#1032)

* fix: correct WAV RIFF length and padding

Include the PCM payload in the RIFF chunk size and pad odd-length data chunks. Add regression coverage for empty, odd, even and larger payloads.

* chore: add comment explaning the wav padding byte

---------

Co-authored-by: Jan Laupetin <[email protected]>
This commit is contained in:
moandJan Laupetin authored and GitHub committed 2026-10-18 20:58:11 +02:00
1 parent 30d2d498bd
commit e95805bce4
2 files changed
+47 -2

No files matched your search

+7 -2
View File
@@ -7,8 +7,8 @@ WavWriter::WavWriter(std::ostream& stream)
void WavWriter::WritePcmHeader(const WavMetaData& metaData, const size_t dataLen) const
{
constexpr auto riffMasterChunkSize = static_cast<uint32_t>(sizeof(WAV_CHUNK_ID_RIFF) + sizeof(uint32_t) + sizeof(WAV_WAVE_ID) + sizeof(WavChunkHeader)
+ sizeof(WavFormatChunkPcm) + sizeof(WavChunkHeader) + sizeof(uint32_t));
const auto riffMasterChunkSize =
static_cast<uint32_t>(sizeof(WAV_WAVE_ID) + sizeof(WavChunkHeader) + sizeof(WavFormatChunkPcm) + sizeof(WavChunkHeader) + dataLen + (dataLen & 1u));
m_stream.write(reinterpret_cast<const char*>(&WAV_CHUNK_ID_RIFF), sizeof(WAV_CHUNK_ID_RIFF));
m_stream.write(reinterpret_cast<const char*>(&riffMasterChunkSize), sizeof(riffMasterChunkSize));
@@ -34,4 +34,9 @@ void WavWriter::WritePcmHeader(const WavMetaData& metaData, const size_t dataLen
void WavWriter::WritePcmData(const void* data, const size_t dataLen) const
{
m_stream.write(static_cast<const char*>(data), static_cast<std::streamsize>(dataLen));
// > The data is always padded to the nearest WORD boundary.
// https://learn.microsoft.com/en-us/windows/win32/xaudio2/resource-interchange-file-format--riff-#chunks
if (dataLen & 1u)
m_stream.put('\0');
}