ffmpeg-normalize 1.44.1__tar.gz → 1.45.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.
Files changed (20) hide show
  1. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/PKG-INFO +8 -4
  2. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/README.md +5 -0
  3. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/pyproject.toml +3 -5
  4. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/pyproject.toml.orig +3 -5
  5. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/__main__.py +89 -17
  6. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_cmd_utils.py +125 -8
  7. ffmpeg_normalize-1.45.0/src/ffmpeg_normalize/_console.py +189 -0
  8. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_ffmpeg_normalize.py +188 -71
  9. ffmpeg_normalize-1.45.0/src/ffmpeg_normalize/_logger.py +63 -0
  10. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_media_file.py +7 -28
  11. ffmpeg_normalize-1.44.1/src/ffmpeg_normalize/_logger.py +0 -72
  12. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/LICENSE.md +0 -0
  13. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/__init__.py +0 -0
  14. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_errors.py +0 -0
  15. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_presets.py +0 -0
  16. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/_streams.py +0 -0
  17. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/data/presets/music.json +0 -0
  18. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/data/presets/podcast.json +0 -0
  19. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/data/presets/streaming-video.json +0 -0
  20. {ffmpeg_normalize-1.44.1 → ffmpeg_normalize-1.45.0}/src/ffmpeg_normalize/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ffmpeg-normalize
3
- Version: 1.44.1
3
+ Version: 1.45.0
4
4
  Summary: Normalize audio via ffmpeg
5
5
  Keywords: ffmpeg,normalize,audio
6
6
  Author: Werner Robitza
@@ -20,11 +20,10 @@ Classifier: Programming Language :: Python :: 3.12
20
20
  Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Programming Language :: Python :: 3.14
22
22
  Classifier: Programming Language :: Python :: 3.15
23
- Requires-Dist: tqdm>=4.64.1
24
- Requires-Dist: colorama>=0.4.6 ; sys_platform == 'win32'
25
23
  Requires-Dist: ffmpeg-progress-yield>=1.0.1
26
- Requires-Dist: colorlog==6.7.0
27
24
  Requires-Dist: mutagen>=1.47.0
25
+ Requires-Dist: rich>=13.7.0
26
+ Requires-Dist: rich-argparse>=1.5.0
28
27
  Requires-Python: >=3.10
29
28
  Project-URL: Homepage, https://github.com/slhck/ffmpeg-normalize
30
29
  Project-URL: Repository, https://github.com/slhck/ffmpeg-normalize
@@ -56,6 +55,7 @@ This program normalizes media files to a certain loudness level using the EBU R1
56
55
  - Selective audio stream normalization — Normalize specific audio streams or only default streams
57
56
  - Skip files already at target — Avoid re-encoding files already within a threshold of the target level
58
57
  - Before/after summary — Print a table of input and output levels and the applied gain for all files with `--print-summary`
58
+ - Friendly terminal output — Colored help and messages, progress bars in interactive terminals, and concise ffmpeg error messages
59
59
  - Self-documenting output — Optionally record the effective encoder settings as an `ENCODER_SETTINGS` tag
60
60
  - Video file support — Process video files while preserving video streams
61
61
  - Docker support — Run via Docker container
@@ -72,6 +72,10 @@ This program normalizes media files to a certain loudness level using the EBU R1
72
72
 
73
73
  ## 🆕 What's New
74
74
 
75
+ - Version 1.45.0 has a **refreshed terminal interface** based on [rich](https://github.com/Textualize/rich): colored `--help` output, colored log messages, progress bars with the current file name and ETA, and a formatted `--print-summary` table. When ffmpeg fails, only the root cause is shown (once), and `--debug` shows the full ffmpeg output for bug reports. Redirected output stays plain text, and the `LEVEL: message` log format is unchanged.
76
+
77
+ > ⚠️ **Breaking change:** Progress bars are now shown **by default** when stderr is an interactive terminal (unless `--quiet` is set). Non-interactive use, e.g. in scripts, cron jobs or with redirected output, is not affected. If you parse the output of an interactive session (for example via a pseudo-terminal), pass `--no-progress` to disable the bars. `-pr`/`--progress` still forces them on.
78
+
75
79
  - Version 1.42.0 can optionally write an **`ENCODER_SETTINGS`** tag on each normalized audio stream via `--write-encoder-settings`. The tag holds an ffmpeg-command-equivalent string — the audio codec, bitrate, sample rate and channels, plus the normalization filter including the measured loudnorm values — so a normalized file documents how it was produced. This is a Matroska/WebM convention and has no effect with `--metadata-disable`.
76
80
 
77
81
  Example:
@@ -24,6 +24,7 @@ This program normalizes media files to a certain loudness level using the EBU R1
24
24
  - Selective audio stream normalization — Normalize specific audio streams or only default streams
25
25
  - Skip files already at target — Avoid re-encoding files already within a threshold of the target level
26
26
  - Before/after summary — Print a table of input and output levels and the applied gain for all files with `--print-summary`
27
+ - Friendly terminal output — Colored help and messages, progress bars in interactive terminals, and concise ffmpeg error messages
27
28
  - Self-documenting output — Optionally record the effective encoder settings as an `ENCODER_SETTINGS` tag
28
29
  - Video file support — Process video files while preserving video streams
29
30
  - Docker support — Run via Docker container
@@ -40,6 +41,10 @@ This program normalizes media files to a certain loudness level using the EBU R1
40
41
 
41
42
  ## 🆕 What's New
42
43
 
44
+ - Version 1.45.0 has a **refreshed terminal interface** based on [rich](https://github.com/Textualize/rich): colored `--help` output, colored log messages, progress bars with the current file name and ETA, and a formatted `--print-summary` table. When ffmpeg fails, only the root cause is shown (once), and `--debug` shows the full ffmpeg output for bug reports. Redirected output stays plain text, and the `LEVEL: message` log format is unchanged.
45
+
46
+ > ⚠️ **Breaking change:** Progress bars are now shown **by default** when stderr is an interactive terminal (unless `--quiet` is set). Non-interactive use, e.g. in scripts, cron jobs or with redirected output, is not affected. If you parse the output of an interactive session (for example via a pseudo-terminal), pass `--no-progress` to disable the bars. `-pr`/`--progress` still forces them on.
47
+
43
48
  - Version 1.42.0 can optionally write an **`ENCODER_SETTINGS`** tag on each normalized audio stream via `--write-encoder-settings`. The tag holds an ffmpeg-command-equivalent string — the audio codec, bitrate, sample rate and channels, plus the normalization filter including the measured loudnorm values — so a normalized file documents how it was produced. This is a Matroska/WebM convention and has no effect with `--metadata-disable`.
44
49
 
45
50
  Example:
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ffmpeg-normalize"
7
- version = "1.44.1"
7
+ version = "1.45.0"
8
8
  description = "Normalize audio via ffmpeg"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -31,11 +31,10 @@ classifiers = [
31
31
  ]
32
32
  requires-python = ">=3.10"
33
33
  dependencies = [
34
- "tqdm>=4.64.1",
35
- "colorama>=0.4.6; platform_system=='Windows'",
36
34
  "ffmpeg-progress-yield>=1.0.1",
37
- "colorlog==6.7.0",
38
35
  "mutagen>=1.47.0",
36
+ "rich>=13.7.0",
37
+ "rich-argparse>=1.5.0",
39
38
  ]
40
39
 
41
40
  [[project.authors]]
@@ -63,7 +62,6 @@ too-many-positional-arguments = "warn"
63
62
  dev = [
64
63
  "pytest>=9.0.3",
65
64
  "ruff>=0.12.11",
66
- "types-tqdm",
67
65
  "shtab>=1.7.0",
68
66
  "ty>=0.0.24",
69
67
  ]
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ffmpeg-normalize"
7
- version = "1.44.1"
7
+ version = "1.45.0"
8
8
  description = "Normalize audio via ffmpeg"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -30,11 +30,10 @@ classifiers = [
30
30
  ]
31
31
  requires-python = ">=3.10"
32
32
  dependencies = [
33
- "tqdm>=4.64.1",
34
- "colorama>=0.4.6; platform_system=='Windows'",
35
33
  "ffmpeg-progress-yield>=1.0.1",
36
- "colorlog==6.7.0",
37
34
  "mutagen>=1.47.0",
35
+ "rich>=13.7.0",
36
+ "rich-argparse>=1.5.0",
38
37
  ]
39
38
 
40
39
  [project.urls]
@@ -52,7 +51,6 @@ package-data = {"ffmpeg_normalize" = ["data/**/*.json"]}
52
51
  dev = [
53
52
  "pytest>=9.0.3",
54
53
  "ruff>=0.12.11",
55
- "types-tqdm",
56
54
  "shtab>=1.7.0",
57
55
  "ty>=0.0.24",
58
56
  ]
@@ -13,6 +13,11 @@ import textwrap
13
13
  from json.decoder import JSONDecodeError
14
14
  from typing import NoReturn
15
15
 
16
+ from rich.console import Console
17
+ from rich.markup import escape
18
+ from rich_argparse import RawTextRichHelpFormatter
19
+
20
+ from ._console import get_console
16
21
  from ._errors import FFmpegNormalizeError
17
22
  from ._ffmpeg_normalize import NORMALIZATION_TYPES, FFmpegNormalize
18
23
  from ._logger import setup_cli_logger
@@ -20,7 +25,22 @@ from ._presets import PresetManager
20
25
 
21
26
  __version__ = importlib.metadata.version("ffmpeg-normalize")
22
27
 
23
- _logger = logging.getLogger(__name__)
28
+ _logger = logging.getLogger("ffmpeg_normalize.__main__")
29
+
30
+
31
+ class HelpFormatter(RawTextRichHelpFormatter):
32
+ """Colored help output that keeps the manual line breaks of the help texts."""
33
+
34
+ group_name_formatter = str
35
+ styles = {
36
+ **RawTextRichHelpFormatter.styles,
37
+ "argparse.groups": "bold yellow",
38
+ "argparse.args": "cyan",
39
+ "argparse.metavar": "dark_cyan",
40
+ "argparse.prog": "bold green",
41
+ "argparse.syntax": "bold",
42
+ "argparse.text": "default",
43
+ }
24
44
 
25
45
 
26
46
  def create_parser(suppress_defaults: bool = False) -> argparse.ArgumentParser:
@@ -34,7 +54,7 @@ def create_parser(suppress_defaults: bool = False) -> argparse.ArgumentParser:
34
54
  # manually overridden because argparse generates the wrong order of arguments, see:
35
55
  # https://github.com/slhck/ffmpeg-normalize/issues/132#issuecomment-662516535
36
56
  usage="%(prog)s INPUT [INPUT ...] [-o OUTPUT [OUTPUT ...]] [options]",
37
- formatter_class=argparse.RawTextHelpFormatter,
57
+ formatter_class=HelpFormatter,
38
58
  epilog=textwrap.dedent(
39
59
  """\
40
60
  The program additionally respects environment variables:
@@ -132,8 +152,26 @@ def create_parser(suppress_defaults: bool = False) -> argparse.ArgumentParser:
132
152
  group_general.add_argument(
133
153
  "-pr",
134
154
  "--progress",
135
- action="store_true",
136
- help="Show progress bar for files and streams",
155
+ action="store_const",
156
+ const=True,
157
+ dest="progress",
158
+ default=None,
159
+ help=textwrap.dedent(
160
+ """\
161
+ Show progress bars for files and streams.
162
+
163
+ Enabled by default when stderr is an interactive terminal and
164
+ `--quiet` is not set; disabled otherwise (e.g. in scripts or when
165
+ output is redirected). Use this option to force progress output.
166
+ """
167
+ ),
168
+ )
169
+ group_general.add_argument(
170
+ "--no-progress",
171
+ action="store_const",
172
+ const=False,
173
+ dest="progress",
174
+ help="Do not show progress bars, even in an interactive terminal",
137
175
  )
138
176
  group_general.add_argument(
139
177
  "--version",
@@ -702,7 +740,8 @@ def create_parser(suppress_defaults: bool = False) -> argparse.ArgumentParser:
702
740
 
703
741
 
704
742
  def main() -> None:
705
- explicit_args = create_parser(suppress_defaults=True).parse_args()
743
+ parser = create_parser(suppress_defaults=True)
744
+ explicit_args = parser.parse_args()
706
745
  cli_args = create_parser().parse_args([])
707
746
  vars(cli_args).update(vars(explicit_args))
708
747
  setup_cli_logger(arguments=cli_args)
@@ -717,17 +756,27 @@ def main() -> None:
717
756
  # Handle --list-presets
718
757
  preset_manager = PresetManager()
719
758
  if cli_args.list_presets:
759
+ console = Console(highlight=False)
720
760
  presets_with_source = preset_manager.get_presets_with_source()
721
761
  if presets_with_source:
722
- print("Available presets:")
762
+ console.print("[bold]Available presets:[/bold]")
723
763
  for preset_name, source in presets_with_source:
724
- source_label = "(user)" if source == "user" else "(builtin)"
725
- print(f" - {preset_name} {source_label}")
764
+ source_label = (
765
+ "[cyan](user)[/cyan]"
766
+ if source == "user"
767
+ else "[dim](builtin)[/dim]"
768
+ )
769
+ console.print(
770
+ f" - [green]{escape(preset_name)}[/green] {source_label}"
771
+ )
726
772
  else:
727
- print("No presets found.")
728
- print()
729
- print(f"User presets directory: {preset_manager.presets_dir}")
730
- print("Place custom .json preset files in this directory.")
773
+ console.print("No presets found.")
774
+ console.print()
775
+ console.print(
776
+ f"User presets directory: [bold]{escape(str(preset_manager.presets_dir))}[/bold]",
777
+ soft_wrap=True,
778
+ )
779
+ console.print("Place custom .json preset files in this directory.")
731
780
  sys.exit(0)
732
781
 
733
782
  # Load and apply preset if specified
@@ -782,6 +831,12 @@ def main() -> None:
782
831
  if cli_args.audio_default_only and cli_args.audio_streams:
783
832
  error("Cannot use both --audio-default-only and --audio-streams together.")
784
833
 
834
+ # Show progress bars by default only in interactive terminals, so that
835
+ # scripts and redirected output are not cluttered with them.
836
+ progress = cli_args.progress
837
+ if progress is None:
838
+ progress = sys.stderr.isatty() and not cli_args.quiet
839
+
785
840
  try:
786
841
  ffmpeg_normalize = FFmpegNormalize(
787
842
  normalization_type=cli_args.normalization_type,
@@ -816,7 +871,7 @@ def main() -> None:
816
871
  output_format=cli_args.output_format,
817
872
  extension=cli_args.extension,
818
873
  dry_run=cli_args.dry_run,
819
- progress=cli_args.progress,
874
+ progress=progress,
820
875
  replaygain=cli_args.replaygain,
821
876
  batch=cli_args.batch,
822
877
  audio_streams=audio_streams,
@@ -847,7 +902,14 @@ def main() -> None:
847
902
  input_files.extend([line.strip() for line in f if line.strip()])
848
903
 
849
904
  if not input_files:
850
- error("No input files specified. Use positional arguments or --input-list.")
905
+ parser.print_usage(sys.stderr)
906
+ _logger.error(
907
+ "No input files specified. Use positional arguments or --input-list."
908
+ )
909
+ get_console().print(
910
+ "Run [bold cyan]ffmpeg-normalize --help[/bold cyan] to see all options."
911
+ )
912
+ sys.exit(1)
851
913
 
852
914
  # Validate all input files upfront before processing
853
915
  _logger.debug("Validating all input files before processing...")
@@ -930,9 +992,19 @@ def main() -> None:
930
992
  if media_file.status == "error"
931
993
  ]
932
994
  if failed_files:
933
- _logger.error(f"{len(failed_files)} file(s) failed to process:")
934
- for media_file in failed_files:
935
- _logger.error(f" - {media_file.input_file}: {media_file.error}")
995
+ # The individual errors were already logged when each file failed
996
+ _logger.error(
997
+ f"{len(failed_files)} of {len(ffmpeg_normalize.media_files)} file(s) "
998
+ "failed to process: "
999
+ + ", ".join(media_file.input_file for media_file in failed_files)
1000
+ )
1001
+ if not cli_args.debug:
1002
+ get_console().print(
1003
+ "[dim]Re-run with [bold]--debug[/bold] to see the full ffmpeg "
1004
+ "output. Please include it when reporting a bug at "
1005
+ "https://github.com/slhck/ffmpeg-normalize/issues[/dim]",
1006
+ soft_wrap=True,
1007
+ )
936
1008
  sys.exit(1)
937
1009
 
938
1010
 
@@ -77,6 +77,120 @@ _MUXER_NAME_FOR_EXT = {
77
77
  }
78
78
 
79
79
 
80
+ _INFO_LINE_PREFIXES = (
81
+ "input #",
82
+ "output #",
83
+ "metadata:",
84
+ "duration:",
85
+ "stream #",
86
+ "stream mapping:",
87
+ "side data:",
88
+ "chapters:",
89
+ "chapter #",
90
+ "press [q]",
91
+ "frame=",
92
+ "size=",
93
+ "video:",
94
+ # side data entries
95
+ "replay gain:",
96
+ "audio service type:",
97
+ "display matrix:",
98
+ "displaymatrix:",
99
+ "cpb:",
100
+ "stereo 3d:",
101
+ "stereo3d:",
102
+ "mastering display metadata:",
103
+ "content light level metadata:",
104
+ "spherical:",
105
+ "dovi configuration record:",
106
+ "ambient viewing environment:",
107
+ "icc profile:",
108
+ )
109
+ _ERROR_KEYWORDS = re.compile(
110
+ r"error|invalid|unable|could not|cannot|can't|failed|not found|no such|"
111
+ r"permission denied|unknown|unrecognized|not supported|does not|too many|"
112
+ r"unsupported|expected",
113
+ re.IGNORECASE,
114
+ )
115
+ _CONTEXT_PREFIX = re.compile(r"^\[[^\]]+ @ (0x)?[0-9a-fA-F]+\]\s*")
116
+ _KEY_VALUE_LINE = re.compile(r"^[\w.-]+\s{2,}:\s")
117
+
118
+
119
+ def summarize_ffmpeg_output(output: str, max_lines: int = 2) -> str:
120
+ """
121
+ Extract the main error message from ffmpeg's stderr output.
122
+
123
+ ffmpeg prints a lot of context (input/stream information, metadata) before
124
+ the actual error, and reports the root cause before any follow-up errors.
125
+ This skips the context and returns the first lines after it, without the
126
+ `[component @ 0x...]` prefixes. If there is no such line, the first lines
127
+ that look like errors are used instead.
128
+
129
+ Args:
130
+ output (str): The stderr output of ffmpeg
131
+ max_lines (int, optional): Maximum number of lines to keep. Defaults to 2.
132
+
133
+ Returns:
134
+ str: The error message, with multiple lines joined by "; "
135
+ """
136
+ all_lines: list[str] = []
137
+ after_info: list[str] = []
138
+ for raw_line in CommandRunner.prune_ffmpeg_progress_from_output(
139
+ output
140
+ ).splitlines():
141
+ line = _CONTEXT_PREFIX.sub("", raw_line.strip())
142
+ if not line:
143
+ continue
144
+ if line.lower().startswith(_INFO_LINE_PREFIXES) or _KEY_VALUE_LINE.match(line):
145
+ after_info = []
146
+ continue
147
+ all_lines.append(line)
148
+ after_info.append(line)
149
+
150
+ selected = after_info or [
151
+ line for line in all_lines if _ERROR_KEYWORDS.search(line)
152
+ ]
153
+ # Drop duplicates while keeping order
154
+ unique = list(dict.fromkeys(selected))[:max_lines]
155
+ return "; ".join(unique) if unique else "ffmpeg failed without an error message"
156
+
157
+
158
+ class FFmpegCommandError(RuntimeError):
159
+ """
160
+ Raised when an ffmpeg command fails.
161
+
162
+ `str()` of the error contains the full command and output, as before.
163
+ Use `summary` for a short, user-facing description of the failure.
164
+ """
165
+
166
+ def __init__(self, cmd: list[str], output: str, returncode: int | None = None):
167
+ self.cmd = cmd
168
+ self.output = output
169
+ self.returncode = returncode
170
+ reason = output.strip() or (
171
+ f"exited with status {returncode} without diagnostics"
172
+ if returncode is not None
173
+ else "failed without diagnostics"
174
+ )
175
+ self.summary = summarize_ffmpeg_output(output) if output.strip() else reason
176
+ super().__init__(f"Error running command {shlex.join(cmd)}: {reason}")
177
+
178
+
179
+ def describe_error(error: BaseException) -> str:
180
+ """
181
+ Return a short, user-facing description of an error.
182
+
183
+ Args:
184
+ error (BaseException): The error
185
+
186
+ Returns:
187
+ str: The ffmpeg error summary for failed ffmpeg commands, otherwise `str(error)`
188
+ """
189
+ if isinstance(error, FFmpegCommandError):
190
+ return f"ffmpeg failed: {error.summary}"
191
+ return str(error)
192
+
193
+
80
194
  class CommandRunner:
81
195
  """
82
196
  Wrapper for running ffmpeg commands
@@ -134,9 +248,16 @@ class CommandRunner:
134
248
  # wrapper for 'ffmpeg-progress-yield'
135
249
  _logger.debug(f"Running command: {shlex.join(cmd)}")
136
250
  with FfmpegProgress(cmd, dry_run=self.dry) as ff:
137
- yield from ff.run_command_with_progress(
138
- popen_kwargs=_get_ffmpeg_popen_kwargs()
139
- )
251
+ try:
252
+ yield from ff.run_command_with_progress(
253
+ popen_kwargs=_get_ffmpeg_popen_kwargs()
254
+ )
255
+ except RuntimeError as e:
256
+ if isinstance(e, FFmpegCommandError):
257
+ raise
258
+ output = ff.stderr or str(e)
259
+ _logger.debug(f"ffmpeg command failed: {shlex.join(cmd)}\n{output}")
260
+ raise FFmpegCommandError(cmd, output) from e
140
261
 
141
262
  self.output = ff.stderr
142
263
 
@@ -179,11 +300,7 @@ class CommandRunner:
179
300
  stderr = stderr_bytes.decode("utf8", errors="replace")
180
301
 
181
302
  if p.returncode != 0:
182
- reason = (
183
- stderr.strip()
184
- or f"exited with status {p.returncode} without diagnostics"
185
- )
186
- raise RuntimeError(f"Error running command {shlex.join(cmd)}: {reason}")
303
+ raise FFmpegCommandError(cmd, stderr, returncode=p.returncode)
187
304
 
188
305
  self.output = stdout + stderr
189
306
  return self
@@ -0,0 +1,189 @@
1
+ """
2
+ Terminal output helpers based on rich.
3
+
4
+ All human-facing output (log messages, progress bars, summary tables) goes
5
+ through a single stderr console, so that log messages are printed above live
6
+ progress bars instead of breaking them. Machine-readable output such as
7
+ `--print-stats` JSON is still written to stdout unchanged.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from collections.abc import Callable, Iterator
14
+ from contextlib import contextmanager
15
+ from types import TracebackType
16
+
17
+ from rich.console import Console
18
+ from rich.markup import escape
19
+ from rich.progress import (
20
+ BarColumn,
21
+ MofNCompleteColumn,
22
+ Progress,
23
+ SpinnerColumn,
24
+ TaskID,
25
+ TaskProgressColumn,
26
+ TextColumn,
27
+ TimeElapsedColumn,
28
+ TimeRemainingColumn,
29
+ )
30
+ from rich.table import Column
31
+ from rich.theme import Theme
32
+
33
+ THEME = Theme(
34
+ {
35
+ "log.debug": "cyan",
36
+ "log.info": "green",
37
+ "log.warning": "yellow",
38
+ "log.error": "bold red",
39
+ "log.critical": "bold white on red",
40
+ "status.ok": "green",
41
+ "status.skipped": "yellow",
42
+ "status.error": "bold red",
43
+ }
44
+ )
45
+
46
+ _console: Console | None = None
47
+
48
+
49
+ def get_console() -> Console:
50
+ """
51
+ Return the shared stderr console, creating it on first use.
52
+
53
+ The console honors the usual `NO_COLOR`, `FORCE_COLOR` and `TERM`
54
+ environment variables and only emits colors when stderr is a terminal.
55
+
56
+ Returns:
57
+ Console: The shared console
58
+ """
59
+ global _console
60
+ if _console is None:
61
+ _console = Console(stderr=True, theme=THEME, highlight=False)
62
+ return _console
63
+
64
+
65
+ def display_name(path: str, max_len: int = 24) -> str:
66
+ """
67
+ Shorten a file path for display in a progress bar.
68
+
69
+ Args:
70
+ path (str): The file path
71
+ max_len (int, optional): Maximum length. Defaults to 24.
72
+
73
+ Returns:
74
+ str: The base name, truncated in the middle if it is too long
75
+ """
76
+ name = os.path.basename(path) or path
77
+ if len(name) <= max_len:
78
+ return name
79
+ keep = (max_len - 1) // 2
80
+ return f"{name[:keep]}…{name[-(max_len - keep - 1) :]}"
81
+
82
+
83
+ class ProgressDisplay:
84
+ """
85
+ A progress display with one overall bar and transient per-pass bars.
86
+
87
+ When disabled, all methods are no-ops, so callers do not need to check
88
+ whether progress output was requested.
89
+ """
90
+
91
+ def __init__(self, enabled: bool) -> None:
92
+ self.enabled = enabled
93
+ self._progress: Progress | None = None
94
+ self._overall: TaskID | None = None
95
+ self._overall_label = ""
96
+
97
+ def __enter__(self) -> ProgressDisplay:
98
+ if self.enabled:
99
+ self._progress = Progress(
100
+ SpinnerColumn(finished_text="[green]✔[/green]"),
101
+ TextColumn(
102
+ "{task.description}",
103
+ table_column=Column(width=40, no_wrap=True, overflow="ellipsis"),
104
+ ),
105
+ BarColumn(),
106
+ TaskProgressColumn(),
107
+ MofNCompleteColumn(),
108
+ TimeElapsedColumn(),
109
+ TextColumn("[dim]eta[/dim]"),
110
+ TimeRemainingColumn(),
111
+ console=get_console(),
112
+ )
113
+ self._progress.start()
114
+ return self
115
+
116
+ def __exit__(
117
+ self,
118
+ exc_type: type[BaseException] | None,
119
+ exc: BaseException | None,
120
+ tb: TracebackType | None,
121
+ ) -> None:
122
+ if self._progress is not None:
123
+ self._progress.stop()
124
+ self._progress = None
125
+ self._overall = None
126
+
127
+ def start_overall(self, description: str, total: int) -> None:
128
+ """
129
+ Start (or replace) the overall bar, e.g. counting files.
130
+
131
+ Args:
132
+ description (str): Label of the bar
133
+ total (int): Number of steps
134
+ """
135
+ if self._progress is None:
136
+ return
137
+ self._overall_label = description
138
+ self._overall = self._progress.add_task(
139
+ self._overall_description(None), total=total
140
+ )
141
+
142
+ def _overall_description(self, current: str | None) -> str:
143
+ label = f"[bold]{escape(self._overall_label)}[/bold]"
144
+ if current:
145
+ label += f" [cyan]{escape(current)}[/cyan]"
146
+ return label
147
+
148
+ def set_current(self, name: str | None) -> None:
149
+ """
150
+ Show the name of the item currently being processed next to the overall bar.
151
+
152
+ Args:
153
+ name (str | None): The name, or None to clear it
154
+ """
155
+ if self._progress is not None and self._overall is not None:
156
+ self._progress.update(
157
+ self._overall, description=self._overall_description(name)
158
+ )
159
+
160
+ def advance_overall(self) -> None:
161
+ """Advance the overall bar by one step."""
162
+ if self._progress is not None and self._overall is not None:
163
+ self._progress.advance(self._overall)
164
+
165
+ @contextmanager
166
+ def task(self, description: str) -> Iterator[Callable[[float], None]]:
167
+ """
168
+ Show a transient bar for a single ffmpeg run that reports 0-100%.
169
+
170
+ Args:
171
+ description (str): Label of the bar
172
+
173
+ Yields:
174
+ Callable[[float], None]: Function to call with the current percentage
175
+ """
176
+ if self._progress is None:
177
+ yield lambda _: None
178
+ return
179
+
180
+ progress = self._progress
181
+ task_id = progress.add_task(f" {escape(description)}", total=100)
182
+
183
+ def update(percentage: float) -> None:
184
+ progress.update(task_id, completed=percentage)
185
+
186
+ try:
187
+ yield update
188
+ finally:
189
+ progress.remove_task(task_id)
@@ -6,11 +6,15 @@ import math
6
6
  import os
7
7
  import sys
8
8
  from itertools import chain
9
- from typing import TYPE_CHECKING, Literal
9
+ from typing import TYPE_CHECKING, Iterator, Literal
10
10
 
11
- from tqdm import tqdm
11
+ from rich import box
12
+ from rich.console import Group, RenderableType
13
+ from rich.table import Table
14
+ from rich.text import Text
12
15
 
13
16
  from ._cmd_utils import (
17
+ describe_error,
14
18
  PCM_INCOMPATIBLE_EXTS,
15
19
  PCM_INCOMPATIBLE_FORMATS,
16
20
  ffmpeg_has_loudnorm,
@@ -18,6 +22,7 @@ from ._cmd_utils import (
18
22
  get_muxer_default_audio_encoder,
19
23
  validate_input_file,
20
24
  )
25
+ from ._console import ProgressDisplay, display_name, get_console
21
26
  from ._errors import FFmpegNormalizeError
22
27
  from ._media_file import MediaFile
23
28
 
@@ -292,6 +297,7 @@ class FFmpegNormalize:
292
297
  self.dry_run = dry_run
293
298
  self.debug = debug
294
299
  self.progress = progress
300
+ self.progress_display = ProgressDisplay(enabled=False)
295
301
  self.replaygain = replaygain
296
302
  self.batch = batch
297
303
 
@@ -520,6 +526,24 @@ class FFmpegNormalize:
520
526
 
521
527
  return batch_reference
522
528
 
529
+ def _iter_media_files(self, description: str) -> Iterator[tuple[int, MediaFile]]:
530
+ """
531
+ Iterate over all media files while updating the overall progress bar.
532
+
533
+ Args:
534
+ description (str): Label of the overall progress bar
535
+
536
+ Yields:
537
+ tuple[int, MediaFile]: The index and the media file
538
+ """
539
+ display = self.progress_display
540
+ display.start_overall(description, self.file_count)
541
+ for index, media_file in enumerate(self.media_files):
542
+ display.set_current(display_name(media_file.input_file))
543
+ yield index, media_file
544
+ display.advance_overall()
545
+ display.set_current(None)
546
+
523
547
  def run_normalization(self) -> None:
524
548
  """
525
549
  Run the normalization procedures.
@@ -547,6 +571,34 @@ class FFmpegNormalize:
547
571
  [media_file.input_file for media_file in self.media_files],
548
572
  [media_file.output_file for media_file in self.media_files],
549
573
  )
574
+ with ProgressDisplay(enabled=self.progress) as display:
575
+ self.progress_display = display
576
+ try:
577
+ self._process_media_files()
578
+ finally:
579
+ self.progress_display = ProgressDisplay(enabled=False)
580
+
581
+ if self.print_stats:
582
+ json.dump(
583
+ list(
584
+ chain.from_iterable(
585
+ media_file.get_stats() for media_file in self.media_files
586
+ )
587
+ ),
588
+ sys.stdout,
589
+ indent=4,
590
+ )
591
+ print()
592
+
593
+ if self.print_summary:
594
+ console = get_console()
595
+ if console.is_terminal:
596
+ console.print(self.summary_renderable())
597
+ else:
598
+ print(self.format_summary(), file=sys.stderr)
599
+
600
+ def _process_media_files(self) -> None:
601
+ """Run both passes for all media files, in batch or per-file mode."""
550
602
  if self.batch:
551
603
  # Batch mode: analyze all files first, then normalize with relative adjustments
552
604
  _logger.info(
@@ -575,14 +627,7 @@ class FFmpegNormalize:
575
627
 
576
628
  # Phase 1: Run first pass on all files to collect measurements
577
629
  _logger.info("Phase 1: Analyzing all files...")
578
- for index, media_file in enumerate(
579
- tqdm(
580
- self.media_files,
581
- desc="Analysis",
582
- disable=not self.progress,
583
- position=0,
584
- )
585
- ):
630
+ for index, media_file in self._iter_media_files("Analysis"):
586
631
  _logger.info(
587
632
  f"Analyzing file {media_file} ({index + 1} of {self.file_count})"
588
633
  )
@@ -596,9 +641,7 @@ class FFmpegNormalize:
596
641
  "Dynamic EBU mode: First pass skipped for this file."
597
642
  )
598
643
  except Exception as e:
599
- media_file.status = "error"
600
- media_file.error = str(e)
601
- _logger.error(f"Error analyzing input file {media_file}: {e}")
644
+ self._record_failure(media_file, e, "analyzing")
602
645
  continue
603
646
 
604
647
  # Phase 2: Calculate batch reference loudness
@@ -606,14 +649,7 @@ class FFmpegNormalize:
606
649
 
607
650
  # Phase 3: Run second pass on all files with batch reference
608
651
  _logger.info("Phase 2: Normalizing all files...")
609
- for index, media_file in enumerate(
610
- tqdm(
611
- self.media_files,
612
- desc="Normalization",
613
- disable=not self.progress,
614
- position=0,
615
- )
616
- ):
652
+ for index, media_file in self._iter_media_files("Normalization"):
617
653
  # Skip files that already failed during analysis
618
654
  if media_file.status == "error":
619
655
  _logger.debug(f"Skipping {media_file} because its analysis failed")
@@ -628,17 +664,11 @@ class FFmpegNormalize:
628
664
  if self.verify and not self.dry_run:
629
665
  media_file.verify_output()
630
666
  except Exception as e:
631
- media_file.status = "error"
632
- media_file.error = str(e)
633
- _logger.error(f"Error processing input file {media_file}: {e}")
667
+ self._record_failure(media_file, e, "processing")
634
668
  continue
635
669
  else:
636
670
  # Non-batch mode: process each file completely before moving to the next
637
- for index, media_file in enumerate(
638
- tqdm(
639
- self.media_files, desc="File", disable=not self.progress, position=0
640
- )
641
- ):
671
+ for index, media_file in self._iter_media_files("Files"):
642
672
  _logger.info(
643
673
  f"Normalizing file {media_file} ({index + 1} of {self.file_count})"
644
674
  )
@@ -648,25 +678,26 @@ class FFmpegNormalize:
648
678
  if self.verify and not self.dry_run:
649
679
  media_file.verify_output()
650
680
  except Exception as e:
651
- media_file.status = "error"
652
- media_file.error = str(e)
653
- _logger.error(f"Error processing input file {media_file}: {e}")
681
+ self._record_failure(media_file, e, "processing")
654
682
  continue
655
683
 
656
- if self.print_stats:
657
- json.dump(
658
- list(
659
- chain.from_iterable(
660
- media_file.get_stats() for media_file in self.media_files
661
- )
662
- ),
663
- sys.stdout,
664
- indent=4,
665
- )
666
- print()
684
+ @staticmethod
685
+ def _record_failure(media_file: MediaFile, error: Exception, action: str) -> None:
686
+ """
687
+ Mark a media file as failed and log a short description of the error.
667
688
 
668
- if self.print_summary:
669
- print(self.format_summary(), file=sys.stderr)
689
+ The full error (e.g. the complete ffmpeg output) is only logged in
690
+ debug mode.
691
+
692
+ Args:
693
+ media_file (MediaFile): The file that failed
694
+ error (Exception): The error
695
+ action (str): What was being done, e.g. "processing"
696
+ """
697
+ media_file.status = "error"
698
+ media_file.error = describe_error(error)
699
+ _logger.debug(f"Full error for {media_file.input_file}: {error}", exc_info=True)
700
+ _logger.error(f"Error {action} input file {media_file}: {media_file.error}")
670
701
 
671
702
  def get_summary(self) -> list[SummaryRow]:
672
703
  """
@@ -687,12 +718,16 @@ class FFmpegNormalize:
687
718
  )
688
719
  )
689
720
 
690
- def format_summary(self) -> str:
721
+ def _summary_parts(
722
+ self,
723
+ ) -> tuple[str, list[str], list[list[str]], list[tuple[str, bool]], list[str]]:
691
724
  """
692
- Return the before/after summary as a human-readable table.
725
+ Collect the pieces of the before/after summary.
693
726
 
694
727
  Returns:
695
- str: The formatted table, including a header line with the target
728
+ tuple: The header, the column headings, the table rows, the
729
+ verification lines (text and whether the check passed), and
730
+ additional notes
696
731
  """
697
732
  if self.normalization_type == "ebu":
698
733
  header = (
@@ -719,15 +754,12 @@ class FFmpegNormalize:
719
754
  if self.dry_run:
720
755
  header += ", dry run"
721
756
 
722
- rows = self.get_summary()
723
- if not rows:
724
- return f"Summary ({header}): no files processed"
725
-
726
757
  def fmt(value: float | None, signed: bool = False) -> str:
727
758
  if value is None:
728
759
  return "-"
729
760
  return f"{value:+.1f}" if signed else f"{value:.1f}"
730
761
 
762
+ rows = self.get_summary()
731
763
  table: list[list[str]] = []
732
764
  for row in rows:
733
765
  values = [fmt(row["input_level"]), fmt(row["output_level"])]
@@ -738,7 +770,50 @@ class FFmpegNormalize:
738
770
  [row["input_file"], str(row["stream_id"]), *values, row["status"]]
739
771
  )
740
772
 
741
- headings = ["File", "Stream", *columns, "Status"]
773
+ verifications: list[tuple[str, bool]] = []
774
+ notes: list[str] = []
775
+ verified = [row for row in rows if "verification" in row]
776
+ if verified:
777
+ level_unit = "LUFS" if self.normalization_type == "ebu" else "dBFS"
778
+ peak_unit = "dBTP" if self.normalization_type == "ebu" else "dBFS"
779
+ for row in verified:
780
+ result = row["verification"]
781
+ outcome = "passed" if result["passed"] else "FAILED"
782
+ verifications.append(
783
+ (
784
+ f"{row['output_file']} stream {result['output_stream_id']}: "
785
+ f"level {fmt(result['output_level'])} {level_unit}, "
786
+ f"peak {fmt(result['output_peak'])} {peak_unit}, {outcome}",
787
+ result["passed"],
788
+ )
789
+ )
790
+ elif self.verify and self.dry_run:
791
+ notes.append("Encoded-output verification skipped: dry run.")
792
+
793
+ return (
794
+ header,
795
+ ["File", "Stream", *columns, "Status"],
796
+ table,
797
+ verifications,
798
+ notes,
799
+ )
800
+
801
+ _SUMMARY_FOOTNOTE = (
802
+ "Output values above: loudnorm filter statistics for EBU; "
803
+ "calculated from applied gain for RMS/peak; input levels for skipped files."
804
+ )
805
+
806
+ def format_summary(self) -> str:
807
+ """
808
+ Return the before/after summary as a human-readable table.
809
+
810
+ Returns:
811
+ str: The formatted table, including a header line with the target
812
+ """
813
+ header, headings, table, verifications, notes = self._summary_parts()
814
+ if not table:
815
+ return f"Summary ({header}): no files processed"
816
+
742
817
  widths = [
743
818
  max(len(headings[i]), *(len(line[i]) for line in table))
744
819
  for i in range(len(headings))
@@ -757,23 +832,65 @@ class FFmpegNormalize:
757
832
  lines = [f"Summary ({header}):", "", fmt_line(headings)]
758
833
  lines.append(fmt_line(["-" * w for w in widths]))
759
834
  lines.extend(fmt_line(line) for line in table)
760
- lines.append(
761
- "\nOutput values above: loudnorm filter statistics for EBU; "
762
- "calculated from applied gain for RMS/peak; input levels for skipped files."
763
- )
764
- verified = [row for row in rows if "verification" in row]
765
- if verified:
766
- level_unit = "LUFS" if self.normalization_type == "ebu" else "dBFS"
767
- peak_unit = "dBTP" if self.normalization_type == "ebu" else "dBFS"
835
+ lines.append("\n" + self._SUMMARY_FOOTNOTE)
836
+ if verifications:
768
837
  lines.append("\nEncoded-output verification (measured after encoding):")
769
- for row in verified:
770
- result = row["verification"]
771
- outcome = "passed" if result["passed"] else "FAILED"
772
- lines.append(
773
- f"{row['output_file']} stream {result['output_stream_id']}: "
774
- f"level {fmt(result['output_level'])} {level_unit}, "
775
- f"peak {fmt(result['output_peak'])} {peak_unit}, {outcome}"
776
- )
777
- elif self.verify and self.dry_run:
778
- lines.append("\nEncoded-output verification skipped: dry run.")
838
+ lines.extend(text for text, _ in verifications)
839
+ for note in notes:
840
+ lines.append("\n" + note)
779
841
  return "\n".join(lines)
842
+
843
+ def summary_renderable(self) -> RenderableType:
844
+ """
845
+ Return the before/after summary as a rich renderable for terminals.
846
+
847
+ Returns:
848
+ RenderableType: A table with the same content as `format_summary()`
849
+ """
850
+ header, headings, table, verifications, notes = self._summary_parts()
851
+ if not table:
852
+ return Text(f"Summary ({header}): no files processed")
853
+
854
+ status_styles = {"normalized": "status.ok", "skipped": "status.skipped"}
855
+ summary = Table(
856
+ title=f"Summary ({header})",
857
+ title_justify="left",
858
+ title_style="bold",
859
+ caption=self._SUMMARY_FOOTNOTE,
860
+ caption_justify="left",
861
+ caption_style="dim",
862
+ header_style="bold",
863
+ box=box.SIMPLE_HEAD,
864
+ )
865
+ last = len(headings) - 1
866
+ for i, heading in enumerate(headings):
867
+ summary.add_column(
868
+ heading,
869
+ justify="left" if i in (0, last) else "right",
870
+ overflow="fold",
871
+ no_wrap=i != 0,
872
+ )
873
+ for line in table:
874
+ status = line[-1]
875
+ summary.add_row(
876
+ *line[:-1],
877
+ Text(status, style=status_styles.get(status, "status.error")),
878
+ )
879
+
880
+ parts: list[RenderableType] = [summary]
881
+ if verifications:
882
+ parts.append(
883
+ Text(
884
+ "Encoded-output verification (measured after encoding):",
885
+ style="bold",
886
+ )
887
+ )
888
+ for text, passed in verifications:
889
+ parts.append(
890
+ Text(
891
+ f" {'✔' if passed else '✘'} {text}",
892
+ style="status.ok" if passed else "status.error",
893
+ )
894
+ )
895
+ parts.extend(Text(note, style="dim") for note in notes)
896
+ return Group(*parts)
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+
6
+ from rich.text import Text
7
+
8
+ from ffmpeg_normalize import __module_name__ as LOGGER_NAME
9
+
10
+ from ._console import get_console
11
+
12
+
13
+ class RichLogHandler(logging.Handler):
14
+ """
15
+ Log handler that prints `LEVEL: message` lines to the shared rich console.
16
+
17
+ Printing through the console keeps messages above any live progress bars.
18
+ The plain `LEVEL: message` layout is kept so that output stays easy to
19
+ grep when stderr is redirected; colors are only used on terminals.
20
+ Messages are never wrapped, and rich markup in messages is not interpreted.
21
+ """
22
+
23
+ def emit(self, record: logging.LogRecord) -> None:
24
+ try:
25
+ message = self.format(record)
26
+ level = record.levelname
27
+ line = Text()
28
+ line.append(f"{level}:", style=f"log.{level.lower()}")
29
+ line.append(" ")
30
+ if record.levelno >= logging.ERROR:
31
+ line.append(message, style="log.error")
32
+ elif record.levelno == logging.DEBUG:
33
+ line.append(message, style="dim")
34
+ else:
35
+ line.append(message)
36
+ get_console().print(line, soft_wrap=True)
37
+ except (KeyboardInterrupt, SystemExit):
38
+ raise
39
+ except Exception:
40
+ self.handleError(record)
41
+
42
+
43
+ def setup_cli_logger(arguments: argparse.Namespace) -> None:
44
+ """Configures the CLI logger.
45
+
46
+ Args:
47
+ arguments (argparse.Namespace): The CLI arguments.
48
+ """
49
+
50
+ logger = logging.getLogger(LOGGER_NAME)
51
+
52
+ handler = RichLogHandler()
53
+ handler.setFormatter(logging.Formatter("%(message)s"))
54
+ logger.addHandler(handler)
55
+
56
+ logger.setLevel(logging.WARNING)
57
+
58
+ if arguments.quiet:
59
+ logger.setLevel(logging.ERROR)
60
+ elif arguments.debug:
61
+ logger.setLevel(logging.DEBUG)
62
+ elif arguments.verbose:
63
+ logger.setLevel(logging.INFO)
@@ -15,7 +15,6 @@ from mutagen.mp3 import MP3
15
15
  from mutagen.mp4 import MP4
16
16
  from mutagen.oggopus import OggOpus
17
17
  from mutagen.oggvorbis import OggVorbis
18
- from tqdm import tqdm
19
18
 
20
19
  from ._cmd_utils import (
21
20
  DUR_REGEX,
@@ -44,8 +43,6 @@ _logger = logging.getLogger(__name__)
44
43
  AUDIO_ONLY_FORMATS = {"aac", "ast", "flac", "mka", "oga", "ogg", "opus", "wav"}
45
44
  ONE_STREAM = {"aac", "ast", "flac", "mp3", "wav"}
46
45
 
47
- TQDM_BAR_FORMAT = "{desc}: {percentage:3.2f}% |{bar}{r_bar}"
48
-
49
46
 
50
47
  def _to_ms(**kwargs: str) -> int:
51
48
  hour = int(kwargs.get("hour", 0))
@@ -352,18 +349,9 @@ class MediaFile:
352
349
  self.output_file = self.temp_file
353
350
 
354
351
  # run the second pass as a whole.
355
- if self.ffmpeg_normalize.progress:
356
- with tqdm(
357
- total=100,
358
- position=1,
359
- desc="Second Pass",
360
- bar_format=TQDM_BAR_FORMAT,
361
- ) as pbar:
362
- for progress in self._second_pass():
363
- pbar.update(progress - pbar.n)
364
- else:
365
- for _ in self._second_pass():
366
- pass
352
+ with self.ffmpeg_normalize.progress_display.task("Second pass") as update:
353
+ for progress in self._second_pass():
354
+ update(progress)
367
355
 
368
356
  # remove temp dir; this will remove the temp file as well if it has not been renamed (e.g. for replaygain)
369
357
  if temp_dir and os.path.exists(temp_dir):
@@ -865,18 +853,10 @@ class MediaFile:
865
853
  else:
866
854
  fun = getattr(audio_stream, "parse_astats")
867
855
 
868
- if self.ffmpeg_normalize.progress:
869
- with tqdm(
870
- total=100,
871
- position=1,
872
- desc=f"Stream {index + 1}/{len(streams_to_normalize)}",
873
- bar_format=TQDM_BAR_FORMAT,
874
- ) as pbar:
875
- for progress in fun():
876
- pbar.update(progress - pbar.n)
877
- else:
878
- for _ in fun():
879
- pass
856
+ description = f"First pass, stream {index + 1}/{len(streams_to_normalize)}"
857
+ with self.ffmpeg_normalize.progress_display.task(description) as update:
858
+ for progress in fun():
859
+ update(progress)
880
860
 
881
861
  def _get_stream_filter_chain(self, audio_stream: AudioStream) -> list[str]:
882
862
  """
@@ -1253,7 +1233,6 @@ class MediaFile:
1253
1233
  try:
1254
1234
  yield from cmd_runner.run_ffmpeg_command(cmd)
1255
1235
  except Exception as e:
1256
- _logger.error(f"Error while running command {shlex.join(cmd)}! Error: {e}")
1257
1236
  if temp_file and os.path.exists(temp_file):
1258
1237
  os.remove(temp_file)
1259
1238
  raise e
@@ -1,72 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- import logging
5
- import sys
6
-
7
- import colorlog
8
- from tqdm import tqdm
9
-
10
- from ffmpeg_normalize import __module_name__ as LOGGER_NAME
11
-
12
-
13
- # https://stackoverflow.com/questions/38543506/
14
- class TqdmLoggingHandler(logging.StreamHandler):
15
- def __init__(self) -> None:
16
- super().__init__(sys.stderr)
17
-
18
- def emit(self, record: logging.LogRecord) -> None:
19
- try:
20
- msg = self.format(record)
21
- set_mp_lock()
22
- tqdm.write(msg, file=sys.stderr)
23
- self.flush()
24
- except (KeyboardInterrupt, SystemExit):
25
- raise
26
- except Exception:
27
- self.handleError(record)
28
-
29
-
30
- def set_mp_lock() -> None:
31
- try:
32
- from multiprocessing import Lock
33
-
34
- tqdm.set_lock(Lock())
35
- except (ImportError, OSError):
36
- # Some python environments do not support multiprocessing
37
- # See: https://github.com/slhck/ffmpeg-normalize/issues/156
38
- pass
39
-
40
-
41
- def setup_cli_logger(arguments: argparse.Namespace) -> None:
42
- """Configurs the CLI logger.
43
-
44
- Args:
45
- arguments (argparse.Namespace): The CLI arguments.
46
- """
47
-
48
- logger = colorlog.getLogger(LOGGER_NAME)
49
-
50
- handler = TqdmLoggingHandler()
51
- handler.setFormatter(
52
- colorlog.ColoredFormatter(
53
- "%(log_color)s%(levelname)s: %(message)s",
54
- log_colors={
55
- "DEBUG": "cyan",
56
- "INFO": "green",
57
- "WARNING": "yellow",
58
- "ERROR": "red",
59
- "CRITICAL": "red,bg_white",
60
- },
61
- )
62
- )
63
- logger.addHandler(handler)
64
-
65
- logger.setLevel(logging.WARNING)
66
-
67
- if arguments.quiet:
68
- logger.setLevel(logging.ERROR)
69
- elif arguments.debug:
70
- logger.setLevel(logging.DEBUG)
71
- elif arguments.verbose:
72
- logger.setLevel(logging.INFO)