using EvilEngine.Music.Aac; using EvilEngine.Music.Alac; using EvilEngine.Music.Files; using EvilEngine.Music.Flac; using EvilEngine.Music.Opus; namespace EvilEngine.Music.Decoding; public interface IPcmSource : IDisposable { int SampleRate { get; } int Channels { get; } long TotalFrames { get; } long Position { get; } int Read(Span interleaved); void Seek(long frame); } public enum PlayPath { None, Native, Decoded } public static class Decoders { public static PlayPath How(TrackInfo info) { return (info.Codec, info.Container) switch { (AudioCodec.Mp3, AudioContainer.Mpeg) => PlayPath.Native, (AudioCodec.Vorbis, AudioContainer.Ogg) => PlayPath.Native, (AudioCodec.Flac, AudioContainer.Flac) => PlayPath.Decoded, (AudioCodec.Pcm or AudioCodec.Float, AudioContainer.Wave or AudioContainer.Aiff) => PlayPath.Decoded, (AudioCodec.Alac, AudioContainer.Mp4) => PlayPath.Decoded, (AudioCodec.Aac, AudioContainer.Mp4 or AudioContainer.Adts) => PlayPath.Decoded, (AudioCodec.Opus, AudioContainer.Ogg or AudioContainer.Mp4) => PlayPath.Decoded, _ => PlayPath.None }; } public static IPcmSource Open(string path) { return Open(AudioFile.Open(path), Path.GetFileName(path)); } public static IPcmSource Open(Stream stream, string name) { try { Span head = stackalloc byte[4]; stream.ReadExactly(head); stream.Position = 0; if (head.SequenceEqual("OggS"u8)) { var ogg = OggOpusStream.Open(stream); return Source(ogg, () => new OpusDecoder(ogg.Head)); } if (head.SequenceEqual("fLaC"u8) || (head[..3].SequenceEqual("ID3"u8) && FlacAfterTags(stream))) return new FlacDecoder(stream); if (AudioFile.Pcm(stream) is { } layout) return new PcmDecoder(stream, layout); if (Mp4Atoms.IsMp4(Head(stream))) return Mp4(Mp4Track.Open(stream)); if (AdtsStream.Info(stream) is not null) { var adts = AdtsStream.Open(stream); return Source(adts, () => new AacDecoder(adts.Config)); } throw new InvalidDataException($"{name} isn't a stream the engine decodes."); } catch { stream.Dispose(); throw; } } private static bool FlacAfterTags(Stream stream) { stream.Position = 0; Id3v2.Skip(stream); Span magic = stackalloc byte[4]; var flac = Bytes.ReadAtMost(stream, magic) == 4 && magic.SequenceEqual("fLaC"u8); stream.Position = 0; return flac; } private static byte[] Head(Stream stream) { var head = new byte[12]; stream.Position = 0; var read = Bytes.ReadAtMost(stream, head); stream.Position = 0; return head[..read]; } private static PacketSource Mp4(Mp4Track track) { return Source(track, () => track.Format switch { "alac" => new AlacDecoder(track.Config), "Opus" => new OpusDecoder(track.Config), "mp4a" when track.ObjectType is 0x40 or 0x66 or 0x67 => new AacDecoder(track.Config), _ => throw new InvalidDataException($"MP4 audio in {track.Format} isn't a codec the engine decodes.") }); } private static PacketSource Source(IPacketStream packets, Func decoder) { try { return new PacketSource(packets, decoder()); } catch { packets.Dispose(); throw; } } }