File: ffmpeg.py

package info (click to toggle)
mautrix-python 0.20.7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,812 kB
  • sloc: python: 19,103; makefile: 16
file content (247 lines) | stat: -rw-r--r-- 7,882 bytes parent folder | download
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations

from typing import Any, Iterable
from pathlib import Path
import asyncio
import json
import logging
import mimetypes
import os
import shutil
import tempfile

try:
    from . import magic
except ImportError:
    magic = None


def _abswhich(program: str) -> str | None:
    path = shutil.which(program)
    return os.path.abspath(path) if path else None


class ConverterError(ChildProcessError):
    pass


class NotInstalledError(ConverterError):
    def __init__(self) -> None:
        super().__init__("failed to transcode media: ffmpeg is not installed")


ffmpeg_path = _abswhich("ffmpeg")
ffmpeg_default_params = ("-hide_banner", "-loglevel", "warning", "-y")

ffprobe_path = _abswhich("ffprobe")
ffprobe_default_params = (
    "-loglevel",
    "quiet",
    "-print_format",
    "json",
    "-show_optional_fields",
    "1",
    "-show_format",
    "-show_streams",
)


async def probe_path(
    input_file: os.PathLike[str] | str,
    logger: logging.Logger | None = None,
) -> Any:
    """
    Probes a media file on the disk using ffprobe.

    Args:
        input_file: The full path to the file.

    Returns:
        A Python object containing the parsed JSON response from ffprobe

    Raises:
        ConverterError: if ffprobe returns a non-zero exit code.
    """
    if ffprobe_path is None:
        raise NotInstalledError()

    input_file = Path(input_file)
    proc = await asyncio.create_subprocess_exec(
        ffprobe_path,
        *ffprobe_default_params,
        str(input_file),
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        stdin=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await proc.communicate()
    if proc.returncode != 0:
        err_text = stderr.decode("utf-8") if stderr else f"unknown ({proc.returncode})"
        raise ConverterError(f"ffprobe error: {err_text}")
    elif stderr and logger:
        logger.warning(f"ffprobe warning: {stderr.decode('utf-8')}")
    return json.loads(stdout)


async def probe_bytes(
    data: bytes,
    input_mime: str | None = None,
    logger: logging.Logger | None = None,
) -> Any:
    """
    Probe media file data using ffprobe.

    Args:
        data: The bytes of the file to probe.
        input_mime: The mime type of the input data. If not specified, will be guessed using magic.

    Returns:
        A Python object containing the parsed JSON response from ffprobe

    Raises:
        ConverterError: if ffprobe returns a non-zero exit code.
    """
    if ffprobe_path is None:
        raise NotInstalledError()

    if input_mime is None:
        if magic is None:
            raise ValueError("input_mime was not specified and magic is not installed")
        input_mime = magic.mimetype(data)
    input_extension = mimetypes.guess_extension(input_mime)
    with tempfile.TemporaryDirectory(prefix="mautrix_ffmpeg_") as tmpdir:
        input_file = Path(tmpdir) / f"data{input_extension}"
        with open(input_file, "wb") as file:
            file.write(data)
        return await probe_path(input_file=input_file, logger=logger)


async def convert_path(
    input_file: os.PathLike[str] | str,
    output_extension: str | None,
    input_args: Iterable[str] | None = None,
    output_args: Iterable[str] | None = None,
    remove_input: bool = False,
    output_path_override: os.PathLike[str] | str | None = None,
    logger: logging.Logger | None = None,
) -> Path | bytes:
    """
    Convert a media file on the disk using ffmpeg.

    Args:
        input_file: The full path to the file.
        output_extension: The extension that the output file should be.
        input_args: Arguments to tell ffmpeg how to parse the input file.
        output_args: Arguments to tell ffmpeg how to convert the file to reach the wanted output.
        remove_input: Whether the input file should be removed after converting.
                      Not compatible with ``output_path_override``.
        output_path_override: A custom output path to use
                              (instead of using the input path with a different extension).

    Returns:
        The path to the converted file, or the stdout if ``output_path_override`` was set to ``-``.

    Raises:
        ConverterError: if ffmpeg returns a non-zero exit code.
    """
    if ffmpeg_path is None:
        raise NotInstalledError()

    if output_path_override:
        output_file = output_path_override
        if remove_input:
            raise ValueError("remove_input can't be specified with output_path_override")
    elif not output_extension:
        raise ValueError("output_extension or output_path_override is required")
    else:
        input_file = Path(input_file)
        output_file = input_file.parent / f"{input_file.stem}{output_extension}"
    if input_file == output_file:
        output_file = Path(output_file)
        output_file = output_file.parent / f"{output_file.stem}-new{output_extension}"

    proc = await asyncio.create_subprocess_exec(
        ffmpeg_path,
        *ffmpeg_default_params,
        *(input_args or ()),
        "-i",
        str(input_file),
        *(output_args or ()),
        str(output_file),
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        stdin=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await proc.communicate()
    if proc.returncode != 0:
        err_text = stderr.decode("utf-8") if stderr else f"unknown ({proc.returncode})"
        raise ConverterError(f"ffmpeg error: {err_text}")
    elif stderr and logger:
        logger.warning(f"ffmpeg warning: {stderr.decode('utf-8')}")
    if remove_input and isinstance(input_file, Path):
        input_file.unlink(missing_ok=True)
    return stdout if output_file == "-" else output_file


async def convert_bytes(
    data: bytes,
    output_extension: str,
    input_args: Iterable[str] | None = None,
    output_args: Iterable[str] | None = None,
    input_mime: str | None = None,
    logger: logging.Logger | None = None,
) -> bytes:
    """
    Convert media file data using ffmpeg.

    Args:
        data: The bytes of the file to convert.
        output_extension: The extension that the output file should be.
        input_args: Arguments to tell ffmpeg how to parse the input file.
        output_args: Arguments to tell ffmpeg how to convert the file to reach the wanted output.
        input_mime: The mime type of the input data. If not specified, will be guessed using magic.

    Returns:
        The converted file as bytes.

    Raises:
        ConverterError: if ffmpeg returns a non-zero exit code.
    """
    if ffmpeg_path is None:
        raise NotInstalledError()

    if input_mime is None:
        if magic is None:
            raise ValueError("input_mime was not specified and magic is not installed")
        input_mime = magic.mimetype(data)
    input_extension = mimetypes.guess_extension(input_mime)
    with tempfile.TemporaryDirectory(prefix="mautrix_ffmpeg_") as tmpdir:
        input_file = Path(tmpdir) / f"data{input_extension}"
        with open(input_file, "wb") as file:
            file.write(data)
        output_file = await convert_path(
            input_file=input_file,
            output_extension=output_extension,
            input_args=input_args,
            output_args=output_args,
            logger=logger,
        )
        with open(output_file, "rb") as file:
            return file.read()


__all__ = [
    "ffmpeg_path",
    "ffmpeg_default_params",
    "ConverterError",
    "NotInstalledError",
    "convert_bytes",
    "convert_path",
    "probe_bytes",
    "probe_path",
]