sniffEncodedMediaFormat function

EncodedMediaFormat? sniffEncodedMediaFormat(
  1. Uint8List bytes
)

The container bytes start with, from their magic bytes, or null when they match none of EncodedMediaFormat.known.

Pure and web-safe, and the only sniffer in core. It reads the first few bytes only; it does not validate the rest of the file, so a truncated or corrupt file of a known type is still reported as that type (the engine then fails to decode it).

Implementation

EncodedMediaFormat? sniffEncodedMediaFormat(Uint8List bytes) {
  bool at(int offset, List<int> signature) {
    if (bytes.length < offset + signature.length) return false;
    for (var i = 0; i < signature.length; i++) {
      if (bytes[offset + i] != signature[i]) return false;
    }
    return true;
  }

  if (at(0, const [0xFF, 0xD8, 0xFF])) return EncodedMediaFormat.jpeg;
  if (at(0, const [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
    return EncodedMediaFormat.png;
  }
  if (at(0, _ascii('GIF87a')) || at(0, _ascii('GIF89a'))) {
    return EncodedMediaFormat.gif;
  }
  if (at(0, _ascii('RIFF'))) {
    if (at(8, _ascii('WEBP'))) return EncodedMediaFormat.webp;
    if (at(8, _ascii('WAVE'))) return EncodedMediaFormat.wav;
    return null;
  }
  if (at(0, const [0x49, 0x49, 0x2A, 0x00]) ||
      at(0, const [0x4D, 0x4D, 0x00, 0x2A])) {
    return EncodedMediaFormat.tiff;
  }
  if (at(0, _ascii('fLaC'))) return EncodedMediaFormat.flac;
  if (at(0, _ascii('OggS'))) return EncodedMediaFormat.ogg;
  if (at(4, _ascii('ftyp'))) return _sniffIsoBaseMedia(bytes);
  if (at(0, _ascii('BM')) && _isBmpHeader(bytes)) return EncodedMediaFormat.bmp;
  if (at(0, _ascii('ID3')) || _isMpegAudioFrame(bytes)) {
    return EncodedMediaFormat.mp3;
  }
  return null;
}