better-ffmpeg-progress 6.0.1__tar.gz → 7.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {better_ffmpeg_progress-6.0.1/better_ffmpeg_progress.egg-info → better_ffmpeg_progress-7.0.0}/PKG-INFO +69 -6
- better_ffmpeg_progress-6.0.1/PKG-INFO → better_ffmpeg_progress-7.0.0/README.md +53 -24
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress/__init__.py +3 -3
- better_ffmpeg_progress-7.0.0/better_ffmpeg_progress/better_ffmpeg_progress.py +423 -0
- better_ffmpeg_progress-7.0.0/better_ffmpeg_progress/exceptions.py +38 -0
- better_ffmpeg_progress-7.0.0/better_ffmpeg_progress/progress_bars.py +197 -0
- better_ffmpeg_progress-7.0.0/better_ffmpeg_progress/terminate_process.py +70 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress/utils.py +87 -24
- better_ffmpeg_progress-6.0.1/README.md → better_ffmpeg_progress-7.0.0/better_ffmpeg_progress.egg-info/PKG-INFO +87 -3
- better_ffmpeg_progress-7.0.0/better_ffmpeg_progress.egg-info/requires.txt +14 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/pyproject.toml +16 -3
- better_ffmpeg_progress-7.0.0/tests/test_ffmpeg_process.py +320 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/tests/test_utils.py +70 -0
- better_ffmpeg_progress-6.0.1/better_ffmpeg_progress/better_ffmpeg_progress.py +0 -277
- better_ffmpeg_progress-6.0.1/better_ffmpeg_progress/exceptions.py +0 -14
- better_ffmpeg_progress-6.0.1/better_ffmpeg_progress/progress_bars.py +0 -98
- better_ffmpeg_progress-6.0.1/better_ffmpeg_progress/terminate_process.py +0 -44
- better_ffmpeg_progress-6.0.1/better_ffmpeg_progress.egg-info/requires.txt +0 -5
- better_ffmpeg_progress-6.0.1/tests/test_ffmpeg_process.py +0 -153
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/LICENSE +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress/enums.py +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress/py.typed +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress.egg-info/SOURCES.txt +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress.egg-info/dependency_links.txt +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress.egg-info/top_level.txt +0 -0
- {better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: better-ffmpeg-progress
|
|
3
|
-
Version:
|
|
3
|
+
Version: 7.0.0
|
|
4
4
|
Summary: Run FFmpeg & see percentage progress + ETA.
|
|
5
5
|
Author-email: "GitHub.com/CrypticSignal" <theaudiophile@outlook.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -8,15 +8,28 @@ Project-URL: Homepage, https://github.com/CrypticSignal/better-ffmpeg-progress
|
|
|
8
8
|
Project-URL: Changelog, https://github.com/CrypticSignal/better-ffmpeg-progress/blob/main/CHANGELOG.md
|
|
9
9
|
Keywords: ffmpeg,progress
|
|
10
10
|
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
16
|
+
Classifier: Topic :: Multimedia :: Video :: Conversion
|
|
11
17
|
Classifier: Operating System :: OS Independent
|
|
12
18
|
Classifier: Typing :: Typed
|
|
13
|
-
Requires-Python: >=3.
|
|
19
|
+
Requires-Python: >=3.11
|
|
14
20
|
Description-Content-Type: text/markdown
|
|
15
21
|
License-File: LICENSE
|
|
16
22
|
Requires-Dist: rich
|
|
17
|
-
|
|
23
|
+
Provides-Extra: tqdm
|
|
24
|
+
Requires-Dist: tqdm; extra == "tqdm"
|
|
18
25
|
Provides-Extra: test
|
|
19
26
|
Requires-Dist: pytest; extra == "test"
|
|
27
|
+
Requires-Dist: tqdm; extra == "test"
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: better-ffmpeg-progress[test]; extra == "dev"
|
|
30
|
+
Requires-Dist: mypy; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff; extra == "dev"
|
|
32
|
+
Requires-Dist: types-tqdm; extra == "dev"
|
|
20
33
|
Dynamic: license-file
|
|
21
34
|
|
|
22
35
|
<div align="center">
|
|
@@ -140,28 +153,78 @@ An instance of `FfmpegProcess` accepts the following optional arguments:
|
|
|
140
153
|
* `duration_override` — Specify input file duration in seconds to use for progress calculation, instead of trying to detect this automatically with FFprobe. Default: `None`.
|
|
141
154
|
* `use_tqdm` — Use tqdm instead of Rich for the progress bar. Default: `False`.
|
|
142
155
|
* `overwrite` — What to do if the output file already exists: `True` overwrites it, `False` raises `FfmpegCommandError`, and `None` asks whether to overwrite it. Ignored if the command contains `-y` or `-n`. Default: `None`.
|
|
156
|
+
* `quiet` — Do not show a progress bar or status messages. Default: `False`.
|
|
157
|
+
* `progress_callback` — A function to call each time FFmpeg reports its progress. See [Progress callback](#progress-callback). Default: `None`.
|
|
158
|
+
* `delete_log_on_success` — Delete the FFmpeg log file if FFmpeg succeeds. Default: `False`.
|
|
159
|
+
|
|
160
|
+
Creating an `FfmpegProcess` only validates the command. FFprobe is run, and you are asked whether to overwrite an existing output file, when `run()` is called.
|
|
143
161
|
|
|
144
162
|
The `run` method accepts the following optional argument:
|
|
145
163
|
* `print_command` — Print the FFmpeg command being executed. Default: `False`.
|
|
146
164
|
|
|
147
165
|
## Using tqdm
|
|
148
|
-
By default, the [Rich](https://github.com/Textualize/rich) library is used to display a progress bar. [tqdm](https://github.com/tqdm/tqdm) can be used instead by passing `use_tqdm=True
|
|
166
|
+
By default, the [Rich](https://github.com/Textualize/rich) library is used to display a progress bar. [tqdm](https://github.com/tqdm/tqdm) can be used instead by passing `use_tqdm=True`. tqdm is an optional dependency, installed with:
|
|
167
|
+
```bash
|
|
168
|
+
pip install "better-ffmpeg-progress[tqdm]" --upgrade
|
|
169
|
+
```
|
|
149
170
|
```python
|
|
150
171
|
process = FfmpegProcess(command, use_tqdm=True)
|
|
151
172
|
process.run()
|
|
152
173
|
```
|
|
174
|
+
|
|
175
|
+
## Progress callback
|
|
176
|
+
To show progress in your own UI (e.g. a GUI or a web app), pass a function as `progress_callback`. It is called with the number of seconds processed, the expected output duration in seconds (`None` if it is unknown) and the current output size in MB. Combine it with `quiet=True` to hide the progress bar:
|
|
177
|
+
```python
|
|
178
|
+
def on_progress(secs: float, duration: float | None, size_mb: float) -> None:
|
|
179
|
+
if duration:
|
|
180
|
+
print(f"{secs / duration:.0%}")
|
|
181
|
+
|
|
182
|
+
FfmpegProcess(command, quiet=True, progress_callback=on_progress).run()
|
|
183
|
+
```
|
|
184
|
+
If the callback raises an exception, FFmpeg is stopped and the exception is propagated by `run()`.
|
|
185
|
+
|
|
186
|
+
## Errors
|
|
187
|
+
All exceptions raised by the package are subclasses of `FfmpegProcessError`, which has these attributes:
|
|
188
|
+
* `returncode` — FFmpeg's exit code, or `None` if FFmpeg was not started or had not exited.
|
|
189
|
+
* `log_file` — The path or file object that FFmpeg's log was written to.
|
|
190
|
+
|
|
191
|
+
Pressing Ctrl+C raises `FfmpegProcessInterruptedError`. FFmpeg is first asked to stop the way pressing `q` does, so it can finish writing the output file, e.g. an MP4 file stays playable. If it does not stop within 5 seconds, it is terminated.
|
|
192
|
+
|
|
193
|
+
## Logging
|
|
194
|
+
Warnings, such as when the input duration cannot be detected, are logged with the `logging` module using the `better_ffmpeg_progress` logger. Without any logging configuration, Python prints them to standard error. To hide them:
|
|
195
|
+
```python
|
|
196
|
+
import logging
|
|
197
|
+
|
|
198
|
+
logging.getLogger("better_ffmpeg_progress").setLevel(logging.ERROR)
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Writing to standard output
|
|
202
|
+
On Linux and macOS, the output can be written to standard output, e.g. `-f mpegts -`, to pipe it to another program. The progress bar is then shown on standard error. This is not supported on Windows, where FFmpeg's progress is read from its standard output.
|
|
203
|
+
|
|
204
|
+
## Duration detection
|
|
205
|
+
FFprobe is looked for next to the FFmpeg executable first (e.g. `/opt/ffmpeg/bin/ffprobe` for `/opt/ffmpeg/bin/ffmpeg`), then in `PATH`. If it does not finish within 30 seconds, e.g. for an unresponsive URL, the duration is treated as unknown.
|
|
153
206
|
## Limitations
|
|
154
207
|
- Progress is calculated from the duration of the first input (the first `-i`).
|
|
155
208
|
- The last argument of the command is treated as the output file, e.g. when checking whether it already exists. With multiple outputs, only the last one is checked.
|
|
156
209
|
|
|
157
210
|
## Development
|
|
158
|
-
Install the package in editable mode with the
|
|
211
|
+
Install the package in editable mode with the development dependencies, then run the tests (FFmpeg and FFprobe must be installed):
|
|
159
212
|
```bash
|
|
160
|
-
pip install -e ".[
|
|
213
|
+
pip install -e ".[dev]"
|
|
161
214
|
```
|
|
162
215
|
```bash
|
|
163
216
|
pytest
|
|
164
217
|
```
|
|
218
|
+
Lint, format and type-check the code like CI does:
|
|
219
|
+
```bash
|
|
220
|
+
ruff check .
|
|
221
|
+
```
|
|
222
|
+
```bash
|
|
223
|
+
ruff format --check better_ffmpeg_progress tests test.py
|
|
224
|
+
```
|
|
225
|
+
```bash
|
|
226
|
+
mypy
|
|
227
|
+
```
|
|
165
228
|
`test.py` is a standalone example that encodes a test pattern and shows the progress bar.
|
|
166
229
|
|
|
167
230
|
## Publishing
|
|
@@ -1,24 +1,3 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: better-ffmpeg-progress
|
|
3
|
-
Version: 6.0.1
|
|
4
|
-
Summary: Run FFmpeg & see percentage progress + ETA.
|
|
5
|
-
Author-email: "GitHub.com/CrypticSignal" <theaudiophile@outlook.com>
|
|
6
|
-
License-Expression: MIT
|
|
7
|
-
Project-URL: Homepage, https://github.com/CrypticSignal/better-ffmpeg-progress
|
|
8
|
-
Project-URL: Changelog, https://github.com/CrypticSignal/better-ffmpeg-progress/blob/main/CHANGELOG.md
|
|
9
|
-
Keywords: ffmpeg,progress
|
|
10
|
-
Classifier: Programming Language :: Python :: 3
|
|
11
|
-
Classifier: Operating System :: OS Independent
|
|
12
|
-
Classifier: Typing :: Typed
|
|
13
|
-
Requires-Python: >=3.9
|
|
14
|
-
Description-Content-Type: text/markdown
|
|
15
|
-
License-File: LICENSE
|
|
16
|
-
Requires-Dist: rich
|
|
17
|
-
Requires-Dist: tqdm
|
|
18
|
-
Provides-Extra: test
|
|
19
|
-
Requires-Dist: pytest; extra == "test"
|
|
20
|
-
Dynamic: license-file
|
|
21
|
-
|
|
22
1
|
<div align="center">
|
|
23
2
|
|
|
24
3
|
# Better FFmpeg Progress
|
|
@@ -140,28 +119,78 @@ An instance of `FfmpegProcess` accepts the following optional arguments:
|
|
|
140
119
|
* `duration_override` — Specify input file duration in seconds to use for progress calculation, instead of trying to detect this automatically with FFprobe. Default: `None`.
|
|
141
120
|
* `use_tqdm` — Use tqdm instead of Rich for the progress bar. Default: `False`.
|
|
142
121
|
* `overwrite` — What to do if the output file already exists: `True` overwrites it, `False` raises `FfmpegCommandError`, and `None` asks whether to overwrite it. Ignored if the command contains `-y` or `-n`. Default: `None`.
|
|
122
|
+
* `quiet` — Do not show a progress bar or status messages. Default: `False`.
|
|
123
|
+
* `progress_callback` — A function to call each time FFmpeg reports its progress. See [Progress callback](#progress-callback). Default: `None`.
|
|
124
|
+
* `delete_log_on_success` — Delete the FFmpeg log file if FFmpeg succeeds. Default: `False`.
|
|
125
|
+
|
|
126
|
+
Creating an `FfmpegProcess` only validates the command. FFprobe is run, and you are asked whether to overwrite an existing output file, when `run()` is called.
|
|
143
127
|
|
|
144
128
|
The `run` method accepts the following optional argument:
|
|
145
129
|
* `print_command` — Print the FFmpeg command being executed. Default: `False`.
|
|
146
130
|
|
|
147
131
|
## Using tqdm
|
|
148
|
-
By default, the [Rich](https://github.com/Textualize/rich) library is used to display a progress bar. [tqdm](https://github.com/tqdm/tqdm) can be used instead by passing `use_tqdm=True
|
|
132
|
+
By default, the [Rich](https://github.com/Textualize/rich) library is used to display a progress bar. [tqdm](https://github.com/tqdm/tqdm) can be used instead by passing `use_tqdm=True`. tqdm is an optional dependency, installed with:
|
|
133
|
+
```bash
|
|
134
|
+
pip install "better-ffmpeg-progress[tqdm]" --upgrade
|
|
135
|
+
```
|
|
149
136
|
```python
|
|
150
137
|
process = FfmpegProcess(command, use_tqdm=True)
|
|
151
138
|
process.run()
|
|
152
139
|
```
|
|
140
|
+
|
|
141
|
+
## Progress callback
|
|
142
|
+
To show progress in your own UI (e.g. a GUI or a web app), pass a function as `progress_callback`. It is called with the number of seconds processed, the expected output duration in seconds (`None` if it is unknown) and the current output size in MB. Combine it with `quiet=True` to hide the progress bar:
|
|
143
|
+
```python
|
|
144
|
+
def on_progress(secs: float, duration: float | None, size_mb: float) -> None:
|
|
145
|
+
if duration:
|
|
146
|
+
print(f"{secs / duration:.0%}")
|
|
147
|
+
|
|
148
|
+
FfmpegProcess(command, quiet=True, progress_callback=on_progress).run()
|
|
149
|
+
```
|
|
150
|
+
If the callback raises an exception, FFmpeg is stopped and the exception is propagated by `run()`.
|
|
151
|
+
|
|
152
|
+
## Errors
|
|
153
|
+
All exceptions raised by the package are subclasses of `FfmpegProcessError`, which has these attributes:
|
|
154
|
+
* `returncode` — FFmpeg's exit code, or `None` if FFmpeg was not started or had not exited.
|
|
155
|
+
* `log_file` — The path or file object that FFmpeg's log was written to.
|
|
156
|
+
|
|
157
|
+
Pressing Ctrl+C raises `FfmpegProcessInterruptedError`. FFmpeg is first asked to stop the way pressing `q` does, so it can finish writing the output file, e.g. an MP4 file stays playable. If it does not stop within 5 seconds, it is terminated.
|
|
158
|
+
|
|
159
|
+
## Logging
|
|
160
|
+
Warnings, such as when the input duration cannot be detected, are logged with the `logging` module using the `better_ffmpeg_progress` logger. Without any logging configuration, Python prints them to standard error. To hide them:
|
|
161
|
+
```python
|
|
162
|
+
import logging
|
|
163
|
+
|
|
164
|
+
logging.getLogger("better_ffmpeg_progress").setLevel(logging.ERROR)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Writing to standard output
|
|
168
|
+
On Linux and macOS, the output can be written to standard output, e.g. `-f mpegts -`, to pipe it to another program. The progress bar is then shown on standard error. This is not supported on Windows, where FFmpeg's progress is read from its standard output.
|
|
169
|
+
|
|
170
|
+
## Duration detection
|
|
171
|
+
FFprobe is looked for next to the FFmpeg executable first (e.g. `/opt/ffmpeg/bin/ffprobe` for `/opt/ffmpeg/bin/ffmpeg`), then in `PATH`. If it does not finish within 30 seconds, e.g. for an unresponsive URL, the duration is treated as unknown.
|
|
153
172
|
## Limitations
|
|
154
173
|
- Progress is calculated from the duration of the first input (the first `-i`).
|
|
155
174
|
- The last argument of the command is treated as the output file, e.g. when checking whether it already exists. With multiple outputs, only the last one is checked.
|
|
156
175
|
|
|
157
176
|
## Development
|
|
158
|
-
Install the package in editable mode with the
|
|
177
|
+
Install the package in editable mode with the development dependencies, then run the tests (FFmpeg and FFprobe must be installed):
|
|
159
178
|
```bash
|
|
160
|
-
pip install -e ".[
|
|
179
|
+
pip install -e ".[dev]"
|
|
161
180
|
```
|
|
162
181
|
```bash
|
|
163
182
|
pytest
|
|
164
183
|
```
|
|
184
|
+
Lint, format and type-check the code like CI does:
|
|
185
|
+
```bash
|
|
186
|
+
ruff check .
|
|
187
|
+
```
|
|
188
|
+
```bash
|
|
189
|
+
ruff format --check better_ffmpeg_progress tests test.py
|
|
190
|
+
```
|
|
191
|
+
```bash
|
|
192
|
+
mypy
|
|
193
|
+
```
|
|
165
194
|
`test.py` is a standalone example that encodes a test pattern and shows the progress bar.
|
|
166
195
|
|
|
167
196
|
## Publishing
|
{better_ffmpeg_progress-6.0.1 → better_ffmpeg_progress-7.0.0}/better_ffmpeg_progress/__init__.py
RENAMED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
__version__ = "
|
|
1
|
+
__version__ = "7.0.0"
|
|
2
2
|
|
|
3
3
|
from .better_ffmpeg_progress import FfmpegProcess
|
|
4
4
|
from .enums import FfmpegLogLevel
|
|
5
5
|
from .exceptions import (
|
|
6
|
-
FfmpegProcessError,
|
|
7
6
|
FfmpegCommandError,
|
|
8
|
-
|
|
7
|
+
FfmpegProcessError,
|
|
9
8
|
FfmpegProcessInterruptedError,
|
|
9
|
+
FfmpegProcessUserCancelledError,
|
|
10
10
|
)
|
|
11
11
|
|
|
12
12
|
__all__ = [
|
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import IO, Any, TextIO
|
|
13
|
+
|
|
14
|
+
from .enums import FfmpegLogLevel
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
FfmpegCommandError,
|
|
17
|
+
FfmpegProcessError,
|
|
18
|
+
FfmpegProcessInterruptedError,
|
|
19
|
+
FfmpegProcessUserCancelledError,
|
|
20
|
+
)
|
|
21
|
+
from .progress_bars import make_display
|
|
22
|
+
from .terminate_process import terminate_ffmpeg_process
|
|
23
|
+
from .utils import (
|
|
24
|
+
build_failure_message,
|
|
25
|
+
find_ffprobe,
|
|
26
|
+
get_expected_output_duration,
|
|
27
|
+
get_media_duration,
|
|
28
|
+
is_lavfi_input,
|
|
29
|
+
is_local_file_input,
|
|
30
|
+
is_stdin_input,
|
|
31
|
+
read_progress,
|
|
32
|
+
truncate_filename,
|
|
33
|
+
validate_ffmpeg_command,
|
|
34
|
+
writes_to_stdout,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
_MAX_FILENAME_LENGTH = 60
|
|
38
|
+
|
|
39
|
+
ProgressCallback = Callable[[float, "float | None", float], None]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _safe_filename(name: str) -> str:
|
|
43
|
+
"""Replaces characters that are not valid in filenames on every OS."""
|
|
44
|
+
return re.sub(r"[^\w.,-]", "_", name)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _parse_log_level(ffmpeg_log_level: FfmpegLogLevel | str | None) -> FfmpegLogLevel:
|
|
48
|
+
if ffmpeg_log_level is None:
|
|
49
|
+
return FfmpegLogLevel.VERBOSE
|
|
50
|
+
if isinstance(ffmpeg_log_level, FfmpegLogLevel):
|
|
51
|
+
return ffmpeg_log_level
|
|
52
|
+
if not isinstance(ffmpeg_log_level, str):
|
|
53
|
+
raise TypeError(
|
|
54
|
+
"ffmpeg_log_level must be an FfmpegLogLevel, a string or None, not "
|
|
55
|
+
f"{type(ffmpeg_log_level).__name__}"
|
|
56
|
+
)
|
|
57
|
+
try:
|
|
58
|
+
return FfmpegLogLevel(ffmpeg_log_level.lower())
|
|
59
|
+
except ValueError:
|
|
60
|
+
valid_levels = [level.value for level in FfmpegLogLevel]
|
|
61
|
+
raise FfmpegCommandError(
|
|
62
|
+
f"Invalid ffmpeg_log_level string: '{ffmpeg_log_level}'. "
|
|
63
|
+
f"Must be one of {valid_levels} (case-insensitive)."
|
|
64
|
+
) from None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _parse_duration_override(duration_override: Any) -> float:
|
|
68
|
+
if isinstance(duration_override, bool):
|
|
69
|
+
raise TypeError("duration_override must be a number of seconds, not bool")
|
|
70
|
+
try:
|
|
71
|
+
duration = float(duration_override)
|
|
72
|
+
except (TypeError, ValueError) as e:
|
|
73
|
+
raise TypeError("duration_override must be a number of seconds or None") from e
|
|
74
|
+
if not math.isfinite(duration) or duration <= 0:
|
|
75
|
+
raise ValueError("duration_override must be a finite number greater than 0")
|
|
76
|
+
return duration
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _default_log_file(command: list[str], input_flag_pos: int) -> Path:
|
|
80
|
+
"""Returns the default log file path, which is named after the input."""
|
|
81
|
+
input_file = command[input_flag_pos + 1]
|
|
82
|
+
|
|
83
|
+
if is_lavfi_input(command, input_flag_pos):
|
|
84
|
+
# A filtergraph such as "testsrc2=size=1920x1080" can contain characters that are not
|
|
85
|
+
# valid in filenames (e.g. ":" on Windows), so name the log after the source instead.
|
|
86
|
+
source_name = _safe_filename(input_file.split("=", 1)[0])
|
|
87
|
+
return Path(f"lavfi_{source_name}_ffmpeg_log.txt")
|
|
88
|
+
if input_file == "-":
|
|
89
|
+
return Path("stdin_ffmpeg_log.txt")
|
|
90
|
+
if is_local_file_input(command, input_flag_pos):
|
|
91
|
+
return Path(f"{Path(input_file).name}_ffmpeg_log.txt")
|
|
92
|
+
# URLs and other protocols (e.g. "pipe:0") can contain characters that are not valid in
|
|
93
|
+
# filenames, such as ":" or "?".
|
|
94
|
+
name = Path(input_file).name or input_file
|
|
95
|
+
return Path(f"{_safe_filename(name)}_ffmpeg_log.txt")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class FfmpegProcess:
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
command: list[str],
|
|
102
|
+
ffmpeg_log_level: FfmpegLogLevel | str | None = None,
|
|
103
|
+
ffmpeg_log_file: str | os.PathLike[str] | IO[Any] | None = None,
|
|
104
|
+
print_detected_duration: bool = False,
|
|
105
|
+
duration_override: float | None = None,
|
|
106
|
+
overwrite: bool | None = None,
|
|
107
|
+
use_tqdm: bool = False,
|
|
108
|
+
quiet: bool = False,
|
|
109
|
+
progress_callback: ProgressCallback | None = None,
|
|
110
|
+
delete_log_on_success: bool = False,
|
|
111
|
+
):
|
|
112
|
+
"""
|
|
113
|
+
Create an FFmpeg process with progress reporting. Nothing is run until run() is called.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
command:
|
|
117
|
+
FFmpeg command as a list of arguments.
|
|
118
|
+
ffmpeg_log_level:
|
|
119
|
+
FFmpeg log level enum or case-insensitive string.
|
|
120
|
+
ffmpeg_log_file:
|
|
121
|
+
File path or file object (with a file descriptor, e.g. one returned by open())
|
|
122
|
+
to which FFmpeg's stderr is written.
|
|
123
|
+
print_detected_duration:
|
|
124
|
+
Print the duration used for progress calculation.
|
|
125
|
+
duration_override:
|
|
126
|
+
Specify input file duration in seconds to use for progress calculation, instead
|
|
127
|
+
of trying to detect this automatically with FFprobe. This is useful for partial,
|
|
128
|
+
damaged, streamed, or synthetic inputs whose duration cannot be detected
|
|
129
|
+
correctly.
|
|
130
|
+
overwrite:
|
|
131
|
+
What to do if the output file already exists. True overwrites it, False raises
|
|
132
|
+
FfmpegCommandError, and None (the default) asks the user. Ignored if the command
|
|
133
|
+
contains -y or -n.
|
|
134
|
+
use_tqdm:
|
|
135
|
+
Use tqdm instead of Rich for the progress bar. Requires tqdm, which can be
|
|
136
|
+
installed with `pip install better-ffmpeg-progress[tqdm]`.
|
|
137
|
+
quiet:
|
|
138
|
+
Do not show a progress bar or status messages.
|
|
139
|
+
progress_callback:
|
|
140
|
+
A function called each time FFmpeg reports its progress, with the number of
|
|
141
|
+
seconds processed, the expected output duration in seconds (or None if it is
|
|
142
|
+
unknown) and the current output size in MB. If it raises an exception, FFmpeg
|
|
143
|
+
is stopped and the exception is propagated.
|
|
144
|
+
delete_log_on_success:
|
|
145
|
+
Delete the log file if FFmpeg succeeds. Only applies when the log is written to
|
|
146
|
+
a regular file given by path (or the default log file).
|
|
147
|
+
"""
|
|
148
|
+
validate_ffmpeg_command(command)
|
|
149
|
+
self._log_level = _parse_log_level(ffmpeg_log_level)
|
|
150
|
+
if overwrite is not None and not isinstance(overwrite, bool):
|
|
151
|
+
raise TypeError("overwrite must be True, False or None")
|
|
152
|
+
if progress_callback is not None and not callable(progress_callback):
|
|
153
|
+
raise TypeError("progress_callback must be callable or None")
|
|
154
|
+
if use_tqdm:
|
|
155
|
+
try:
|
|
156
|
+
import tqdm # noqa: F401
|
|
157
|
+
except ImportError:
|
|
158
|
+
raise FfmpegCommandError(
|
|
159
|
+
"use_tqdm=True requires tqdm. Install it with: "
|
|
160
|
+
"pip install better-ffmpeg-progress[tqdm]"
|
|
161
|
+
) from None
|
|
162
|
+
|
|
163
|
+
self._writes_to_stdout = writes_to_stdout(command)
|
|
164
|
+
if self._writes_to_stdout and os.name == "nt":
|
|
165
|
+
raise FfmpegCommandError(
|
|
166
|
+
"Writing the output to standard output is not supported on Windows."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
self._command = list(command)
|
|
170
|
+
input_flag_pos = command.index("-i")
|
|
171
|
+
self._input_file = command[input_flag_pos + 1]
|
|
172
|
+
self._input_filepath = Path(self._input_file)
|
|
173
|
+
# Assumes the last argument is the output.
|
|
174
|
+
self._output_filepath = Path(command[-1])
|
|
175
|
+
|
|
176
|
+
self._ffmpeg_log_file: Path | IO[Any]
|
|
177
|
+
if ffmpeg_log_file is None:
|
|
178
|
+
self._ffmpeg_log_file = _default_log_file(command, input_flag_pos)
|
|
179
|
+
elif isinstance(ffmpeg_log_file, (str, os.PathLike)):
|
|
180
|
+
self._ffmpeg_log_file = Path(ffmpeg_log_file)
|
|
181
|
+
else:
|
|
182
|
+
self._ffmpeg_log_file = ffmpeg_log_file
|
|
183
|
+
|
|
184
|
+
self._duration_override = (
|
|
185
|
+
_parse_duration_override(duration_override) if duration_override is not None else None
|
|
186
|
+
)
|
|
187
|
+
self._print_detected_duration = print_detected_duration
|
|
188
|
+
self._overwrite = overwrite
|
|
189
|
+
self._quiet = quiet
|
|
190
|
+
self._progress_callback = progress_callback
|
|
191
|
+
self._delete_log_on_success = delete_log_on_success
|
|
192
|
+
self._duration_secs: float | None = None
|
|
193
|
+
self._process: subprocess.Popen[bytes] | None = None
|
|
194
|
+
self.use_tqdm: bool = use_tqdm
|
|
195
|
+
|
|
196
|
+
@property
|
|
197
|
+
def _message_stream(self) -> TextIO:
|
|
198
|
+
"""
|
|
199
|
+
Where the progress bar and messages are written. If FFmpeg writes the output to standard
|
|
200
|
+
output, they are written to standard error, so they do not get mixed with the output.
|
|
201
|
+
"""
|
|
202
|
+
return sys.stderr if self._writes_to_stdout else sys.stdout
|
|
203
|
+
|
|
204
|
+
def _get_output_duration(self) -> float | None:
|
|
205
|
+
"""Returns the expected duration of the output in seconds, or None if it is unknown."""
|
|
206
|
+
if self._duration_override is not None:
|
|
207
|
+
input_duration_secs: float | None = self._duration_override
|
|
208
|
+
elif is_stdin_input(self._input_file):
|
|
209
|
+
# Running FFprobe on standard input would consume data that is meant for FFmpeg.
|
|
210
|
+
input_duration_secs = None
|
|
211
|
+
else:
|
|
212
|
+
input_duration_secs = get_media_duration(
|
|
213
|
+
self._input_file, ffprobe=find_ffprobe(self._command[0])
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
# Account for trimming (-ss, -sseof, -t, -to) so the progress bar reflects the
|
|
217
|
+
# duration of the output rather than the whole input.
|
|
218
|
+
duration_secs = (
|
|
219
|
+
get_expected_output_duration(self._command, input_duration_secs)
|
|
220
|
+
if input_duration_secs is not None
|
|
221
|
+
else None
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
if self._print_detected_duration or (
|
|
225
|
+
self._duration_override is not None and not self._quiet
|
|
226
|
+
):
|
|
227
|
+
stream = self._message_stream
|
|
228
|
+
if input_duration_secs is None:
|
|
229
|
+
print(
|
|
230
|
+
"Could not detect duration. Progress bar may not show time remaining.",
|
|
231
|
+
file=stream,
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
label = (
|
|
235
|
+
"Using duration override"
|
|
236
|
+
if self._duration_override is not None
|
|
237
|
+
else "Detected duration"
|
|
238
|
+
)
|
|
239
|
+
print(f"{label}: {input_duration_secs:.2f} seconds", file=stream)
|
|
240
|
+
if duration_secs != input_duration_secs:
|
|
241
|
+
print(
|
|
242
|
+
f"Expected output duration after trimming: {duration_secs:.2f} seconds",
|
|
243
|
+
file=stream,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
return duration_secs
|
|
247
|
+
|
|
248
|
+
def _should_overwrite(self) -> bool:
|
|
249
|
+
"""
|
|
250
|
+
Returns True if "-y" must be added to the command because the output file exists and may be
|
|
251
|
+
overwritten. Raises an FfmpegProcessError if it must not be overwritten.
|
|
252
|
+
"""
|
|
253
|
+
user_args = self._command[1:]
|
|
254
|
+
if "-y" in user_args or self._writes_to_stdout or not self._output_filepath.exists():
|
|
255
|
+
return False
|
|
256
|
+
if "-n" in user_args or self._overwrite is False:
|
|
257
|
+
raise FfmpegCommandError(
|
|
258
|
+
f"Output file {self._output_filepath} already exists and overwriting is disabled."
|
|
259
|
+
)
|
|
260
|
+
if self._overwrite is None:
|
|
261
|
+
if is_stdin_input(self._input_file):
|
|
262
|
+
# Prompting would read from standard input, which carries FFmpeg's input.
|
|
263
|
+
raise FfmpegCommandError(
|
|
264
|
+
f"Output file {self._output_filepath} already exists. Pass "
|
|
265
|
+
"overwrite=True or add -y to the command to overwrite it."
|
|
266
|
+
)
|
|
267
|
+
self._ask_to_overwrite()
|
|
268
|
+
return True
|
|
269
|
+
|
|
270
|
+
def _ask_to_overwrite(self) -> None:
|
|
271
|
+
"""Raises an FfmpegProcessError unless the user agrees to overwrite the output file."""
|
|
272
|
+
try:
|
|
273
|
+
answer = input(
|
|
274
|
+
f"Output file {self._output_filepath} already exists. Overwrite? [y/N]: "
|
|
275
|
+
)
|
|
276
|
+
except KeyboardInterrupt as e:
|
|
277
|
+
raise FfmpegProcessInterruptedError(
|
|
278
|
+
"[KeyboardInterrupt] FFmpeg process cancelled during overwrite prompt."
|
|
279
|
+
) from e
|
|
280
|
+
except EOFError as e:
|
|
281
|
+
raise FfmpegProcessInterruptedError(
|
|
282
|
+
"Input error (EOF) during overwrite prompt. FFmpeg process cancelled."
|
|
283
|
+
) from e
|
|
284
|
+
|
|
285
|
+
if answer.strip().lower() != "y":
|
|
286
|
+
raise FfmpegProcessUserCancelledError(
|
|
287
|
+
"FFmpeg process cancelled. Output file exists and overwrite declined."
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
def _build_command(self, progress_url: str, overwrite: bool) -> list[str]:
|
|
291
|
+
return [
|
|
292
|
+
self._command[0],
|
|
293
|
+
*(["-y"] if overwrite else []),
|
|
294
|
+
"-hide_banner",
|
|
295
|
+
"-loglevel",
|
|
296
|
+
self._log_level.value,
|
|
297
|
+
"-progress",
|
|
298
|
+
progress_url,
|
|
299
|
+
"-nostats",
|
|
300
|
+
*self._command[1:],
|
|
301
|
+
]
|
|
302
|
+
|
|
303
|
+
def run(self, print_command: bool = False) -> None:
|
|
304
|
+
"""
|
|
305
|
+
Runs FFmpeg and shows its progress until it exits.
|
|
306
|
+
|
|
307
|
+
Raises:
|
|
308
|
+
FfmpegProcessError: If FFmpeg fails, or cannot be started. Its returncode and
|
|
309
|
+
log_file attributes are set when available.
|
|
310
|
+
FfmpegProcessInterruptedError: If Ctrl+C is pressed. FFmpeg is stopped first.
|
|
311
|
+
"""
|
|
312
|
+
overwrite = self._should_overwrite()
|
|
313
|
+
self._duration_secs = self._get_output_duration()
|
|
314
|
+
|
|
315
|
+
if isinstance(self._ffmpeg_log_file, Path):
|
|
316
|
+
log_file: Any = open(self._ffmpeg_log_file, "w", encoding="utf-8")
|
|
317
|
+
else:
|
|
318
|
+
log_file = contextlib.nullcontext(self._ffmpeg_log_file)
|
|
319
|
+
|
|
320
|
+
# FFmpeg's progress is read from a pipe. On POSIX, a separate pipe is used, so FFmpeg's
|
|
321
|
+
# standard output stays free for the output (e.g. "-f mpegts -"). On Windows, where
|
|
322
|
+
# passing extra file descriptors is not supported, standard output is used.
|
|
323
|
+
read_fd: int | None = None
|
|
324
|
+
write_fd: int | None = None
|
|
325
|
+
popen_kwargs: dict[str, Any]
|
|
326
|
+
if os.name == "nt":
|
|
327
|
+
progress_url = "pipe:1"
|
|
328
|
+
# Run FFmpeg in its own process group, so that pressing Ctrl+C does not send the
|
|
329
|
+
# signal to FFmpeg directly.
|
|
330
|
+
popen_kwargs = {
|
|
331
|
+
"stdout": subprocess.PIPE,
|
|
332
|
+
"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
|
|
333
|
+
}
|
|
334
|
+
else:
|
|
335
|
+
read_fd, write_fd = os.pipe()
|
|
336
|
+
progress_url = f"pipe:{write_fd}"
|
|
337
|
+
# Run FFmpeg in its own session, so that pressing Ctrl+C does not send the signal to
|
|
338
|
+
# FFmpeg directly, and terminating its process group does not terminate Python.
|
|
339
|
+
popen_kwargs = {"pass_fds": (write_fd,), "start_new_session": True}
|
|
340
|
+
|
|
341
|
+
# FFmpeg reads commands such as "q" from standard input. Unless standard input carries
|
|
342
|
+
# FFmpeg's input, give it a pipe instead, so it does not consume data meant for this
|
|
343
|
+
# program or change the terminal's settings. Writing "q" to the pipe stops FFmpeg
|
|
344
|
+
# cleanly (see terminate_ffmpeg_process).
|
|
345
|
+
stdin = None if is_stdin_input(self._input_file) else subprocess.PIPE
|
|
346
|
+
|
|
347
|
+
ffmpeg_command = self._build_command(progress_url, overwrite)
|
|
348
|
+
if print_command:
|
|
349
|
+
print(f"Executing: {shlex.join(ffmpeg_command)}", file=self._message_stream)
|
|
350
|
+
|
|
351
|
+
try:
|
|
352
|
+
# FFmpeg keeps its own handle to the log file, so it can be closed here.
|
|
353
|
+
with log_file as stderr:
|
|
354
|
+
self._process = subprocess.Popen(
|
|
355
|
+
ffmpeg_command, stdin=stdin, stderr=stderr, **popen_kwargs
|
|
356
|
+
)
|
|
357
|
+
except Exception as e:
|
|
358
|
+
if read_fd is not None:
|
|
359
|
+
os.close(read_fd)
|
|
360
|
+
raise FfmpegProcessError(
|
|
361
|
+
f"Error starting FFmpeg process: {e}", log_file=self._ffmpeg_log_file
|
|
362
|
+
) from e
|
|
363
|
+
finally:
|
|
364
|
+
# FFmpeg has its own copy of the write end. Closing this one means reading the pipe
|
|
365
|
+
# ends when FFmpeg exits.
|
|
366
|
+
if write_fd is not None:
|
|
367
|
+
os.close(write_fd)
|
|
368
|
+
|
|
369
|
+
process = self._process
|
|
370
|
+
if read_fd is not None:
|
|
371
|
+
progress_stream: IO[bytes] = os.fdopen(read_fd, "rb")
|
|
372
|
+
else:
|
|
373
|
+
assert process.stdout is not None
|
|
374
|
+
progress_stream = process.stdout
|
|
375
|
+
|
|
376
|
+
filename = truncate_filename(self._input_filepath.name, _MAX_FILENAME_LENGTH)
|
|
377
|
+
display = make_display(
|
|
378
|
+
filename, self._duration_secs, self._message_stream, self._quiet, self.use_tqdm
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
try:
|
|
382
|
+
# The progress output must always be read, even if it is not displayed: once the
|
|
383
|
+
# pipe's buffer is full, FFmpeg blocks and never exits.
|
|
384
|
+
with progress_stream, display:
|
|
385
|
+
size_mb = 0.0
|
|
386
|
+
for secs, size_mb in read_progress(progress_stream, self._duration_secs):
|
|
387
|
+
display.update(secs, size_mb)
|
|
388
|
+
if self._progress_callback is not None:
|
|
389
|
+
self._progress_callback(secs, self._duration_secs, size_mb)
|
|
390
|
+
returncode = process.wait()
|
|
391
|
+
if returncode == 0:
|
|
392
|
+
display.complete(size_mb)
|
|
393
|
+
except KeyboardInterrupt as e:
|
|
394
|
+
terminate_ffmpeg_process(process)
|
|
395
|
+
raise FfmpegProcessInterruptedError(
|
|
396
|
+
"[KeyboardInterrupt] FFmpeg process cancelled.",
|
|
397
|
+
returncode=process.returncode,
|
|
398
|
+
log_file=self._ffmpeg_log_file,
|
|
399
|
+
) from e
|
|
400
|
+
except BaseException:
|
|
401
|
+
# e.g. an exception raised by progress_callback.
|
|
402
|
+
terminate_ffmpeg_process(process)
|
|
403
|
+
raise
|
|
404
|
+
finally:
|
|
405
|
+
if process.stdin is not None:
|
|
406
|
+
with contextlib.suppress(OSError):
|
|
407
|
+
process.stdin.close()
|
|
408
|
+
|
|
409
|
+
if returncode != 0:
|
|
410
|
+
raise FfmpegProcessError(
|
|
411
|
+
build_failure_message(self._ffmpeg_log_file),
|
|
412
|
+
returncode=returncode,
|
|
413
|
+
log_file=self._ffmpeg_log_file,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
if (
|
|
417
|
+
self._delete_log_on_success
|
|
418
|
+
and isinstance(self._ffmpeg_log_file, Path)
|
|
419
|
+
# Never delete e.g. os.devnull.
|
|
420
|
+
and self._ffmpeg_log_file.is_file()
|
|
421
|
+
):
|
|
422
|
+
with contextlib.suppress(OSError):
|
|
423
|
+
self._ffmpeg_log_file.unlink()
|