> For AI agents: the complete documentation index is available at https://anyformat.swc.rs/llms.txt, the full documentation bundle is available at https://anyformat.swc.rs/llms-full.txt.

# Any format

The `@swc/anyformat` (Node.js) and `anyformat-core` (Python) packages
identify the format of a file of any family. Use them when a file can be of
any family, for example a file that a user uploads. They replace `file-type`
in Node.js, and `python-magic` (which needs libmagic) or `filetype` in Python,
for the formats that anyformat supports.

| Language | Package          | Module           |
| -------- | ---------------- | ---------------- |
| Node.js  | `@swc/anyformat` | `@swc/anyformat` |
| Python   | `anyformat-core` | `anyformat_core` |

The package contains the detection code of every family and nothing else. To
decode, encode, or compare files, install the package of the family, for
example [`@swc/anyformat-image`](https://anyformat.swc.rs/api/image.md).

## Supported formats

`detect` returns these formats. The first extension of each format is the most
common one.

| Family | Identifier | MIME type                                                                   | Extensions            |
| ------ | ---------- | --------------------------------------------------------------------------- | --------------------- |
| Image  | `png`      | `image/png`                                                                 | `png`                 |
| Image  | `jpeg`     | `image/jpeg`                                                                | `jpg`, `jpeg`         |
| Image  | `gif`      | `image/gif`                                                                 | `gif`                 |
| Image  | `webp`     | `image/webp`                                                                | `webp`                |
| Image  | `avif`     | `image/avif`                                                                | `avif`                |
| Image  | `heic`     | `image/heic`                                                                | `heic`, `heif`        |
| Image  | `jxl`      | `image/jxl`                                                                 | `jxl`                 |
| Image  | `tiff`     | `image/tiff`                                                                | `tiff`, `tif`         |
| Image  | `bmp`      | `image/bmp`                                                                 | `bmp`                 |
| Image  | `ico`      | `image/vnd.microsoft.icon`                                                  | `ico`                 |
| Image  | `qoi`      | `image/qoi`                                                                 | `qoi`                 |
| Video  | `mp4`      | `video/mp4`                                                                 | `mp4`, `m4v`          |
| Video  | `mov`      | `video/quicktime`                                                           | `mov`, `qt`           |
| Video  | `3gp`      | `video/3gpp`                                                                | `3gp`, `3g2`          |
| Video  | `webm`     | `video/webm`                                                                | `webm`                |
| Video  | `mkv`      | `video/x-matroska`                                                          | `mkv`                 |
| Video  | `avi`      | `video/x-msvideo`                                                           | `avi`                 |
| Video  | `flv`      | `video/x-flv`                                                               | `flv`                 |
| Video  | `ts`       | `video/mp2t`                                                                | `ts`, `m2ts`, `mts`   |
| Video  | `mpg`      | `video/mpeg`                                                                | `mpg`, `mpeg`         |
| Audio  | `mp3`      | `audio/mpeg`                                                                | `mp3`                 |
| Audio  | `aac`      | `audio/aac`                                                                 | `aac`                 |
| Audio  | `m4a`      | `audio/mp4`                                                                 | `m4a`, `m4b`          |
| Audio  | `flac`     | `audio/flac`                                                                | `flac`                |
| Audio  | `wav`      | `audio/wav`                                                                 | `wav`                 |
| Audio  | `aiff`     | `audio/aiff`                                                                | `aiff`, `aif`, `aifc` |
| Audio  | `opus`     | `audio/opus`                                                                | `opus`                |
| Audio  | `ogg`      | `audio/ogg`                                                                 | `ogg`, `oga`          |
| Audio  | `midi`     | `audio/midi`                                                                | `mid`, `midi`         |
| Audio  | `amr`      | `audio/amr`                                                                 | `amr`                 |
| Font   | `ttf`      | `font/ttf`                                                                  | `ttf`                 |
| Font   | `otf`      | `font/otf`                                                                  | `otf`                 |
| Font   | `ttc`      | `font/collection`                                                           | `ttc`                 |
| Font   | `woff`     | `font/woff`                                                                 | `woff`                |
| Font   | `woff2`    | `font/woff2`                                                                | `woff2`               |
| Font   | `eot`      | `application/vnd.ms-fontobject`                                             | `eot`                 |
| PDF    | `pdf`      | `application/pdf`                                                           | `pdf`                 |
| Office | `docx`     | `application/vnd.openxmlformats-officedocument.wordprocessingml.document`   | `docx`                |
| Office | `xlsx`     | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`         | `xlsx`                |
| Office | `pptx`     | `application/vnd.openxmlformats-officedocument.presentationml.presentation` | `pptx`                |
| Office | `odt`      | `application/vnd.oasis.opendocument.text`                                   | `odt`                 |
| Office | `ods`      | `application/vnd.oasis.opendocument.spreadsheet`                            | `ods`                 |
| Office | `odp`      | `application/vnd.oasis.opendocument.presentation`                           | `odp`                 |
| Office | `cfb`      | `application/x-cfb`                                                         | `doc`, `xls`, `ppt`   |
| Office | `rtf`      | `application/rtf`                                                           | `rtf`                 |

## How `detect` works

`detect` tries the `detect` function of each family in this order and returns
the first match: [image](https://anyformat.swc.rs/api/image.md), [video](https://anyformat.swc.rs/api/video.md), [audio](https://anyformat.swc.rs/api/audio.md),
[font](https://anyformat.swc.rs/api/font.md), [PDF](https://anyformat.swc.rs/api/pdf.md), [office](https://anyformat.swc.rs/api/office.md). The family packages use
the same detection code. For PDF files, `detect` uses the same check as `isPdf`
of the PDF family.

Some container formats belong to more than one family. For example, an ISO
BMFF file is an image (AVIF, HEIC), a video (MP4, MOV, 3GP), or audio (M4A).
The `ftyp` brands of the file select the family, and the brands of the
families do not overlap. The order makes the result stable if two families
match the same file in a later version.

`detect` reads only the leading bytes of a file and does not check the rest of
the file:

- Most formats need at most the first 1032 bytes, because a PDF header can
  start anywhere in the first 1024 bytes.
- ZIP-based office documents need the local file headers up to the entry that
  identifies the format. This is usually in the first few kilobytes.
- An audio file with an ID3v2 tag needs the whole tag and a few bytes after it.

[`detectPrefixLenSync`](#detectprefixlensync) tells how many leading bytes
`detect` needs for a file. [`detectFile`](#detectfile) and
[`detectStream`](#detectstream) read only these bytes.

## `detect`

Identifies the format of `data` from its leading bytes. Returns `null` in
Node.js and `None` in Python when the format is not recognized.

`families` limits the detection to these families. The function tries them in
the order above, not in the order of `families`. An empty list matches no
file. An unknown family name is an error: `ERR_INVALID_ARG_VALUE` in Node.js
and `ValueError` in Python.

### Node.js

```ts
type Family = 'image' | 'audio' | 'video' | 'font' | 'pdf' | 'office'

function detect(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): Promise<DetectedFile | null>
function detectSync(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): DetectedFile | null
```

```js
import { readFile } from 'node:fs/promises'
import { detect } from '@swc/anyformat'

await detect(await readFile('photo.jpg'))
// => { family: 'image', format: 'jpeg', mimeType: 'image/jpeg', extensions: ['jpg', 'jpeg'] }

await detect(await readFile('photo.jpg'), { families: ['audio', 'video'] })
// => null
```

`detect` detects the format on the libuv thread pool. It copies only the
leading bytes that the families need, so you can change `data` after the
call. `detectSync` blocks the event loop. An argument of a wrong type rejects
the promise of `detect` and makes `detectSync` throw.

### Python

```python
Family = Literal["image", "audio", "video", "font", "pdf", "office"]

def detect(data: Buffer, *, families: Sequence[Family] | None = None) -> DetectedFile | None
```

`data` is `bytes` or any other object with the buffer protocol, for example
`bytearray` or `memoryview`.

```python
from pathlib import Path

import anyformat_core

anyformat_core.detect(Path("photo.jpg").read_bytes())
# => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))

anyformat_core.detect(Path("photo.jpg").read_bytes(), families=["audio", "video"])
# => None
```

## `detectFile`

Identifies the format of the file at `path`. The function reads only the
leading bytes that [`detectPrefixLenSync`](#detectprefixlensync) asks for, not
the whole file. The result is the same as the result of `detect` on the bytes
of the file, with the same `families` option. Returns `null` in Node.js and
`None` in Python when the format is not recognized.

### Node.js

```ts
function detectFile(
  path: string | URL,
  options?: { families?: readonly Family[] | null } | null,
): Promise<DetectedFile | null>
function detectFileSync(
  path: string | URL,
  options?: { families?: readonly Family[] | null } | null,
): DetectedFile | null
```

```js
import { detectFile } from '@swc/anyformat'

await detectFile('upload.bin')
// => { family: 'image', format: 'jpeg', mimeType: 'image/jpeg', extensions: ['jpg', 'jpeg'] }

await detectFile('upload.bin', { families: ['audio', 'video'] })
// => null
```

`detectFile` reads the file and detects the format on the libuv thread pool.
`detectFileSync` blocks the event loop. A `URL` must use the `file:` scheme.

When the file cannot be read, `detectFile` rejects, and `detectFileSync`
throws, an `Error` with these properties:

- `code`: the Node.js errno name, for example `ENOENT`, `EACCES`, or `EISDIR`,
  or `ERR_IO` for an error that has no errno name.
- `path`: the path of the file.

### Python

```python
def detect_file(
    path: str | os.PathLike[str], *, families: Sequence[Family] | None = None
) -> DetectedFile | None
```

```python
import anyformat_core

anyformat_core.detect_file("upload.bin")
# => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))
```

The function releases the GIL while it reads the file. When the file cannot be
read, it raises the `OSError` subclass of the error, as `open` does, for
example `FileNotFoundError`, `PermissionError`, or `IsADirectoryError`. The
`filename` attribute of the exception is `path`.

## `detectStream`

Identifies the format of a stream, for example an upload or an HTTP response.
The function reads only the leading bytes that
[`detectPrefixLenSync`](#detectprefixlensync) asks for. The `families` option
is the same as the option of `detect`. With fewer families, the function can
read fewer bytes.

### Node.js

```ts
function detectStream(
  stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,
  options?: { families?: readonly Family[] | null } | null,
): Promise<{ result: DetectedFile | null; stream: ReadableStream<Uint8Array> }>
```

```js
import { detectStream } from '@swc/anyformat'

const response = await fetch('https://example.com/file')
const { result, stream } = await detectStream(response.body)
// result => { family: 'pdf', format: 'pdf', mimeType: 'application/pdf', extensions: ['pdf'] }
// stream gives all of the bytes of the response.
```

The function reads chunks until it has the bytes that `detectPrefixLenSync`
asks for, or until the input ends. Then it calls `detectSync`. The returned
`stream` gives all of the bytes of the input, including the bytes that the
function read, so use the returned stream and not the input stream. The input
can be a web `ReadableStream` or an async iterable, for example a Node.js
`Readable`. Each chunk must be a `Uint8Array`, for example a `Buffer`.

### Python

```python
def detect_stream(
    f: BinaryIO, *, families: Sequence[Family] | None = None
) -> DetectedFile | None
```

```python
import anyformat_core

with open("upload.bin", "rb") as f:
    anyformat_core.detect_stream(f)
    # => DetectedFile(family='image', format='jpeg', mime_type='image/jpeg', extensions=('jpg', 'jpeg'))
    # f.tell() is the same as before the call.
```

`f` must be a seekable binary file object. The function records `f.tell()`,
reads the bytes that `detect_prefix_len` asks for, and seeks back to the
recorded position. When `f.seekable()` is false, the function raises
`io.UnsupportedOperation`. For such an object, read a prefix with
`detect_prefix_len` and call `detect`:

```python
data = b""
while len(data) < anyformat_core.detect_prefix_len(data):
    chunk = f.read(anyformat_core.detect_prefix_len(data) - len(data))
    if not chunk:
        break
    data += chunk
anyformat_core.detect(data)
```

## `detectPrefixLenSync`

Returns the number of leading bytes that `detect` needs to give its final
result for `data`, the bytes read so far. The value is the largest value of
`detectPrefixLenSync` of the families in `families`. It can grow when more
bytes are available, for example for an ID3v2 tag. The maximum value is
16 MiB. When `families` is empty, the value is 0.

`detectFile` and `detectStream` read the bytes that this function asks for.
Use it to read a prefix yourself.

### Node.js

```ts
function detectPrefixLenSync(
  data: Uint8Array,
  options?: { families?: readonly Family[] | null } | null,
): number
```

### Python

```python
def detect_prefix_len(data: Buffer, *, families: Sequence[Family] | None = None) -> int
```

## `DetectedFile`

A file format identified by `detect`, with its family.

| Node.js      | Python       | Type       | Description                                                                                                                                          |
| ------------ | ------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `family`     | `family`     | `Family`   | The family of the format.                                                                                                                            |
| `format`     | `format`     | `string`   | The identifier of the format in its family, for example `"png"`. It is the same as `format` of `detect` of the family. For PDF files, it is `"pdf"`. |
| `mimeType`   | `mime_type`  | `string`   | The most common MIME type of the format.                                                                                                             |
| `extensions` | `extensions` | `string[]` | The usual file extensions of the format, without a dot, for example `["jpg", "jpeg"]`. The first extension is the most common one.                   |

Use `extensions` to check that the name of a file matches its content.

In Python, `DetectedFile` is a final class with read-only properties. The type
of `extensions` is `tuple[str, ...]`, and the type of the other properties is
`str`. Two objects with the same values are equal.

## `supportedFormats`

Every format that `detect` can return, grouped by family in the order that
`detect` tries the families. It contains every format of `supportedFormats`
of each family, and PDF. In Node.js, the array and its objects are frozen. In
Python, the constant is `SUPPORTED_FORMATS`, a tuple of `DetectedFile`.

### Node.js

```ts
const supportedFormats: readonly Readonly<DetectedFile>[]
```

```js
import { supportedFormats } from '@swc/anyformat'

supportedFormats.filter((format) => format.family === 'font').map((format) => format.format)
// => ['ttf', 'otf', 'ttc', 'woff', 'woff2', 'eot']
```

### Python

```python
SUPPORTED_FORMATS: tuple[DetectedFile, ...]
```

```python
import anyformat_core

[format.format for format in anyformat_core.SUPPORTED_FORMATS if format.family == "font"]
# => ['ttf', 'otf', 'ttc', 'woff', 'woff2', 'eot']
```
