|
6 | 6 | import shutil |
7 | 7 | import subprocess |
8 | 8 | import tempfile |
| 9 | +from typing import List, Optional |
9 | 10 |
|
10 | 11 | from zimscraperlib import logger |
11 | 12 | from zimscraperlib.logging import nicer_args_join |
12 | 13 |
|
13 | 14 |
|
| 15 | +def _build_ffmpeg_args( |
| 16 | + src_path: pathlib.Path, |
| 17 | + tmp_path: pathlib.Path, |
| 18 | + ffmpeg_args: List[str], |
| 19 | + threads: Optional[int], |
| 20 | +) -> List[str]: |
| 21 | + if threads: |
| 22 | + if "-threads" in ffmpeg_args: |
| 23 | + raise AttributeError("Cannot set the number of threads, already set") |
| 24 | + else: |
| 25 | + ffmpeg_args += ["-threads", str(threads)] |
| 26 | + args = [ |
| 27 | + "/usr/bin/env", |
| 28 | + "ffmpeg", |
| 29 | + "-y", |
| 30 | + "-i", |
| 31 | + f"file:{src_path}", |
| 32 | + *ffmpeg_args, |
| 33 | + f"file:{tmp_path}", |
| 34 | + ] |
| 35 | + return args |
| 36 | + |
| 37 | + |
14 | 38 | def reencode( |
15 | 39 | src_path, |
16 | 40 | dst_path, |
17 | 41 | ffmpeg_args, |
18 | 42 | delete_src=False, # noqa: FBT002 |
19 | 43 | with_process=False, # noqa: FBT002 |
20 | 44 | failsafe=True, # noqa: FBT002 |
| 45 | + threads: Optional[int] = 1, |
21 | 46 | ): |
22 | 47 | """Runs ffmpeg with given ffmpeg_args |
23 | 48 |
|
24 | 49 | Arguments - |
25 | 50 | src_path - Path to source file |
26 | 51 | dst_path - Path to destination file |
27 | 52 | ffmpeg_args - A list of ffmpeg arguments |
| 53 | + threads - Number of encoding threads used by ffmpeg |
28 | 54 | delete_src - Delete source file after convertion |
29 | 55 | with_process - Optionally return the output from ffmpeg (stderr and stdout) |
30 | 56 | failsafe - Run in failsafe mode |
31 | 57 | """ |
32 | 58 |
|
33 | 59 | with tempfile.TemporaryDirectory() as tmp_dir: |
34 | 60 | tmp_path = pathlib.Path(tmp_dir).joinpath(f"video.tmp{dst_path.suffix}") |
35 | | - args = [ |
36 | | - "/usr/bin/env", |
37 | | - "ffmpeg", |
38 | | - "-y", |
39 | | - "-i", |
40 | | - f"file:{src_path}", |
41 | | - *ffmpeg_args, |
42 | | - f"file:{tmp_path}", |
43 | | - ] |
| 61 | + args = _build_ffmpeg_args( |
| 62 | + src_path=src_path, |
| 63 | + tmp_path=tmp_path, |
| 64 | + ffmpeg_args=ffmpeg_args, |
| 65 | + threads=threads, |
| 66 | + ) |
44 | 67 | logger.debug( |
45 | 68 | f"Encode {src_path} -> {dst_path} video format = {dst_path.suffix}" |
46 | 69 | ) |
|
0 commit comments