ffmpeg-normalize 1.45.4__tar.gz → 1.46.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 (19) hide show
  1. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/PKG-INFO +3 -1
  2. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/README.md +2 -0
  3. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/pyproject.toml +1 -1
  4. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/pyproject.toml.orig +1 -1
  5. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/__main__.py +34 -9
  6. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_ffmpeg_normalize.py +51 -6
  7. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_logger.py +5 -3
  8. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_media_file.py +83 -30
  9. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_presets.py +35 -1
  10. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_streams.py +42 -13
  11. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/LICENSE.md +0 -0
  12. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/__init__.py +0 -0
  13. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_cmd_utils.py +0 -0
  14. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_console.py +0 -0
  15. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/_errors.py +0 -0
  16. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/data/presets/music.json +0 -0
  17. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/data/presets/podcast.json +0 -0
  18. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.0}/src/ffmpeg_normalize/data/presets/streaming-video.json +0 -0
  19. {ffmpeg_normalize-1.45.4 → ffmpeg_normalize-1.46.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.45.4
3
+ Version: 1.46.0
4
4
  Summary: Normalize audio via ffmpeg
5
5
  Keywords: ffmpeg,normalize,audio
6
6
  Author: Werner Robitza
@@ -72,6 +72,8 @@ 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.46.0 is the result of a **bug sweep** with about 20 fixes. Among them: audio tracks keep their own language and title tags when selecting or keeping streams, statistics no longer get mixed up between tracks, float, 8-bit and AIFF PCM outputs work as expected, silent or very short inputs are left unchanged instead of getting a huge gain, ReplayGain tagging is more robust (including the Opus R128 reference level), and presets now support logging options and string or list values. Note that `--batch` now stops with an error when some output files already exist (use `-f` to overwrite), since skipping them would change the gain of the other files.
76
+
75
77
  - 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
78
 
77
79
  > ⚠️ **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.
@@ -41,6 +41,8 @@ This program normalizes media files to a certain loudness level using the EBU R1
41
41
 
42
42
  ## 🆕 What's New
43
43
 
44
+ - Version 1.46.0 is the result of a **bug sweep** with about 20 fixes. Among them: audio tracks keep their own language and title tags when selecting or keeping streams, statistics no longer get mixed up between tracks, float, 8-bit and AIFF PCM outputs work as expected, silent or very short inputs are left unchanged instead of getting a huge gain, ReplayGain tagging is more robust (including the Opus R128 reference level), and presets now support logging options and string or list values. Note that `--batch` now stops with an error when some output files already exist (use `-f` to overwrite), since skipping them would change the gain of the other files.
45
+
44
46
  - 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
47
 
46
48
  > ⚠️ **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.
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ffmpeg-normalize"
7
- version = "1.45.4"
7
+ version = "1.46.0"
8
8
  description = "Normalize audio via ffmpeg"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ffmpeg-normalize"
7
- version = "1.45.4"
7
+ version = "1.46.0"
8
8
  description = "Normalize audio via ffmpeg"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -788,8 +788,10 @@ def main() -> None:
788
788
  preset_data = preset_manager.load_preset(cli_args.preset)
789
789
  _logger.debug(f"Loaded preset '{cli_args.preset}': {preset_data}")
790
790
  preset_manager.merge_preset_with_args(
791
- preset_data, cli_args, set(vars(explicit_args))
791
+ preset_data, cli_args, set(vars(explicit_args)), parser
792
792
  )
793
+ # the preset may set verbose, quiet or debug
794
+ setup_cli_logger(arguments=cli_args)
793
795
  _logger.info(f"Applied preset '{cli_args.preset}'")
794
796
  except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
795
797
  error(str(e))
@@ -818,6 +820,9 @@ def main() -> None:
818
820
  error(f"Could not parse extra_options: {e}")
819
821
  return ret
820
822
 
823
+ # accept "-ext .flac" as well as "-ext flac"
824
+ cli_args.extension = cli_args.extension.lstrip(".")
825
+
821
826
  # parse extra options
822
827
  extra_input_options = _split_options(cli_args.extra_input_options)
823
828
  extra_output_options = _split_options(cli_args.extra_output_options)
@@ -836,8 +841,10 @@ def main() -> None:
836
841
 
837
842
  # Show progress bars by default only in interactive terminals, so that
838
843
  # scripts and redirected output are not cluttered with them.
844
+ # A preset may enable them too, but only --progress on the command line
845
+ # forces them for non-interactive or quiet runs.
839
846
  progress = cli_args.progress
840
- if progress is None:
847
+ if progress is None or (progress and "progress" not in vars(explicit_args)):
841
848
  progress = sys.stderr.isatty() and not cli_args.quiet
842
849
 
843
850
  try:
@@ -889,13 +896,6 @@ def main() -> None:
889
896
  except FFmpegNormalizeError as e:
890
897
  error(e)
891
898
 
892
- if cli_args.output and len(cli_args.input) > len(cli_args.output):
893
- _logger.warning(
894
- "There are more input files than output file names given. "
895
- "Please specify one output file name per input file using -o <output1> <output2> ... "
896
- "Will apply default file naming for the remaining ones."
897
- )
898
-
899
899
  # Collect input files from positional args and --input-list
900
900
  input_files = list(cli_args.input) if cli_args.input else []
901
901
  if cli_args.input_list:
@@ -914,6 +914,13 @@ def main() -> None:
914
914
  )
915
915
  sys.exit(1)
916
916
 
917
+ if cli_args.output and len(input_files) > len(cli_args.output):
918
+ _logger.warning(
919
+ "There are more input files than output file names given. "
920
+ "Please specify one output file name per input file using -o <output1> <output2> ... "
921
+ "Will apply default file naming for the remaining ones."
922
+ )
923
+
917
924
  # Validate all input files upfront before processing
918
925
  _logger.debug("Validating all input files before processing...")
919
926
  validation_errors = FFmpegNormalize.validate_input_files(input_files)
@@ -953,9 +960,27 @@ def main() -> None:
953
960
  except FFmpegNormalizeError as e:
954
961
  error(e)
955
962
 
963
+ # in batch mode, the gain of each file depends on all files, so skipping
964
+ # existing outputs would silently change the gain of the remaining ones
965
+ if cli_args.batch and not cli_args.force and not cli_args.replaygain:
966
+ existing = [
967
+ output_file
968
+ for output_file in output_files
969
+ if os.path.exists(output_file)
970
+ and os.path.realpath(output_file) != os.path.realpath(os.devnull)
971
+ ]
972
+ if existing:
973
+ error(
974
+ "Batch mode needs to process all files together, but these "
975
+ f"output files already exist: {', '.join(existing)}. "
976
+ "Use -f to overwrite them."
977
+ )
978
+
956
979
  for input_file, output_file in zip(input_files, output_files):
957
980
  if (
958
981
  os.path.exists(output_file)
982
+ # the null device always exists, but writing to it is harmless
983
+ and os.path.realpath(output_file) != os.path.realpath(os.devnull)
959
984
  and not cli_args.force
960
985
  and not cli_args.replaygain
961
986
  ):
@@ -34,6 +34,35 @@ _logger = logging.getLogger(__name__)
34
34
  NORMALIZATION_TYPES = ("ebu", "rms", "peak")
35
35
 
36
36
 
37
+ def parse_sample_rate(sample_rate: object) -> int:
38
+ """
39
+ Parse a sample rate given as a number or a string such as "48000",
40
+ "44100.0", "48k" or "44.1k".
41
+
42
+ Args:
43
+ sample_rate (object): The sample rate to parse
44
+
45
+ Returns:
46
+ int: The sample rate in Hz
47
+
48
+ Raises:
49
+ FFmpegNormalizeError: If the sample rate is not a positive whole number of Hz
50
+ """
51
+ value = str(sample_rate).strip()
52
+ multiplier = 1
53
+ if value.lower().endswith("k"):
54
+ value, multiplier = value[:-1], 1000
55
+ try:
56
+ rate = float(value) * multiplier
57
+ except ValueError:
58
+ rate = math.nan
59
+ if not math.isfinite(rate) or rate <= 0 or rate != int(rate):
60
+ raise FFmpegNormalizeError(
61
+ f"Invalid sample rate {sample_rate!r}, expected a value in Hz such as 48000 or 48k"
62
+ )
63
+ return int(rate)
64
+
65
+
37
66
  def check_range(number: object, min_r: float, max_r: float, name: str = "") -> float:
38
67
  """
39
68
  Checks if "number" is an int or float and is between min_r (inclusive)
@@ -268,7 +297,9 @@ class FFmpegNormalize:
268
297
 
269
298
  self.dual_mono = dual_mono
270
299
  self.dynamic = dynamic
271
- self.sample_rate = None if sample_rate is None else int(sample_rate)
300
+ self.sample_rate = (
301
+ None if sample_rate is None else parse_sample_rate(sample_rate)
302
+ )
272
303
  self.audio_channels = None if audio_channels is None else int(audio_channels)
273
304
 
274
305
  self.audio_codec = audio_codec
@@ -293,7 +324,7 @@ class FFmpegNormalize:
293
324
  self.post_filter = post_filter
294
325
 
295
326
  self.output_format = output_format
296
- self.extension = extension
327
+ self.extension = extension.lstrip(".")
297
328
  self.dry_run = dry_run
298
329
  self.debug = debug
299
330
  self.progress = progress
@@ -423,10 +454,22 @@ class FFmpegNormalize:
423
454
  normalized in place and multiple outputs to the null device.
424
455
  """
425
456
 
457
+ def is_case_insensitive(directory: str) -> bool:
458
+ # e.g. the default filesystems on macOS and Windows
459
+ swapped = directory.swapcase()
460
+ return (
461
+ swapped != directory
462
+ and os.path.exists(swapped)
463
+ and os.path.samefile(directory, swapped)
464
+ )
465
+
426
466
  def path_keys(path: str) -> list[str | tuple[int, int]]:
427
- keys: list[str | tuple[int, int]] = [
428
- os.path.normcase(os.path.realpath(path))
429
- ]
467
+ real_path = os.path.normcase(os.path.realpath(path))
468
+ directory, name = os.path.split(real_path)
469
+ if os.path.isdir(directory) and is_case_insensitive(directory):
470
+ # files that differ only in case are the same file here
471
+ real_path = os.path.join(directory, name.casefold())
472
+ keys: list[str | tuple[int, int]] = [real_path]
430
473
  if os.path.exists(path):
431
474
  stat = os.stat(path)
432
475
  keys.append((stat.st_dev, stat.st_ino))
@@ -480,8 +523,10 @@ class FFmpegNormalize:
480
523
  if self.normalization_type == "ebu":
481
524
  # Get EBU integrated loudness from first pass
482
525
  ebu_stats = stream.loudness_statistics.get("ebu_pass1")
526
+ # -99 stands for unmeasurable loudness (silent or too short)
483
527
  if ebu_stats and "input_i" in ebu_stats:
484
- measurements.append(float(ebu_stats["input_i"]))
528
+ if float(ebu_stats["input_i"]) > -99:
529
+ measurements.append(float(ebu_stats["input_i"]))
485
530
  elif self.normalization_type == "rms":
486
531
  # Get RMS mean value
487
532
  mean = stream.loudness_statistics.get("mean")
@@ -49,9 +49,11 @@ def setup_cli_logger(arguments: argparse.Namespace) -> None:
49
49
 
50
50
  logger = logging.getLogger(LOGGER_NAME)
51
51
 
52
- handler = RichLogHandler()
53
- handler.setFormatter(logging.Formatter("%(message)s"))
54
- logger.addHandler(handler)
52
+ # may be called again once a preset is applied, so add the handler once
53
+ if not any(isinstance(h, RichLogHandler) for h in logger.handlers):
54
+ handler = RichLogHandler()
55
+ handler.setFormatter(logging.Formatter("%(message)s"))
56
+ logger.addHandler(handler)
55
57
 
56
58
  logger.setLevel(logging.WARNING)
57
59
 
@@ -158,6 +158,12 @@ class MediaFile:
158
158
  _logger.debug(output)
159
159
 
160
160
  output_lines = [line.strip() for line in output.split("\n")]
161
+ # only look at the input streams: in the output section, ffmpeg marks
162
+ # the first stream of each type as default if no input stream is
163
+ for index, line in enumerate(output_lines):
164
+ if line.startswith(("Stream mapping:", "Output #")):
165
+ output_lines = output_lines[:index]
166
+ break
161
167
 
162
168
  # First pass: parse disposition flags for each stream
163
169
  stream_dispositions: dict[int, bool] = {}
@@ -694,10 +700,13 @@ class MediaFile:
694
700
  """
695
701
  _logger.debug(f"Writing ReplayGain tags to {self.input_file}")
696
702
 
697
- input_file_ext = os.path.splitext(self.input_file)[1]
703
+ input_file_ext = os.path.splitext(self.input_file)[1].lower()
698
704
  if input_file_ext == ".mp3":
699
705
  mp3 = MP3(self.input_file, ID3=ID3)
700
- if not mp3.tags:
706
+ # files without an ID3 tag need one before tags can be written
707
+ if mp3.tags is None:
708
+ mp3.add_tags()
709
+ if mp3.tags is None:
701
710
  return
702
711
  mp3.tags.add(
703
712
  TXXX(desc="REPLAYGAIN_TRACK_GAIN", text=[f"{track_gain:.2f} dB"])
@@ -706,9 +715,10 @@ class MediaFile:
706
715
  mp3.save()
707
716
  elif input_file_ext in [".mp4", ".m4a", ".m4v", ".mov"]:
708
717
  mp4 = MP4(self.input_file)
709
- if not mp4.tags:
718
+ # an existing but empty tag is falsy, and add_tags() would reject it
719
+ if mp4.tags is None:
710
720
  mp4.add_tags()
711
- if not mp4.tags:
721
+ if mp4.tags is None:
712
722
  return
713
723
  mp4.tags["----:com.apple.iTunes:REPLAYGAIN_TRACK_GAIN"] = [
714
724
  f"{track_gain:.2f} dB".encode()
@@ -724,8 +734,10 @@ class MediaFile:
724
734
  ogg.save()
725
735
  elif input_file_ext == ".opus":
726
736
  opus = OggOpus(self.input_file)
727
- # See https://datatracker.ietf.org/doc/html/rfc7845#section-5.2.1
728
- opus["R128_TRACK_GAIN"] = [str(round(256 * track_gain))]
737
+ # See https://datatracker.ietf.org/doc/html/rfc7845#section-5.2.1:
738
+ # the gain is relative to -23 LUFS, whatever the target level
739
+ r128_gain = track_gain - (self.ffmpeg_normalize.target_level + 23)
740
+ opus["R128_TRACK_GAIN"] = [str(round(256 * r128_gain))]
729
741
  opus.save()
730
742
  else:
731
743
  _logger.error(
@@ -752,7 +764,7 @@ class MediaFile:
752
764
  """
753
765
  _logger.debug(f"Stripping ReplayGain tags from {output_file}")
754
766
 
755
- output_file_ext = os.path.splitext(output_file)[1]
767
+ output_file_ext = os.path.splitext(output_file)[1].lower()
756
768
  if output_file_ext == ".mp3":
757
769
  try:
758
770
  mp3 = MP3(output_file, ID3=ID3)
@@ -911,7 +923,24 @@ class MediaFile:
911
923
  ):
912
924
  skip_normalization = True
913
925
 
914
- if skip_normalization:
926
+ # loudnorm reports -inf (stored as -99) when nothing passes its gate,
927
+ # i.e. for silence or input shorter than one 400 ms block. Any gain
928
+ # computed from that would be meaningless.
929
+ unmeasurable = (
930
+ self.ffmpeg_normalize.normalization_type == "ebu"
931
+ and not self.ffmpeg_normalize.dynamic
932
+ and audio_stream.loudness_statistics["ebu_pass1"] is not None
933
+ and audio_stream.loudness_statistics["ebu_pass1"]["input_i"] <= -99
934
+ )
935
+
936
+ if unmeasurable:
937
+ _logger.warning(
938
+ f"{self.input_file}: Stream {audio_stream.stream_id} has no measurable "
939
+ "loudness (silent, or shorter than 0.4 s), leaving it unchanged."
940
+ )
941
+ normalization_filter = "acopy"
942
+ audio_stream.applied_gain = 0.0
943
+ elif skip_normalization:
915
944
  _logger.warning(
916
945
  f"Stream {audio_stream.stream_id} had measured input loudness lower than target, skipping normalization."
917
946
  )
@@ -1074,6 +1103,21 @@ class MediaFile:
1074
1103
  # add input file and basic filter
1075
1104
  cmd.extend(["-i", self.input_file, "-filter_complex", audio_filter_cmd])
1076
1105
 
1106
+ # Determine streams to normalize and passthrough
1107
+ streams_to_normalize = self._get_streams_to_normalize()
1108
+ all_audio_streams = list(self.streams["audio"].values())
1109
+
1110
+ # Determine which streams to passthrough
1111
+ if self.ffmpeg_normalize.keep_other_audio and (
1112
+ self.ffmpeg_normalize.audio_streams is not None
1113
+ or self.ffmpeg_normalize.audio_default_only
1114
+ ):
1115
+ streams_to_passthrough = [
1116
+ s for s in all_audio_streams if s not in streams_to_normalize
1117
+ ]
1118
+ else:
1119
+ streams_to_passthrough = []
1120
+
1077
1121
  # map metadata, only if needed
1078
1122
  if self.ffmpeg_normalize.metadata_disable:
1079
1123
  cmd.extend(["-map_metadata", "-1"])
@@ -1085,6 +1129,20 @@ class MediaFile:
1085
1129
  stream_key = stream_type[0]
1086
1130
  if stream_type not in self.streams:
1087
1131
  continue
1132
+ if stream_type == "audio":
1133
+ # output audio is the normalized streams, then the
1134
+ # passthrough ones, which need not be the first input
1135
+ # streams, so take the tags from the stream itself
1136
+ for idx, audio_stream in enumerate(
1137
+ streams_to_normalize + streams_to_passthrough
1138
+ ):
1139
+ cmd.extend(
1140
+ [
1141
+ f"-map_metadata:s:a:{idx}",
1142
+ f"0:s:{audio_stream.stream_id}",
1143
+ ]
1144
+ )
1145
+ continue
1088
1146
  for idx, _ in enumerate(self.streams[stream_type].items()):
1089
1147
  cmd.extend(
1090
1148
  [
@@ -1112,21 +1170,6 @@ class MediaFile:
1112
1170
  f"The chosen output extension {self.output_ext} does not support video/cover art. It will be disabled."
1113
1171
  )
1114
1172
 
1115
- # Determine streams to normalize and passthrough
1116
- streams_to_normalize = self._get_streams_to_normalize()
1117
- all_audio_streams = list(self.streams["audio"].values())
1118
-
1119
- # Determine which streams to passthrough
1120
- if self.ffmpeg_normalize.keep_other_audio and (
1121
- self.ffmpeg_normalize.audio_streams is not None
1122
- or self.ffmpeg_normalize.audio_default_only
1123
- ):
1124
- streams_to_passthrough = [
1125
- s for s in all_audio_streams if s not in streams_to_normalize
1126
- ]
1127
- else:
1128
- streams_to_passthrough = []
1129
-
1130
1173
  # ... and map the output of the normalization filters
1131
1174
  for ol in output_labels:
1132
1175
  cmd.extend(["-map", ol])
@@ -1229,6 +1272,15 @@ class MediaFile:
1229
1272
  # drop it from the copy (keeping any other flags, e.g. comment)
1230
1273
  # to avoid players picking the un-normalized original
1231
1274
  cmd.extend([f"-disposition:a:{output_audio_idx}", "-default"])
1275
+ # per-stream metadata mapping above turns off ffmpeg's automatic
1276
+ # copying of stream tags, so map the copy's tags explicitly
1277
+ if not self.ffmpeg_normalize.metadata_disable:
1278
+ cmd.extend(
1279
+ [
1280
+ f"-map_metadata:s:a:{output_audio_idx}",
1281
+ f"0:s:a:{index}",
1282
+ ]
1283
+ )
1232
1284
  output_audio_idx += 1
1233
1285
 
1234
1286
  # extra options (if any)
@@ -1291,9 +1343,10 @@ class MediaFile:
1291
1343
  # in the second pass, we do not normalize stream-by-stream, so we set the stats based on the
1292
1344
  # overall output (which includes multiple loudnorm stats)
1293
1345
  if self.ffmpeg_normalize.normalization_type == "ebu":
1294
- ebu_pass_2_stats = list(
1295
- AudioStream.prune_and_parse_loudnorm_output(output).values()
1296
- )
1346
+ # ffmpeg does not print the loudnorm stats in filter order, so sort
1347
+ # them by filter index, which follows the order of the streams
1348
+ parsed_stats = AudioStream.prune_and_parse_loudnorm_output(output)
1349
+ ebu_pass_2_stats = [parsed_stats[key] for key in sorted(parsed_stats)]
1297
1350
  # Only set second pass stats for streams that were actually normalized
1298
1351
  streams_to_normalize = self._get_streams_to_normalize()
1299
1352
  if len(ebu_pass_2_stats) == len(streams_to_normalize):
@@ -1336,13 +1389,13 @@ class MediaFile:
1336
1389
  f"To avoid this, raise --true-peak (-tp) to at least {min_tp:.1f}, "
1337
1390
  f"or lower the target level (-t) to at most {max_target:.1f}."
1338
1391
  )
1339
- elif (
1340
- pass1_stats["input_lra"]
1341
- > self.ffmpeg_normalize.loudness_range_target
1392
+ elif pass1_stats["input_lra"] > (
1393
+ lra_target := audio_stream.loudness_range_target
1394
+ or self.ffmpeg_normalize.loudness_range_target
1342
1395
  ):
1343
1396
  reason = (
1344
1397
  f" Reason: the input loudness range ({pass1_stats['input_lra']:.2f} LU) "
1345
- f"exceeds the target ({self.ffmpeg_normalize.loudness_range_target:.2f} LU). "
1398
+ f"exceeds the target ({lra_target:.2f} LU). "
1346
1399
  "Consider raising the target loudness range or using "
1347
1400
  "--keep-loudness-range-target / --keep-lra-above-loudness-range-target."
1348
1401
  )
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import argparse
5
6
  import json
6
7
  import logging
7
8
  import os
@@ -169,7 +170,11 @@ class PresetManager:
169
170
  return preset_data
170
171
 
171
172
  def merge_preset_with_args(
172
- self, preset_data: dict[str, Any], cli_args: Any, explicit_args: set[str]
173
+ self,
174
+ preset_data: dict[str, Any],
175
+ cli_args: Any,
176
+ explicit_args: set[str],
177
+ parser: argparse.ArgumentParser | None = None,
173
178
  ) -> None:
174
179
  """Apply preset values only to options omitted from the command line.
175
180
 
@@ -177,7 +182,13 @@ class PresetManager:
177
182
  preset_data: Preset configuration.
178
183
  cli_args: Parsed arguments, including defaults; modified in place.
179
184
  explicit_args: Argument destinations explicitly supplied by the user.
185
+ parser: The CLI parser. If given, preset values are converted to
186
+ the option's type, as if they had been given on the command line.
187
+
188
+ Raises:
189
+ ValueError: If a preset value cannot be converted to the option's type.
180
190
  """
191
+ actions = {action.dest: action for action in parser._actions} if parser else {}
181
192
  for key, value in preset_data.items():
182
193
  attr_name = key.replace("-", "_")
183
194
  if not hasattr(cli_args, attr_name):
@@ -185,10 +196,33 @@ class PresetManager:
185
196
  f"Preset option '{key}' is not a valid ffmpeg-normalize option. Skipping."
186
197
  )
187
198
  continue
199
+ if attr_name in actions:
200
+ value = self._convert_preset_value(key, value, actions[attr_name])
188
201
  if attr_name not in explicit_args:
189
202
  setattr(cli_args, attr_name, value)
190
203
  _logger.debug(f"Applied preset option '{key}' = {value}")
191
204
 
205
+ @staticmethod
206
+ def _convert_preset_value(key: str, value: Any, action: argparse.Action) -> Any:
207
+ """Convert a JSON preset value to what the CLI option would produce."""
208
+ # list values for options that take one string on the command line
209
+ if isinstance(value, list) and action.nargs is None:
210
+ if action.dest.startswith("extra_"):
211
+ # extra options accept a JSON list
212
+ value = json.dumps([str(v) for v in value])
213
+ else:
214
+ # e.g. audio streams, which are comma-separated
215
+ value = ",".join(str(v) for v in value)
216
+ convert = action.type
217
+ if isinstance(value, str) and (convert is int or convert is float):
218
+ try:
219
+ value = convert(value)
220
+ except ValueError:
221
+ raise ValueError(
222
+ f"Invalid value for preset option '{key}': {value!r}"
223
+ ) from None
224
+ return value
225
+
192
226
  def validate_preset(self, preset_name: str) -> tuple[bool, str]:
193
227
  """Validate that a preset file exists and is valid.
194
228
 
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import logging
5
+ import math
5
6
  import os
6
7
  import re
7
8
  from typing import TYPE_CHECKING, Iterator, Literal, TypedDict, cast
@@ -189,6 +190,8 @@ class AudioStream(MediaStream):
189
190
  # Stays None for EBU, where the gain is derived from the second pass stats.
190
191
  self.applied_gain: float | None = None
191
192
  self.verification_target_level: float | None = None
193
+ # loudness range target used for this stream in the second pass
194
+ self.loudness_range_target: float | None = None
192
195
  self.verification: VerificationResult | None = None
193
196
 
194
197
  self.sample_rate = sample_rate
@@ -360,17 +363,29 @@ class AudioStream(MediaStream):
360
363
  Returns:
361
364
  str: The PCM codec string.
362
365
  """
366
+ # AIFF only takes big-endian PCM (apart from 16-bit)
367
+ output_format = self.media_file.ffmpeg_normalize.output_format
368
+ big_endian = output_format == "aiff" or (
369
+ output_format is None
370
+ and self.media_file.output_ext.lower() in ("aif", "aiff", "aifc")
371
+ )
372
+ endian = "be" if big_endian else "le"
373
+
363
374
  if not self.bit_depth:
364
- return "pcm_s16le"
375
+ return f"pcm_s16{endian}"
376
+ elif self.is_float and self.bit_depth in [32, 64]:
377
+ # keep float sources in float, so gain above 0 dBFS does not clip
378
+ return f"pcm_f{self.bit_depth}{endian}"
365
379
  elif self.bit_depth <= 8:
366
- return "pcm_s8"
380
+ # unsigned, since WAV and Matroska cannot hold signed 8-bit PCM
381
+ return "pcm_u8"
367
382
  elif self.bit_depth in [16, 24, 32, 64]:
368
- return f"pcm_s{self.bit_depth}le"
383
+ return f"pcm_s{self.bit_depth}{endian}"
369
384
  else:
370
385
  _logger.warning(
371
- f"{self.media_file.input_file}: Unsupported bit depth {self.bit_depth}, falling back to pcm_s16le"
386
+ f"{self.media_file.input_file}: Unsupported bit depth {self.bit_depth}, falling back to pcm_s16{endian}"
372
387
  )
373
- return "pcm_s16le"
388
+ return f"pcm_s16{endian}"
374
389
 
375
390
  def get_output_sample_fmt(self, codec: str | None) -> str | None:
376
391
  """
@@ -763,6 +778,10 @@ class AudioStream(MediaStream):
763
778
 
764
779
  will_use_dynamic_mode: bool = self.media_file.ffmpeg_normalize.dynamic
765
780
 
781
+ # per stream, so a stream that keeps its own range does not change the
782
+ # target for the streams and files processed after it
783
+ loudness_range_target = self.media_file.ffmpeg_normalize.loudness_range_target
784
+
766
785
  if self.media_file.ffmpeg_normalize.keep_loudness_range_target:
767
786
  _logger.debug(
768
787
  "Keeping target loudness range in second pass loudnorm filter"
@@ -774,34 +793,33 @@ class AudioStream(MediaStream):
774
793
  f"({input_lra}), capping to allowed range"
775
794
  )
776
795
 
777
- self.media_file.ffmpeg_normalize.loudness_range_target = self._constrain(
796
+ loudness_range_target = self._constrain(
778
797
  self.loudness_statistics["ebu_pass1"]["input_lra"], 1, 50
779
798
  )
780
799
 
781
800
  if self.media_file.ffmpeg_normalize.keep_lra_above_loudness_range_target:
782
801
  if (
783
802
  self.loudness_statistics["ebu_pass1"]["input_lra"]
784
- <= self.media_file.ffmpeg_normalize.loudness_range_target
803
+ <= loudness_range_target
785
804
  ):
786
805
  _logger.debug(
787
806
  "Setting loudness range target in second pass loudnorm filter"
788
807
  )
789
808
  else:
790
- self.media_file.ffmpeg_normalize.loudness_range_target = (
791
- self.loudness_statistics["ebu_pass1"]["input_lra"]
809
+ loudness_range_target = self._constrain(
810
+ self.loudness_statistics["ebu_pass1"]["input_lra"], 1, 50
792
811
  )
793
812
  _logger.debug(
794
813
  "Keeping target loudness range in second pass loudnorm filter"
795
814
  )
796
815
 
797
816
  if (
798
- self.media_file.ffmpeg_normalize.loudness_range_target
799
- < self.loudness_statistics["ebu_pass1"]["input_lra"]
817
+ loudness_range_target < self.loudness_statistics["ebu_pass1"]["input_lra"]
800
818
  and not will_use_dynamic_mode
801
819
  ):
802
820
  _logger.warning(
803
821
  f"{self.media_file.input_file}: Input file had loudness range of {self.loudness_statistics['ebu_pass1']['input_lra']}. "
804
- f"This is larger than the loudness range target ({self.media_file.ffmpeg_normalize.loudness_range_target}). "
822
+ f"This is larger than the loudness range target ({loudness_range_target}). "
805
823
  "Normalization will revert to dynamic mode. Choose a higher target loudness range if you want linear normalization. "
806
824
  "Alternatively, use the --keep-loudness-range-target or --keep-lra-above-loudness-range-target option to keep the target loudness range from "
807
825
  "the input."
@@ -874,7 +892,7 @@ class AudioStream(MediaStream):
874
892
 
875
893
  opts = {
876
894
  "i": target_level,
877
- "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
895
+ "lra": loudness_range_target,
878
896
  "tp": self.media_file.ffmpeg_normalize.true_peak,
879
897
  "offset": self._constrain(target_offset, -99, 99, name="target_offset"),
880
898
  "measured_i": self._constrain(stats["input_i"], -99, 0, name="input_i"),
@@ -893,6 +911,7 @@ class AudioStream(MediaStream):
893
911
  opts["dual_mono"] = "true"
894
912
 
895
913
  self.verification_target_level = target_level
914
+ self.loudness_range_target = loudness_range_target
896
915
  return "loudnorm=" + dict_to_filter_opts(opts)
897
916
 
898
917
  def get_second_pass_opts_peakrms(self, batch_reference: float | None = None) -> str:
@@ -949,6 +968,16 @@ class AudioStream(MediaStream):
949
968
  "Can only set adjustment for peak and RMS normalization"
950
969
  )
951
970
 
971
+ # silent input measures as -inf dB, which would give an infinite gain
972
+ # (or NaN in batch mode) and turn the output into NaN samples
973
+ if not math.isfinite(adjustment):
974
+ _logger.warning(
975
+ f"{self.media_file.input_file}: Stream {self.stream_id} is silent, "
976
+ "leaving its volume unchanged"
977
+ )
978
+ self.applied_gain = 0.0
979
+ return "volume=0dB"
980
+
952
981
  _logger.info(
953
982
  f"Adjusting stream {self.stream_id} by {adjustment} dB to reach {target_level}"
954
983
  )