-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlacParser.java
More file actions
213 lines (184 loc) · 7.58 KB
/
FlacParser.java
File metadata and controls
213 lines (184 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package me.tamkungz.codecmedia.internal.audio.flac;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import me.tamkungz.codecmedia.CodecMediaException;
import me.tamkungz.codecmedia.internal.audio.BitrateMode;
public final class FlacParser {
private FlacParser() {
}
public static FlacProbeInfo parse(byte[] bytes) throws CodecMediaException {
if (!isLikelyFlac(bytes)) {
throw new CodecMediaException("Not a FLAC file");
}
int offset = 4; // skip fLaC marker
boolean streamInfoFound = false;
int sampleRate = 0;
int channels = 0;
int bitsPerSample = 0;
long totalSamples = 0;
int audioStartOffset = -1;
while (offset + 4 <= bytes.length) {
int header = bytes[offset] & 0xFF;
boolean last = (header & 0x80) != 0;
int blockType = header & 0x7F;
if (blockType == 0x7F) {
throw new CodecMediaException("Invalid FLAC metadata block type: 127 is reserved");
}
int length = ((bytes[offset + 1] & 0xFF) << 16)
| ((bytes[offset + 2] & 0xFF) << 8)
| (bytes[offset + 3] & 0xFF);
offset += 4;
if (offset + length > bytes.length) {
throw new CodecMediaException("Invalid FLAC metadata block length");
}
if (blockType == 0) { // STREAMINFO
if (length < 34) {
throw new CodecMediaException("Invalid FLAC STREAMINFO block");
}
long packed = readUInt64BE(bytes, offset + 10);
sampleRate = (int) ((packed >>> 44) & 0xFFFFF);
channels = (int) (((packed >>> 41) & 0x7) + 1);
bitsPerSample = (int) (((packed >>> 36) & 0x1F) + 1);
totalSamples = packed & 0xFFFFFFFFFL;
streamInfoFound = true;
}
offset += length;
if (last) {
audioStartOffset = offset;
break;
}
}
if (!streamInfoFound || sampleRate <= 0 || channels <= 0 || bitsPerSample <= 0) {
throw new CodecMediaException("FLAC STREAMINFO is missing or invalid");
}
long durationMillis = totalSamples > 0 ? (totalSamples * 1000L) / sampleRate : 0;
long encodedAudioBytes = (audioStartOffset >= 0 && audioStartOffset <= bytes.length)
? (bytes.length - (long) audioStartOffset)
: 0;
int avgBitrateKbps = durationMillis > 0
? (int) ((encodedAudioBytes * 8L * 1000L) / durationMillis / 1000L)
: 0;
int pcmEquivalentKbps = (int) (((long) sampleRate * channels * bitsPerSample) / 1000L);
int bitrateKbps = avgBitrateKbps > 0 ? avgBitrateKbps : pcmEquivalentKbps;
return new FlacProbeInfo("flac", sampleRate, channels, bitsPerSample, bitrateKbps, BitrateMode.VBR, durationMillis);
}
public static boolean isLikelyFlac(byte[] bytes) {
return bytes != null
&& bytes.length >= 4
&& bytes[0] == 'f'
&& bytes[1] == 'L'
&& bytes[2] == 'a'
&& bytes[3] == 'C';
}
public static Map<String, String> readVorbisCommentMetadata(byte[] bytes) throws CodecMediaException {
if (!isLikelyFlac(bytes)) {
throw new CodecMediaException("Not a FLAC file");
}
int offset = 4;
while (offset + 4 <= bytes.length) {
int header = bytes[offset] & 0xFF;
boolean last = (header & 0x80) != 0;
int blockType = header & 0x7F;
int length = ((bytes[offset + 1] & 0xFF) << 16)
| ((bytes[offset + 2] & 0xFF) << 8)
| (bytes[offset + 3] & 0xFF);
offset += 4;
if (offset + length > bytes.length) {
throw new CodecMediaException("Invalid FLAC metadata block length");
}
if (blockType == 4) {
return parseVorbisCommentBlock(bytes, offset, length);
}
offset += length;
if (last) {
break;
}
}
return Map.of();
}
private static Map<String, String> parseVorbisCommentBlock(byte[] bytes, int offset, int length) {
int end = offset + length;
int pos = offset;
int vendorLen = readLeIntAt(bytes, pos, end);
if (vendorLen < 0) {
return Map.of();
}
pos += 4;
if (pos + vendorLen > end) {
return Map.of();
}
pos += vendorLen;
int commentCount = readLeIntAt(bytes, pos, end);
if (commentCount < 0) {
return Map.of();
}
pos += 4;
Map<String, String> raw = new HashMap<>();
Map<String, String> out = new LinkedHashMap<>();
for (int i = 0; i < commentCount; i++) {
int commentLen = readLeIntAt(bytes, pos, end);
if (commentLen < 0) {
return Map.of();
}
pos += 4;
if (pos + commentLen > end) {
return Map.of();
}
String comment = new String(bytes, pos, commentLen, StandardCharsets.UTF_8);
int eq = comment.indexOf('=');
if (eq > 0) {
String key = comment.substring(0, eq).trim().toUpperCase(Locale.ROOT);
String value = comment.substring(eq + 1).trim();
if (!value.isEmpty()) {
raw.putIfAbsent(key, value);
}
}
pos += commentLen;
}
putIfPresent(out, "title", raw, "TITLE");
putIfPresent(out, "artist", raw, "ARTIST");
putIfPresent(out, "album", raw, "ALBUM");
putIfPresent(out, "comment", raw, "COMMENT");
putIfPresent(out, "genre", raw, "GENRE");
putIfPresent(out, "date", raw, "DATE", "YEAR");
return out;
}
private static long readUInt64BE(byte[] bytes, int offset) throws CodecMediaException {
if (offset + 8 > bytes.length) {
throw new CodecMediaException("Unexpected end of FLAC data");
}
return ((long) (bytes[offset] & 0xFF) << 56)
| ((long) (bytes[offset + 1] & 0xFF) << 48)
| ((long) (bytes[offset + 2] & 0xFF) << 40)
| ((long) (bytes[offset + 3] & 0xFF) << 32)
| ((long) (bytes[offset + 4] & 0xFF) << 24)
| ((long) (bytes[offset + 5] & 0xFF) << 16)
| ((long) (bytes[offset + 6] & 0xFF) << 8)
| ((long) (bytes[offset + 7] & 0xFF));
}
private static int readLeIntAt(byte[] bytes, int offset, int endExclusive) {
if (offset < 0 || offset + 4 > endExclusive || offset + 4 > bytes.length) {
return -1;
}
long value = (bytes[offset] & 0xFFL)
| ((bytes[offset + 1] & 0xFFL) << 8)
| ((bytes[offset + 2] & 0xFFL) << 16)
| ((bytes[offset + 3] & 0xFFL) << 24);
if (value > Integer.MAX_VALUE) {
return -1;
}
return (int) value;
}
private static void putIfPresent(Map<String, String> target, String targetKey, Map<String, String> source, String... sourceKeys) {
for (String sourceKey : sourceKeys) {
String value = source.get(sourceKey);
if (value != null && !value.isBlank()) {
target.putIfAbsent(targetKey, value);
return;
}
}
}
}