using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; namespace EvilEngine.Music.Files; public static class OggPages { private const int MaxPacket = 64 << 20; public static bool Read(Stream stream, TagReading reading, out TrackInfo info) { info = new TrackInfo(); stream.Position = 0; var packets = new PacketReader(stream); if (packets.Next() is not { } first) return false; var serial = packets.Serial; TrackInfo found; var preSkip = 0; if (first.Length >= 30 && first[0] == 1 && first.AsSpan(1, 6).SequenceEqual("vorbis"u8)) { found = new TrackInfo { Codec = AudioCodec.Vorbis, Channels = first[11], SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian(first.AsSpan(12)), Bitrate = BinaryPrimitives.ReadInt32LittleEndian(first.AsSpan(20)) / 1000 }; if (packets.Next() is { } comments && comments.Length > 7 && comments[0] == 3 && comments.AsSpan(1, 6).SequenceEqual("vorbis"u8)) VorbisComments.Read(comments.AsSpan(7), reading); } else if (first.Length >= 19 && first.AsSpan(0, 8).SequenceEqual("OpusHead"u8)) { preSkip = BinaryPrimitives.ReadUInt16LittleEndian(first.AsSpan(10)); found = new TrackInfo { Codec = AudioCodec.Opus, Channels = first[9], SampleRate = 48000 }; if (packets.Next() is { } comments && comments.Length > 8 && comments.AsSpan(0, 8).SequenceEqual("OpusTags"u8)) VorbisComments.Read(comments.AsSpan(8), reading); } else if (first.Length >= 13 && first[0] == 0x7F && first.AsSpan(1, 4).SequenceEqual("FLAC"u8)) { found = new TrackInfo { Codec = AudioCodec.OggFlac }; if (first.Length >= 51 && first.AsSpan(9, 4).SequenceEqual("fLaC"u8)) { var streamInfo = FlacMetadata.StreamInfo.Parse(first.AsSpan(17)); found = found with { SampleRate = streamInfo.SampleRate, Channels = streamInfo.Channels, BitsPerSample = streamInfo.BitsPerSample }; } while (packets.Next() is { Length: >= 4 } block) { if ((block[0] & 0x7F) == 4) VorbisComments.Read(block.AsSpan(4), reading); else if ((block[0] & 0x7F) == 6) FlacMetadata.Picture(block.AsSpan(4), reading); if ((block[0] & 0x80) != 0) break; } } else { return false; } var granule = LastGranule(stream, serial); var seconds = granule > 0 && found.SampleRate > 0 ? (double)(granule - preSkip) / found.SampleRate : 0; if (found.Bitrate <= 0 && seconds > 0) found = found with { Bitrate = (int)(stream.Length * 8 / seconds / 1000) }; info = found with { Container = AudioContainer.Ogg, Seconds = Math.Max(0, seconds) }; return true; } private static long LastGranule(Stream stream, uint serial) { var size = (int)Math.Min(stream.Length, 256 * 1024); var tail = new byte[size]; stream.Position = stream.Length - size; stream.ReadExactly(tail); for (var at = size - 27; at >= 0; at--) { if (tail[at] != (byte)'O' || !tail.AsSpan(at, 4).SequenceEqual("OggS"u8) || tail[at + 4] != 0) continue; if (BinaryPrimitives.ReadUInt32LittleEndian(tail.AsSpan(at + 14)) != serial) continue; var granule = BinaryPrimitives.ReadInt64LittleEndian(tail.AsSpan(at + 6)); if (granule >= 0) return granule; } return 0; } private sealed class PacketReader(Stream stream) { private readonly MemoryStream partial = new(); private readonly Queue ready = new(); private bool started; public uint Serial { get; private set; } public byte[]? Next() { while (ready.Count == 0) if (!Page()) return null; return ready.Dequeue(); } private bool Page() { Span header = stackalloc byte[27]; if (Bytes.ReadAtMost(stream, header) != 27 || !header.StartsWith("OggS"u8) || header[4] != 0) return false; var serial = BinaryPrimitives.ReadUInt32LittleEndian(header[14..]); if (!started) { Serial = serial; started = true; } Span lacing = stackalloc byte[header[26]]; stream.ReadExactly(lacing); var total = 0; foreach (var value in lacing) total += value; var body = Bytes.Read(stream, total); if (serial != Serial) return true; var at = 0; foreach (var value in lacing) { partial.Write(body, at, value); at += value; if (partial.Length > MaxPacket) throw new InvalidDataException("An Ogg packet runs past 64 MB."); if (value == 255) continue; ready.Enqueue(partial.ToArray()); partial.SetLength(0); } return true; } } } public static class VorbisComments { public static void Read(ReadOnlySpan data, TagReading reading) { if (data.Length < 8) return; var vendor = BinaryPrimitives.ReadUInt32LittleEndian(data); if (vendor > data.Length - 8) return; var at = 4 + (int)vendor; var count = BinaryPrimitives.ReadUInt32LittleEndian(data[at..]); at += 4; for (var i = 0u; i < count && at + 4 <= data.Length; i++) { var length = BinaryPrimitives.ReadUInt32LittleEndian(data[at..]); at += 4; if (length > data.Length - at) break; var entry = data.Slice(at, (int)length); at += (int)length; var equals = entry.IndexOf((byte)'='); if (equals <= 0) continue; var key = Bytes.Latin1.GetString(entry[..equals]); var value = entry[(equals + 1)..]; if (key.Equals("METADATA_BLOCK_PICTURE", StringComparison.OrdinalIgnoreCase)) CoverArt(value, reading); else if (key.Equals("COVERART", StringComparison.OrdinalIgnoreCase)) LegacyCover(value, reading); else reading.Tags.Add(key, Bytes.Utf8Text(value)); } } private static void CoverArt(ReadOnlySpan base64, TagReading reading) { if (!reading.WantPictures) { reading.HasPicture = true; return; } var decoded = Decode(base64); if (decoded is not null) FlacMetadata.Picture(decoded, reading); } private static void LegacyCover(ReadOnlySpan base64, TagReading reading) { if (!reading.WantPictures) { reading.HasPicture = true; return; } if (Decode(base64) is { } data) reading.AddPicture(Picture.FrontCover, Bytes.MimeOf(data), () => data); } private static byte[]? Decode(ReadOnlySpan base64) { var buffer = new byte[base64.Length * 3 / 4 + 3]; return Base64.DecodeFromUtf8(base64, buffer, out _, out var written) == OperationStatus.Done ? buffer[..written] : null; } }