Skip to content
0.2.0-dev Download ZIP
225 lines ·7.8 KB Raw
1using System.Buffers;
2using System.Buffers.Binary;
3using System.Buffers.Text;
4
5namespace EvilEngine.Music.Files;
6
7public static class OggPages
8{
9 private const int MaxPacket = 64 << 20;
10
11 public static bool Read(Stream stream, TagReading reading, out TrackInfo info)
12 {
13 info = new TrackInfo();
14 stream.Position = 0;
15 var packets = new PacketReader(stream);
16 if (packets.Next() is not { } first)
17 return false;
18 var serial = packets.Serial;
19 TrackInfo found;
20 var preSkip = 0;
21 if (first.Length >= 30 && first[0] == 1 && first.AsSpan(1, 6).SequenceEqual("vorbis"u8))
22 {
23 found = new TrackInfo
24 {
25 Codec = AudioCodec.Vorbis,
26 Channels = first[11],
27 SampleRate = (int)BinaryPrimitives.ReadUInt32LittleEndian(first.AsSpan(12)),
28 Bitrate = BinaryPrimitives.ReadInt32LittleEndian(first.AsSpan(20)) / 1000
29 };
30 if (packets.Next() is { } comments && comments.Length > 7 && comments[0] == 3 &&
31 comments.AsSpan(1, 6).SequenceEqual("vorbis"u8))
32 VorbisComments.Read(comments.AsSpan(7), reading);
33 }
34 else if (first.Length >= 19 && first.AsSpan(0, 8).SequenceEqual("OpusHead"u8))
35 {
36 preSkip = BinaryPrimitives.ReadUInt16LittleEndian(first.AsSpan(10));
37 found = new TrackInfo
38 {
39 Codec = AudioCodec.Opus,
40 Channels = first[9],
41 SampleRate = 48000
42 };
43 if (packets.Next() is { } comments && comments.Length > 8 &&
44 comments.AsSpan(0, 8).SequenceEqual("OpusTags"u8))
45 VorbisComments.Read(comments.AsSpan(8), reading);
46 }
47 else if (first.Length >= 13 && first[0] == 0x7F && first.AsSpan(1, 4).SequenceEqual("FLAC"u8))
48 {
49 found = new TrackInfo { Codec = AudioCodec.OggFlac };
50 if (first.Length >= 51 && first.AsSpan(9, 4).SequenceEqual("fLaC"u8))
51 {
52 var streamInfo = FlacMetadata.StreamInfo.Parse(first.AsSpan(17));
53 found = found with
54 {
55 SampleRate = streamInfo.SampleRate,
56 Channels = streamInfo.Channels,
57 BitsPerSample = streamInfo.BitsPerSample
58 };
59 }
60
61 while (packets.Next() is { Length: >= 4 } block)
62 {
63 if ((block[0] & 0x7F) == 4)
64 VorbisComments.Read(block.AsSpan(4), reading);
65 else if ((block[0] & 0x7F) == 6)
66 FlacMetadata.Picture(block.AsSpan(4), reading);
67 if ((block[0] & 0x80) != 0)
68 break;
69 }
70 }
71 else
72 {
73 return false;
74 }
75
76 var granule = LastGranule(stream, serial);
77 var seconds = granule > 0 && found.SampleRate > 0 ? (double)(granule - preSkip) / found.SampleRate : 0;
78 if (found.Bitrate <= 0 && seconds > 0)
79 found = found with { Bitrate = (int)(stream.Length * 8 / seconds / 1000) };
80 info = found with { Container = AudioContainer.Ogg, Seconds = Math.Max(0, seconds) };
81 return true;
82 }
83
84 private static long LastGranule(Stream stream, uint serial)
85 {
86 var size = (int)Math.Min(stream.Length, 256 * 1024);
87 var tail = new byte[size];
88 stream.Position = stream.Length - size;
89 stream.ReadExactly(tail);
90 for (var at = size - 27; at >= 0; at--)
91 {
92 if (tail[at] != (byte)'O' || !tail.AsSpan(at, 4).SequenceEqual("OggS"u8) || tail[at + 4] != 0)
93 continue;
94 if (BinaryPrimitives.ReadUInt32LittleEndian(tail.AsSpan(at + 14)) != serial)
95 continue;
96 var granule = BinaryPrimitives.ReadInt64LittleEndian(tail.AsSpan(at + 6));
97 if (granule >= 0)
98 return granule;
99 }
100
101 return 0;
102 }
103
104 private sealed class PacketReader(Stream stream)
105 {
106 private readonly MemoryStream partial = new();
107 private readonly Queue<byte[]> ready = new();
108 private bool started;
109
110 public uint Serial { get; private set; }
111
112 public byte[]? Next()
113 {
114 while (ready.Count == 0)
115 if (!Page())
116 return null;
117 return ready.Dequeue();
118 }
119
120 private bool Page()
121 {
122 Span<byte> header = stackalloc byte[27];
123 if (Bytes.ReadAtMost(stream, header) != 27 || !header.StartsWith("OggS"u8) || header[4] != 0)
124 return false;
125 var serial = BinaryPrimitives.ReadUInt32LittleEndian(header[14..]);
126 if (!started)
127 {
128 Serial = serial;
129 started = true;
130 }
131
132 Span<byte> lacing = stackalloc byte[header[26]];
133 stream.ReadExactly(lacing);
134 var total = 0;
135 foreach (var value in lacing)
136 total += value;
137 var body = Bytes.Read(stream, total);
138 if (serial != Serial)
139 return true;
140 var at = 0;
141 foreach (var value in lacing)
142 {
143 partial.Write(body, at, value);
144 at += value;
145 if (partial.Length > MaxPacket)
146 throw new InvalidDataException("An Ogg packet runs past 64 MB.");
147 if (value == 255)
148 continue;
149 ready.Enqueue(partial.ToArray());
150 partial.SetLength(0);
151 }
152
153 return true;
154 }
155 }
156}
157
158public static class VorbisComments
159{
160 public static void Read(ReadOnlySpan<byte> data, TagReading reading)
161 {
162 if (data.Length < 8)
163 return;
164 var vendor = BinaryPrimitives.ReadUInt32LittleEndian(data);
165 if (vendor > data.Length - 8)
166 return;
167 var at = 4 + (int)vendor;
168 var count = BinaryPrimitives.ReadUInt32LittleEndian(data[at..]);
169 at += 4;
170 for (var i = 0u; i < count && at + 4 <= data.Length; i++)
171 {
172 var length = BinaryPrimitives.ReadUInt32LittleEndian(data[at..]);
173 at += 4;
174 if (length > data.Length - at)
175 break;
176 var entry = data.Slice(at, (int)length);
177 at += (int)length;
178 var equals = entry.IndexOf((byte)'=');
179 if (equals <= 0)
180 continue;
181 var key = Bytes.Latin1.GetString(entry[..equals]);
182 var value = entry[(equals + 1)..];
183 if (key.Equals("METADATA_BLOCK_PICTURE", StringComparison.OrdinalIgnoreCase))
184 CoverArt(value, reading);
185 else if (key.Equals("COVERART", StringComparison.OrdinalIgnoreCase))
186 LegacyCover(value, reading);
187 else
188 reading.Tags.Add(key, Bytes.Utf8Text(value));
189 }
190 }
191
192 private static void CoverArt(ReadOnlySpan<byte> base64, TagReading reading)
193 {
194 if (!reading.WantPictures)
195 {
196 reading.HasPicture = true;
197 return;
198 }
199
200 var decoded = Decode(base64);
201 if (decoded is not null)
202 FlacMetadata.Picture(decoded, reading);
203 }
204
205 private static void LegacyCover(ReadOnlySpan<byte> base64, TagReading reading)
206 {
207 if (!reading.WantPictures)
208 {
209 reading.HasPicture = true;
210 return;
211 }
212
213 if (Decode(base64) is { } data)
214 reading.AddPicture(Picture.FrontCover, Bytes.MimeOf(data), () => data);
215 }
216
217 private static byte[]? Decode(ReadOnlySpan<byte> base64)
218 {
219 var buffer = new byte[base64.Length * 3 / 4 + 3];
220 return Base64.DecodeFromUtf8(base64, buffer, out _, out var written) ==
221 OperationStatus.Done
222 ? buffer[..written]
223 : null;
224 }
225}