From a31b0becf15314553fc865514812517862cfcb96 Mon Sep 17 00:00:00 2001 From: Pavel Penev Date: Thu, 19 Nov 2015 00:28:04 +0200 Subject: [PATCH] Make AudLoader implement ISoundLoader --- OpenRA.Game/FileFormats/AudLoader.cs | 49 ++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/OpenRA.Game/FileFormats/AudLoader.cs b/OpenRA.Game/FileFormats/AudLoader.cs index a2d7579463..7896a754d0 100644 --- a/OpenRA.Game/FileFormats/AudLoader.cs +++ b/OpenRA.Game/FileFormats/AudLoader.cs @@ -36,16 +36,18 @@ namespace OpenRA.FileFormats Chunk c; c.CompressedSize = s.ReadUInt16(); c.OutputSize = s.ReadUInt16(); + if (s.ReadUInt32() != 0xdeaf) throw new InvalidDataException("Chunk header is bogus"); return c; } } - public static class AudLoader + public class AudLoader : ISoundLoader { - static int[] indexAdjust = { -1, -1, -1, -1, 2, 4, 6, 8 }; - static int[] stepTable = + static readonly int ExpectedSampleRate = 22050; + static readonly int[] IndexAdjust = { -1, -1, -1, -1, 2, 4, 6, 8 }; + static readonly int[] StepTable = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, @@ -64,14 +66,14 @@ namespace OpenRA.FileFormats var sb = (b & 8) != 0; b &= 7; - var delta = (stepTable[index] * b) / 4 + stepTable[index] / 8; + var delta = (StepTable[index] * b) / 4 + StepTable[index] / 8; if (sb) delta = -delta; current += delta; if (current > short.MaxValue) current = short.MaxValue; if (current < short.MinValue) current = short.MinValue; - index += indexAdjust[b]; + index += IndexAdjust[b]; if (index < 0) index = 0; if (index > 88) index = 88; @@ -117,13 +119,24 @@ namespace OpenRA.FileFormats return samples / sampleRate; } - public static byte[] LoadSound(Stream s) + public static bool LoadSound(Stream s, out byte[] rawData) { - /*var sampleRate =*/ s.ReadUInt16(); + rawData = null; + + var sampleRate = s.ReadUInt16(); var dataSize = s.ReadInt32(); var outputSize = s.ReadInt32(); - /*var flags = (SoundFlags)*/ s.ReadByte(); - /*var format = (SoundFormat)*/ s.ReadByte(); + var readFlag = s.ReadByte(); + var readFormat = s.ReadByte(); + + if (sampleRate != ExpectedSampleRate) + return false; + + if (!Enum.IsDefined(typeof(SoundFlags), readFlag)) + return false; + + if (!Enum.IsDefined(typeof(SoundFormat), readFormat)) + return false; var output = new byte[outputSize]; var offset = 0; @@ -153,7 +166,23 @@ namespace OpenRA.FileFormats dataSize -= 8 + chunk.CompressedSize; } - return output; + rawData = output; + return true; + } + + public bool TryParseSound(Stream stream, string fileName, out byte[] rawData, out int channels, out int sampleBits, + out int sampleRate) + { + channels = sampleBits = sampleRate = 0; + + if (!LoadSound(stream, out rawData)) + return false; + + channels = 1; + sampleBits = 16; + sampleRate = ExpectedSampleRate; + + return true; } } }