]> git.nihav.org Git - nihav.git/blob - nihav-registry/src/detect.rs
54bc756ba53f6ce225c01d1398267c5903761a8d
[nihav.git] / nihav-registry / src / detect.rs
1 //! Container format detection.
2 //!
3 //! Usually user does not know the container format of the opened file.
4 //! That is why format detection functionality is needed.
5 //! This module contains the set of rules to detect container not merely by file extension but also by its content if possible.
6 //!
7 //! # Examples
8 //!
9 //! ```no_run
10 //! use nihav_registry::detect::detect_format;
11 //! use std::fs::File;
12 //! use nihav_core::io::byteio::*;
13 //!
14 //! let name = "mediafile.ogv";
15 //! let mut file = File::open(name).unwrap();
16 //! let mut br = FileReader::new_read(&mut file);
17 //! let result = detect_format(name, &mut br);
18 //! if let Some((name, score)) = result {
19 //! println!("detected format {} with score {:?}", name, score);
20 //! }
21 //! ```
22 use std::io::SeekFrom;
23 use nihav_core::io::byteio::ByteIO;
24
25 /// Format detection score.
26 #[derive(Debug,Clone,Copy,PartialEq)]
27 pub enum DetectionScore {
28 /// Format is not detected.
29 No,
30 /// Format matched by file extension.
31 ExtensionMatches,
32 /// Format matches by markers inside the file.
33 MagicMatches,
34 }
35
36 impl DetectionScore {
37 /// Checks whether current detection score is less than a value it is compared against.
38 pub fn less(self, other: DetectionScore) -> bool {
39 (self as i32) < (other as i32)
40 }
41 }
42
43 #[allow(dead_code)]
44 enum Arg {
45 Byte(u8),
46 U16BE(u16),
47 U16LE(u16),
48 U24BE(u32),
49 U24LE(u32),
50 U32BE(u32),
51 U32LE(u32),
52 U64BE(u64),
53 U64LE(u64),
54 }
55
56 impl Arg {
57 fn val(&self) -> u64 {
58 match *self {
59 Arg::Byte(b) => { u64::from(b) }
60 Arg::U16BE(v) => { u64::from(v) }
61 Arg::U16LE(v) => { u64::from(v) }
62 Arg::U24BE(v) => { u64::from(v) }
63 Arg::U24LE(v) => { u64::from(v) }
64 Arg::U32BE(v) => { u64::from(v) }
65 Arg::U32LE(v) => { u64::from(v) }
66 Arg::U64BE(v) => { v }
67 Arg::U64LE(v) => { v }
68 }
69 }
70 fn read_val(&self, src: &mut dyn ByteIO) -> Option<u64> {
71 match *self {
72 Arg::Byte(_) => {
73 let res = src.peek_byte();
74 if res.is_err() { return None; }
75 Some(u64::from(res.unwrap()))
76 }
77 Arg::U16BE(_) => {
78 let res = src.peek_u16be();
79 if res.is_err() { return None; }
80 Some(u64::from(res.unwrap()))
81 }
82 Arg::U16LE(_) => {
83 let res = src.peek_u16le();
84 if res.is_err() { return None; }
85 Some(u64::from(res.unwrap()))
86 }
87 Arg::U24BE(_) => {
88 let res = src.peek_u24be();
89 if res.is_err() { return None; }
90 Some(u64::from(res.unwrap()))
91 }
92 Arg::U24LE(_) => {
93 let res = src.peek_u24le();
94 if res.is_err() { return None; }
95 Some(u64::from(res.unwrap()))
96 }
97 Arg::U32BE(_) => {
98 let res = src.peek_u32be();
99 if res.is_err() { return None; }
100 Some(u64::from(res.unwrap()))
101 }
102 Arg::U32LE(_) => {
103 let res = src.peek_u32le();
104 if res.is_err() { return None; }
105 Some(u64::from(res.unwrap()))
106 }
107 Arg::U64BE(_) => {
108 let res = src.peek_u64be();
109 if res.is_err() { return None; }
110 Some(res.unwrap())
111 }
112 Arg::U64LE(_) => {
113 let res = src.peek_u64le();
114 if res.is_err() { return None; }
115 Some(res.unwrap())
116 }
117 }
118 }
119 fn eq(&self, src: &mut dyn ByteIO) -> bool {
120 if let Some(rval) = self.read_val(src) {
121 rval == self.val()
122 } else {
123 false
124 }
125 }
126 fn ge(&self, src: &mut dyn ByteIO) -> bool {
127 if let Some(rval) = self.read_val(src) {
128 rval >= self.val()
129 } else {
130 false
131 }
132 }
133 fn gt(&self, src: &mut dyn ByteIO) -> bool {
134 if let Some(rval) = self.read_val(src) {
135 rval > self.val()
136 } else {
137 false
138 }
139 }
140 fn le(&self, src: &mut dyn ByteIO) -> bool {
141 if let Some(rval) = self.read_val(src) {
142 rval <= self.val()
143 } else {
144 false
145 }
146 }
147 fn lt(&self, src: &mut dyn ByteIO) -> bool {
148 if let Some(rval) = self.read_val(src) {
149 rval < self.val()
150 } else {
151 false
152 }
153 }
154 }
155
156 #[allow(dead_code)]
157 enum CC<'a> {
158 Or(&'a CC<'a>, &'a CC<'a>),
159 Eq(Arg),
160 Str(&'static [u8]),
161 In(Arg, Arg),
162 Lt(Arg),
163 Le(Arg),
164 Gt(Arg),
165 Ge(Arg),
166 }
167
168 impl<'a> CC<'a> {
169 fn eval(&self, src: &mut dyn ByteIO) -> bool {
170 match *self {
171 CC::Or(a, b) => { a.eval(src) || b.eval(src) },
172 CC::Eq(ref arg) => { arg.eq(src) },
173 CC::In(ref a, ref b) => { a.ge(src) && b.le(src) },
174 CC::Lt(ref arg) => { arg.lt(src) },
175 CC::Le(ref arg) => { arg.le(src) },
176 CC::Gt(ref arg) => { arg.gt(src) },
177 CC::Ge(ref arg) => { arg.ge(src) },
178 CC::Str(strng) => {
179 let mut val: Vec<u8> = vec![0; strng.len()];
180 let res = src.peek_buf(val.as_mut_slice());
181 if res.is_err() { return false; }
182 val == strng
183 }
184 }
185 }
186 }
187
188 struct CheckItem<'a> {
189 offs: u32,
190 cond: &'a CC<'a>,
191 }
192
193 #[allow(dead_code)]
194 struct DetectConditions<'a> {
195 demux_name: &'static str,
196 extensions: &'static str,
197 conditions: &'a [CheckItem<'a>],
198 }
199
200 const DETECTORS: &[DetectConditions] = &[
201 DetectConditions {
202 demux_name: "avi",
203 extensions: ".avi",
204 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::Str(b"RIFF"), &CC::Str(b"ON2 ")) },
205 CheckItem{offs: 8, cond: &CC::Or(&CC::Or(&CC::Str(b"AVI LIST"),
206 &CC::Str(b"AVIXLIST")),
207 &CC::Str(b"ON2fLIST")) },
208 ]
209 },
210 DetectConditions {
211 demux_name: "wav",
212 extensions: ".wav",
213 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"RIFF") },
214 CheckItem{offs: 8, cond: &CC::Str(b"WAVEfmt ") }
215 ]
216 },
217 DetectConditions {
218 demux_name: "mov",
219 extensions: ".mov",
220 conditions: &[CheckItem{offs: 4, cond: &CC::Or(&CC::Or(&CC::Str(b"mdat"),
221 &CC::Str(b"moov")),
222 &CC::Str(b"ftyp")) }],
223 },
224 DetectConditions {
225 demux_name: "gif",
226 extensions: ".gif",
227 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::Str(b"GIF87a"),
228 &CC::Str(b"GIF89a")) }],
229 },
230 DetectConditions {
231 demux_name: "mov",
232 extensions: ".mov",
233 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"\x00\x00\x00\x08wide") },
234 CheckItem{offs: 12, cond: &CC::Or(&CC::Or(&CC::Str(b"mdat"),
235 &CC::Str(b"moov")),
236 &CC::Str(b"ftyp")) }],
237 },
238 DetectConditions {
239 demux_name: "mov-macbin",
240 extensions: ".mov,.bin",
241 conditions: &[CheckItem{offs: 0, cond: &CC::Eq(Arg::Byte(0))},
242 CheckItem{offs: 0x41, cond: &CC::Str(b"MooV")},
243 CheckItem{offs: 0x7A, cond: &CC::Eq(Arg::Byte(0x81))},
244 CheckItem{offs: 0x7B, cond: &CC::Eq(Arg::Byte(0x81))},
245 CheckItem{offs: 0x84, cond: &CC::Str(b"mdat")}],
246 },
247 DetectConditions {
248 demux_name: "mov-resfork",
249 extensions: ".mov",
250 conditions: &[CheckItem{offs: 0, cond: &CC::Eq(Arg::U32BE(0x100))},
251 CheckItem{offs: 0x108, cond: &CC::Str(b"moov")}],
252 },
253 DetectConditions {
254 demux_name: "yuv4mpeg",
255 extensions: ".y4m",
256 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"YUV4MPEG2 ") }],
257 },
258 DetectConditions {
259 demux_name: "armovie",
260 extensions: ".rpl",
261 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"ARMovie\n") }],
262 },
263 DetectConditions {
264 demux_name: "tca",
265 extensions: ".tca",
266 conditions: &[CheckItem{offs: 0x00, cond: &CC::Str(b"ACEF") },
267 CheckItem{offs: 0x18, cond: &CC::Eq(Arg::U32LE(64))}],
268 },
269 DetectConditions {
270 demux_name: "flv",
271 extensions: ".flv",
272 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"FLV") },
273 CheckItem{offs: 3, cond: &CC::Le(Arg::Byte(1)) }],
274 },
275 DetectConditions {
276 demux_name: "dvi",
277 extensions: ".avs,.dvi",
278 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"IVDV")},
279 CheckItem{offs: 12, cond: &CC::Str(b"SSVA")}],
280 },
281 DetectConditions {
282 demux_name: "ivf",
283 extensions: ".ivf",
284 conditions: &[CheckItem{offs: 0, cond: &CC::Str(&[0x50, 0xEF, 0x81, 0x19, 0xB3, 0xBD, 0xD0, 0x11, 0xA3, 0xE5, 0x00, 0xA0, 0xC9, 0x24, 0x44])},
285 CheckItem{offs: 15, cond: &CC::Or(&CC::Eq(Arg::Byte(0x36)), &CC::Eq(Arg::Byte(0x37)))}],
286 },
287 DetectConditions {
288 demux_name: "dkivf",
289 extensions: ".ivf",
290 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"DKIF\x00\x00")},
291 CheckItem{offs: 6, cond: &CC::Ge(Arg::U16LE(32))}],
292 },
293 DetectConditions {
294 demux_name: "gdv",
295 extensions: ".gdv",
296 conditions: &[CheckItem{offs: 0, cond: &CC::Eq(Arg::U32LE(0x29111994))}],
297 },
298 DetectConditions {
299 demux_name: "smush",
300 extensions: ".san",
301 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"ANIM")},
302 CheckItem{offs: 8, cond: &CC::Str(b"AHDR")}],
303 },
304 DetectConditions {
305 demux_name: "smush-mcmp",
306 extensions: ".imc",
307 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"MCMP")},
308 CheckItem{offs: 6, cond: &CC::Eq(Arg::Byte(0))},
309 CheckItem{offs: 7, cond: &CC::Eq(Arg::Byte(0))}],
310 },
311 DetectConditions {
312 demux_name: "smush",
313 extensions: ".snm",
314 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"SANM")},
315 CheckItem{offs: 8, cond: &CC::Str(b"SHDR")}],
316 },
317 DetectConditions {
318 demux_name: "mvi",
319 extensions: ".mvi",
320 conditions: &[],
321 },
322 DetectConditions {
323 demux_name: "qpeg",
324 extensions: ".dvc",
325 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"IDVCd")}],
326 },
327 DetectConditions {
328 demux_name: "tealmov",
329 extensions: ".pdb",
330 conditions: &[CheckItem{offs: 0x3C, cond: &CC::Str(b"MvieTlMv")}],
331 },
332 DetectConditions {
333 demux_name: "realaudio",
334 extensions: ".ra,.ram",
335 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b".ra\xFD")}],
336 },
337 DetectConditions {
338 demux_name: "realmedia",
339 extensions: ".rm,.rmvb,.rma,.ra,.ram",
340 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::Str(b".RMF"), &CC::Str(b".RMP")) },
341 CheckItem{offs: 4, cond: &CC::Ge(Arg::U32BE(10))}],
342 },
343 DetectConditions {
344 demux_name: "real_ivr",
345 extensions: ".ivr",
346 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::Str(b".R1M"), &CC::Str(b".REC"))}],
347 },
348 DetectConditions {
349 demux_name: "bink",
350 extensions: ".bik,.bk2",
351 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::In(Arg::U32BE(0x42494B62), // BIKb
352 Arg::U32BE(0x42494B7B)), // BIKz
353 &CC::In(Arg::U32BE(0x4B423261), // KB2a
354 Arg::U32BE(0x4B42327B)))}], // KB2z
355 },
356 DetectConditions {
357 demux_name: "smacker",
358 extensions: ".smk",
359 conditions: &[CheckItem{offs: 0, cond: &CC::Or(&CC::Str(b"SMK2"), &CC::Str(b"SMK4"))}],
360 },
361 DetectConditions {
362 demux_name: "ape",
363 extensions: ".ape",
364 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"MAC ") },
365 CheckItem{offs: 4, cond: &CC::In(Arg::U16LE(3800), Arg::U16LE(3990))}],
366 },
367 DetectConditions {
368 demux_name: "flac",
369 extensions: ".flac",
370 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"fLaC") }],
371 },
372 DetectConditions {
373 demux_name: "tta",
374 extensions: ".tta",
375 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"TTA1") }],
376 },
377 DetectConditions {
378 demux_name: "wavpack",
379 extensions: ".wv",
380 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"wvpk") },
381 CheckItem{offs: 8, cond: &CC::In(Arg::U16LE(0x402), Arg::U16LE(0x410))}],
382 },
383 DetectConditions {
384 demux_name: "vivo",
385 extensions: ".viv",
386 conditions: &[CheckItem{offs: 0, cond: &CC::In(Arg::U16BE(1), Arg::U16BE(0xFF))},
387 CheckItem{offs: 2, cond: &CC::Str(b"\x0D\x0AVersion:Vivo/")}],
388 },
389 DetectConditions {
390 demux_name: "vivo",
391 extensions: ".viv",
392 conditions: &[CheckItem{offs: 0, cond: &CC::In(Arg::U16BE(1), Arg::U16BE(0xFF))},
393 CheckItem{offs: 3, cond: &CC::Str(b"\x0D\x0AVersion:Vivo/")}],
394 },
395 DetectConditions {
396 demux_name: "bmv",
397 extensions: ".bmv",
398 conditions: &[],
399 },
400 DetectConditions {
401 demux_name: "bmv3",
402 extensions: ".bmv",
403 conditions: &[CheckItem{offs: 0, cond: &CC::Str(b"BMVi") },
404 CheckItem{offs: 32, cond: &CC::Str(b"DATA")}],
405 },
406 DetectConditions {
407 demux_name: "sga",
408 extensions: ".dtv,.avc",
409 conditions: &[],
410 },
411 DetectConditions {
412 demux_name: "sierra-seq",
413 extensions: ".seq",
414 conditions: &[],
415 },
416 DetectConditions {
417 demux_name: "vmd",
418 extensions: ".vmd",
419 conditions: &[],
420 },
421 ];
422
423 /// Tries to detect container format.
424 ///
425 /// This function tries to determine container format using both file extension and checking against container specific markers inside.
426 /// In case of success the function returns short container name and the detection score.
427 /// Result should have the highest detection score among tested.
428 pub fn detect_format(name: &str, src: &mut dyn ByteIO) -> Option<(&'static str, DetectionScore)> {
429 let mut result = None;
430 let lname = name.to_lowercase();
431 for detector in DETECTORS {
432 let mut score = DetectionScore::No;
433 if !name.is_empty() {
434 for ext in detector.extensions.split(',') {
435 if lname.ends_with(ext) {
436 score = DetectionScore::ExtensionMatches;
437 break;
438 }
439 }
440 }
441 let mut passed = !detector.conditions.is_empty();
442 for ck in detector.conditions {
443 let ret = src.seek(SeekFrom::Start(u64::from(ck.offs)));
444 if ret.is_err() {
445 passed = false;
446 break;
447 }
448 if !ck.cond.eval(src) {
449 passed = false;
450 break;
451 }
452 }
453 if passed {
454 score = DetectionScore::MagicMatches;
455 }
456 if score == DetectionScore::MagicMatches {
457 return Some((detector.demux_name, score));
458 }
459 if result.is_none() && score != DetectionScore::No {
460 result = Some((detector.demux_name, score));
461 } else if result.is_some() {
462 let (_, oldsc) = result.unwrap();
463 if oldsc.less(score) {
464 result = Some((detector.demux_name, score));
465 }
466 }
467 }
468 result
469 }
470
471 /// Tries to detect container format for provided file name.
472 pub fn detect_format_by_name(name: &str) -> Option<&'static str> {
473 if name.is_empty() {
474 return None;
475 }
476 let lname = name.to_lowercase();
477 for detector in DETECTORS {
478 for ext in detector.extensions.split(',') {
479 if lname.ends_with(ext) {
480 return Some(detector.demux_name);
481 }
482 }
483 }
484 None
485 }
486
487 #[cfg(test)]
488 mod test {
489 use super::*;
490 use std::fs::File;
491 use nihav_core::io::byteio::*;
492
493 #[test]
494 fn test_avi_detect() {
495 let name = "assets/Indeo/laser05.avi";
496 let mut file = File::open(name).unwrap();
497 let mut br = FileReader::new_read(&mut file);
498 let (name, score) = detect_format(name, &mut br).unwrap();
499 assert_eq!(name, "avi");
500 assert_eq!(score, DetectionScore::MagicMatches);
501 }
502
503 #[test]
504 fn test_gdv_detect() {
505 let name = "assets/Game/intro1.gdv";
506 let mut file = File::open(name).unwrap();
507 let mut br = FileReader::new_read(&mut file);
508 let (name, score) = detect_format(name, &mut br).unwrap();
509 assert_eq!(name, "gdv");
510 assert_eq!(score, DetectionScore::MagicMatches);
511 }
512 }