ffmpeg_normalize

 1import importlib.metadata
 2
 3from ._cmd_utils import ffmpeg_env
 4from ._errors import FFmpegNormalizeError
 5from ._ffmpeg_normalize import FFmpegNormalize
 6from ._media_file import MediaFile
 7from ._streams import AudioStream, MediaStream, SubtitleStream, VideoStream
 8
 9__version__ = importlib.metadata.version("ffmpeg-normalize")
10
11__module_name__ = "ffmpeg_normalize"
12
13__all__ = [
14    "FFmpegNormalize",
15    "FFmpegNormalizeError",
16    "MediaFile",
17    "AudioStream",
18    "VideoStream",
19    "SubtitleStream",
20    "MediaStream",
21    "ffmpeg_env",
22    "__version__",
23]
class FFmpegNormalize:
 62class FFmpegNormalize:
 63    """
 64    ffmpeg-normalize class.
 65
 66    Args:
 67        normalization_type (str, optional): Normalization type. Defaults to "ebu".
 68        target_level (float, optional): Target level. Defaults to -23.0.
 69        print_stats (bool, optional): Print loudnorm stats. Defaults to False.
 70        print_summary (bool, optional): Print a before/after summary table to stderr after processing. Defaults to False.
 71        threshold (float, optional): When set to a positive value, skip normalization when the input is already within this many dB/LU of the target level, copying it through unchanged. Defaults to 0 (disabled, always normalize).
 72        loudness_range_target (float, optional): Loudness range target. Defaults to 7.0.
 73        keep_loudness_range_target (bool, optional): Keep loudness range target. Defaults to False.
 74        keep_lra_above_loudness_range_target (bool, optional): Keep input loudness range above loudness range target. Defaults to False.
 75        true_peak (float, optional): True peak. Defaults to -2.0.
 76        offset (float, optional): Offset. Defaults to 0.0.
 77        lower_only (bool, optional): Whether the audio should not increase in loudness. Defaults to False.
 78        auto_lower_loudness_target (bool, optional): Automatically lower EBU Integrated Loudness Target.
 79        dual_mono (bool, optional): Dual mono. Defaults to False.
 80        dynamic (bool, optional): Use dynamic EBU R128 normalization. This is a one-pass algorithm and skips the initial media scan. Defaults to False.
 81        audio_codec (str, optional): Audio codec. Defaults to "pcm_s16le".
 82        audio_bitrate (float, optional): Audio bitrate. Defaults to None.
 83        sample_rate (int, optional): Sample rate. Defaults to None.
 84        audio_channels (int | None, optional): Audio channels. Defaults to None.
 85        keep_original_audio (bool, optional): Keep original audio. Defaults to False.
 86        pre_filter (str, optional): Pre filter. Defaults to None.
 87        post_filter (str, optional): Post filter. Defaults to None.
 88        video_codec (str, optional): Video codec. Defaults to "copy".
 89        video_disable (bool, optional): Disable video. Defaults to False.
 90        subtitle_disable (bool, optional): Disable subtitles. Defaults to False.
 91        metadata_disable (bool, optional): Disable metadata. Defaults to False.
 92        chapters_disable (bool, optional): Disable chapters. Defaults to False.
 93        write_encoder_settings (bool, optional): Write the effective encoder settings (codec, bitrate, sample rate, channels and the normalization filter including the measured loudnorm values) as an ENCODER_SETTINGS tag on each normalized audio stream. Defaults to False.
 94        extra_input_options (list, optional): Extra input options. Defaults to None.
 95        extra_output_options (list, optional): Extra output options. Defaults to None.
 96        output_format (str, optional): Output format. Defaults to None.
 97        extension (str, optional): Output file extension to use for output files that were not explicitly specified. Defaults to "mkv".
 98        dry_run (bool, optional): Dry run. Defaults to False.
 99        debug (bool, optional): Debug. Defaults to False.
100        progress (bool, optional): Progress. Defaults to False.
101        replaygain (bool, optional): Write ReplayGain tags without normalizing. Defaults to False.
102        batch (bool, optional): Preserve relative loudness between files (album mode). Defaults to False.
103        audio_streams (list[int] | None, optional): List of audio stream indices to normalize. Defaults to None (all streams).
104        audio_default_only (bool, optional): Only normalize audio streams with default disposition. Defaults to False.
105        keep_other_audio (bool, optional): Keep non-selected audio streams in output (copy without normalization). Defaults to False.
106        keep_mtime (bool, optional): Copy the input file's modification time to the output file. Defaults to False.
107        keep_bit_depth (bool, optional): Carry the detected input bit depth through to the output encoder. Defaults to True.
108        verify (bool, optional): Measure the encoded output and check its effective target and peak ceiling. Defaults to False. Not available with ReplayGain; skipped during dry runs.
109        verify_loudness_tolerance (float, optional): Allowed level deviation in dB/LU. Defaults to 0.5.
110        verify_peak_tolerance (float, optional): Allowed peak overshoot in dB. Defaults to 0.1.
111
112    Raises:
113        FFmpegNormalizeError: If the ffmpeg executable is not found or does not support the loudnorm filter.
114    """
115
116    # Default parameter values - single source of truth for all defaults
117    # Note: output_folder is a CLI-level option and not passed to FFmpegNormalize.__init__
118    DEFAULTS = {
119        "normalization_type": "ebu",
120        "target_level": -23.0,
121        "print_stats": False,
122        "print_summary": False,
123        "threshold": 0.0,
124        "loudness_range_target": 7.0,
125        "keep_loudness_range_target": False,
126        "keep_lra_above_loudness_range_target": False,
127        "true_peak": -2.0,
128        "offset": 0.0,
129        "lower_only": False,
130        "auto_lower_loudness_target": False,
131        "dual_mono": False,
132        "dynamic": False,
133        "audio_codec": "pcm_s16le",
134        "audio_bitrate": None,
135        "sample_rate": None,
136        "audio_channels": None,
137        "keep_original_audio": False,
138        "pre_filter": None,
139        "post_filter": None,
140        "video_codec": "copy",
141        "video_disable": False,
142        "subtitle_disable": False,
143        "metadata_disable": False,
144        "chapters_disable": False,
145        "write_encoder_settings": False,
146        "extra_input_options": None,
147        "extra_output_options": None,
148        "output_format": None,
149        "output_folder": "normalized",
150        "extension": "mkv",
151        "dry_run": False,
152        "debug": False,
153        "progress": False,
154        "replaygain": False,
155        "batch": False,
156        "audio_streams": None,
157        "audio_default_only": False,
158        "keep_other_audio": False,
159        "keep_mtime": False,
160        "keep_bit_depth": True,
161        "verify": False,
162        "verify_loudness_tolerance": 0.5,
163        "verify_peak_tolerance": 0.1,
164    }
165
166    def __init__(
167        self,
168        normalization_type: Literal["ebu", "rms", "peak"] = "ebu",
169        target_level: float = -23.0,
170        print_stats: bool = False,
171        print_summary: bool = False,
172        threshold: float = 0.0,
173        loudness_range_target: float = 7.0,
174        keep_loudness_range_target: bool = False,
175        keep_lra_above_loudness_range_target: bool = False,
176        true_peak: float = -2.0,
177        offset: float = 0.0,
178        lower_only: bool = False,
179        auto_lower_loudness_target: bool = False,
180        dual_mono: bool = False,
181        dynamic: bool = False,
182        audio_codec: str = "pcm_s16le",
183        audio_bitrate: float | None = None,
184        sample_rate: float | int | None = None,
185        audio_channels: int | None = None,
186        keep_original_audio: bool = False,
187        pre_filter: str | None = None,
188        post_filter: str | None = None,
189        video_codec: str = "copy",
190        video_disable: bool = False,
191        subtitle_disable: bool = False,
192        metadata_disable: bool = False,
193        chapters_disable: bool = False,
194        write_encoder_settings: bool = False,
195        extra_input_options: list[str] | None = None,
196        extra_output_options: list[str] | None = None,
197        output_format: str | None = None,
198        extension: str = "mkv",
199        dry_run: bool = False,
200        debug: bool = False,
201        progress: bool = False,
202        replaygain: bool = False,
203        batch: bool = False,
204        audio_streams: list[int] | None = None,
205        audio_default_only: bool = False,
206        keep_other_audio: bool = False,
207        keep_mtime: bool = False,
208        keep_bit_depth: bool = True,
209        verify: bool = False,
210        verify_loudness_tolerance: float = 0.5,
211        verify_peak_tolerance: float = 0.1,
212    ):
213        self.ffmpeg_exe = get_ffmpeg_exe()
214        self.has_loudnorm_capabilities = ffmpeg_has_loudnorm()
215
216        if normalization_type not in NORMALIZATION_TYPES:
217            raise FFmpegNormalizeError(
218                "Normalization type must be: 'ebu', 'rms', or 'peak'"
219            )
220        self.normalization_type = normalization_type
221
222        if not self.has_loudnorm_capabilities and self.normalization_type == "ebu":
223            raise FFmpegNormalizeError(
224                "Your ffmpeg does not support the 'loudnorm' EBU R128 filter. "
225                "Please install ffmpeg v4.2 or above, or choose another normalization type."
226            )
227
228        if self.normalization_type == "ebu":
229            self.target_level = check_range(target_level, -70, -5, name="target_level")
230        else:
231            self.target_level = check_range(target_level, -99, 0, name="target_level")
232
233        self.print_stats = print_stats
234        self.print_summary = print_summary
235
236        self.threshold = check_range(threshold, 0, 99, name="threshold")
237
238        self.loudness_range_target = check_range(
239            loudness_range_target, 1, 50, name="loudness_range_target"
240        )
241
242        self.keep_loudness_range_target = keep_loudness_range_target
243
244        if self.keep_loudness_range_target and loudness_range_target != 7.0:
245            _logger.warning(
246                "Setting --keep-loudness-range-target will override your set loudness range target value! "
247                "Remove --keep-loudness-range-target or remove the --lrt/--loudness-range-target option."
248            )
249
250        self.keep_lra_above_loudness_range_target = keep_lra_above_loudness_range_target
251
252        if (
253            self.keep_loudness_range_target
254            and self.keep_lra_above_loudness_range_target
255        ):
256            raise FFmpegNormalizeError(
257                "Options --keep-loudness-range-target and --keep-lra-above-loudness-range-target are mutually exclusive! "
258                "Please choose just one of the two options."
259            )
260
261        self.true_peak = check_range(true_peak, -9, 0, name="true_peak")
262        self.offset = check_range(offset, -99, 99, name="offset")
263        self.lower_only = lower_only
264        self.auto_lower_loudness_target = auto_lower_loudness_target
265
266        # Ensure library user is passing correct types
267        assert isinstance(dual_mono, bool), "dual_mono must be bool"
268        assert isinstance(dynamic, bool), "dynamic must be bool"
269
270        self.dual_mono = dual_mono
271        self.dynamic = dynamic
272        self.sample_rate = None if sample_rate is None else int(sample_rate)
273        self.audio_channels = None if audio_channels is None else int(audio_channels)
274
275        self.audio_codec = audio_codec
276        self.audio_bitrate = audio_bitrate
277        self.keep_original_audio = keep_original_audio
278        self.video_codec = video_codec
279        self.video_disable = video_disable
280        self.subtitle_disable = subtitle_disable
281        self.metadata_disable = metadata_disable
282        self.chapters_disable = chapters_disable
283        self.write_encoder_settings = write_encoder_settings
284
285        if self.write_encoder_settings and self.metadata_disable:
286            _logger.warning(
287                "write_encoder_settings has no effect together with metadata_disable; "
288                "no metadata will be written to the output."
289            )
290
291        self.extra_input_options = extra_input_options
292        self.extra_output_options = extra_output_options
293        self.pre_filter = pre_filter
294        self.post_filter = post_filter
295
296        self.output_format = output_format
297        self.extension = extension
298        self.dry_run = dry_run
299        self.debug = debug
300        self.progress = progress
301        self.progress_display = ProgressDisplay(enabled=False)
302        self.replaygain = replaygain
303        self.batch = batch
304
305        # Stream selection options
306        self.audio_streams = audio_streams
307        self.audio_default_only = audio_default_only
308        self.keep_other_audio = keep_other_audio
309
310        self.keep_mtime = keep_mtime
311        self.keep_bit_depth = keep_bit_depth
312        self.verify = verify
313        self.verify_loudness_tolerance = check_range(
314            verify_loudness_tolerance, 0, 99, name="verify_loudness_tolerance"
315        )
316        self.verify_peak_tolerance = check_range(
317            verify_peak_tolerance, 0, 99, name="verify_peak_tolerance"
318        )
319        if not all(
320            math.isfinite(value)
321            for value in (self.verify_loudness_tolerance, self.verify_peak_tolerance)
322        ):
323            raise FFmpegNormalizeError("Verification tolerances must be finite")
324        if verify and replaygain:
325            raise FFmpegNormalizeError("--verify cannot be combined with --replaygain")
326
327        if self.output_format in PCM_INCOMPATIBLE_FORMATS:
328            if self.audio_codec is not None and "pcm" in self.audio_codec:
329                raise FFmpegNormalizeError(
330                    f"Output format {self.output_format} does not support PCM audio. "
331                    "Please choose a suitable audio codec with the -c:a option."
332                )
333            if (
334                self.audio_codec is None
335                and get_muxer_default_audio_encoder(self.output_format) is None
336            ):
337                raise FFmpegNormalizeError(
338                    f"Output format {self.output_format} does not support PCM audio, "
339                    "and a default audio codec could not be determined. Please choose "
340                    "a suitable audio codec with the -c:a option."
341                )
342
343        # replaygain only works for EBU for now
344        if self.replaygain and self.normalization_type != "ebu":
345            raise FFmpegNormalizeError(
346                "ReplayGain only works for EBU normalization type for now."
347            )
348
349        # Validate stream selection options
350        if self.audio_streams is not None and self.audio_default_only:
351            raise FFmpegNormalizeError(
352                "Cannot use both audio_streams and audio_default_only together."
353            )
354
355        if self.keep_other_audio and self.keep_original_audio:
356            raise FFmpegNormalizeError(
357                "Cannot use both --keep-other-audio and --keep-original-audio together. "
358                "Use --keep-original-audio to keep all original streams alongside normalized ones, "
359                "or --keep-other-audio to keep only non-selected streams as passthrough."
360            )
361
362        self.stats: list[LoudnessStatisticsWithMetadata] = []
363        self.media_files: list[MediaFile] = []
364        self.file_count = 0
365
366    def add_media_file(self, input_file: str, output_file: str) -> None:
367        """
368        Add a media file to normalize
369
370        Args:
371            input_file (str): Path to input file
372            output_file (str): Path to output file
373        """
374        if not os.path.exists(input_file):
375            raise FFmpegNormalizeError(f"file {input_file} does not exist")
376
377        ext = os.path.splitext(output_file)[1][1:].lower()
378        if ext in PCM_INCOMPATIBLE_EXTS:
379            if self.audio_codec is not None and "pcm" in self.audio_codec:
380                raise FFmpegNormalizeError(
381                    f"Output extension {ext} does not support PCM audio. "
382                    "Please choose a suitable audio codec with the -c:a option."
383                )
384            if (
385                self.audio_codec is None
386                and get_muxer_default_audio_encoder(ext) is None
387            ):
388                raise FFmpegNormalizeError(
389                    f"Output extension {ext} does not support PCM audio, and a "
390                    "default audio codec could not be determined. Please choose a "
391                    "suitable audio codec with the -c:a option."
392                )
393
394        self.media_files.append(MediaFile(self, input_file, output_file))
395        self.file_count += 1
396
397    @staticmethod
398    def validate_input_files(input_files: list[str]) -> list[str]:
399        """
400        Validate all input files before processing.
401
402        This method checks that each input file exists, is readable, and contains
403        at least one audio stream. All files are validated upfront so that users
404        can fix all issues before rerunning the batch.
405
406        Args:
407            input_files: List of input file paths to validate
408
409        Returns:
410            list: List of error messages for invalid files. Empty if all files are valid.
411        """
412        errors = []
413        for input_file in input_files:
414            is_valid, error_msg = validate_input_file(input_file)
415            if not is_valid and error_msg:
416                errors.append(error_msg)
417        return errors
418
419    @staticmethod
420    def validate_output_files(input_files: list[str], output_files: list[str]) -> None:
421        """Reject duplicate destinations and outputs that overwrite another input.
422
423        Resolve symlinks and existing hard links, while allowing each file to be
424        normalized in place and multiple outputs to the null device.
425        """
426
427        def path_keys(path: str) -> list[str | tuple[int, int]]:
428            keys: list[str | tuple[int, int]] = [
429                os.path.normcase(os.path.realpath(path))
430            ]
431            if os.path.exists(path):
432                stat = os.stat(path)
433                keys.append((stat.st_dev, stat.st_ino))
434            return keys
435
436        input_owners: dict[str | tuple[int, int], set[int]] = {}
437        for index, path in enumerate(input_files):
438            for key in path_keys(path):
439                input_owners.setdefault(key, set()).add(index)
440
441        output_owners: dict[str | tuple[int, int], str] = {}
442        for index, path in enumerate(output_files):
443            if os.path.realpath(path) == os.path.realpath(os.devnull):
444                continue
445            for key in path_keys(path):
446                if key in output_owners:
447                    raise FFmpegNormalizeError(
448                        f"Output collision: '{path}' and '{output_owners[key]}' "
449                        "refer to the same destination. Specify distinct output paths."
450                    )
451                if input_owners.get(key, set()) - {index}:
452                    raise FFmpegNormalizeError(
453                        f"Output '{path}' would overwrite another input file. "
454                        "Specify a different output path."
455                    )
456                output_owners[key] = path
457
458    def _calculate_batch_reference(self) -> float | None:
459        """
460        Calculate a shared reference from the selected streams' measurements.
461
462        Peak mode uses the highest sample peak. RMS mode uses the average RMS,
463        with gain capped by the highest sample peak. EBU uses average LUFS.
464
465        Returns:
466            float | None: The batch reference loudness value, or None if no measurements found.
467
468        Note:
469            RMS and EBU averages weight each selected stream equally.
470        """
471        measurements: list[float] = []
472        peaks: list[float] = []
473
474        for media_file in self.media_files:
475            if media_file.status == "error":
476                continue
477            for stream in media_file._get_streams_to_normalize():
478                peak = stream.loudness_statistics.get("max")
479                if peak is not None and math.isfinite(peak):
480                    peaks.append(float(peak))
481                if self.normalization_type == "ebu":
482                    # Get EBU integrated loudness from first pass
483                    ebu_stats = stream.loudness_statistics.get("ebu_pass1")
484                    if ebu_stats and "input_i" in ebu_stats:
485                        measurements.append(float(ebu_stats["input_i"]))
486                elif self.normalization_type == "rms":
487                    # Get RMS mean value
488                    mean = stream.loudness_statistics.get("mean")
489                    if mean is not None:
490                        measurements.append(float(mean))
491                elif self.normalization_type == "peak":
492                    # Get peak max value
493                    max_val = stream.loudness_statistics.get("max")
494                    if max_val is not None:
495                        measurements.append(float(max_val))
496
497        measurements = [value for value in measurements if math.isfinite(value)]
498        if not measurements:
499            _logger.warning(
500                "No loudness measurements found for batch reference calculation. "
501                "Batch mode will not be applied."
502            )
503            return None
504
505        # Peak mode targets the loudest sample in the album. RMS mode targets
506        # the average level, but limits the shared gain to available headroom.
507        batch_reference = (
508            max(measurements)
509            if self.normalization_type == "peak"
510            else sum(measurements) / len(measurements)
511        )
512        if self.normalization_type == "rms" and peaks:
513            safe_reference = self.target_level + max(peaks)
514            if safe_reference > batch_reference:
515                _logger.warning(
516                    "Reducing album gain to avoid sample clipping; "
517                    "the requested RMS target will not be reached."
518                )
519                batch_reference = safe_reference
520        if self.lower_only and self.normalization_type in ("peak", "rms"):
521            batch_reference = max(batch_reference, self.target_level)
522        _logger.debug(f"Batch mode: Measurements for batch reference: {measurements}")
523        _logger.info(
524            f"Batch mode: Calculated reference loudness = {batch_reference:.2f} "
525            f"({self.normalization_type.upper()}, based on {len(measurements)} stream(s))"
526        )
527
528        return batch_reference
529
530    def _iter_media_files(self, description: str) -> Iterator[tuple[int, MediaFile]]:
531        """
532        Iterate over all media files while updating the overall progress bar.
533
534        Args:
535            description (str): Label of the overall progress bar
536
537        Yields:
538            tuple[int, MediaFile]: The index and the media file
539        """
540        display = self.progress_display
541        display.start_overall(description, self.file_count)
542        for index, media_file in enumerate(self.media_files):
543            display.set_current(display_name(media_file.input_file))
544            yield index, media_file
545            display.advance_overall()
546        display.set_current(None)
547
548    def run_normalization(self) -> None:
549        """
550        Run the normalization procedures.
551
552        In batch mode, all files are analyzed first (first pass), then a batch reference
553        loudness is calculated, and finally all files are normalized (second pass) with
554        adjustments relative to the batch reference to preserve relative loudness.
555
556        In non-batch mode, each file is processed completely (both passes) before
557        moving to the next file.
558        """
559        if (
560            self.verify
561            and not self.dry_run
562            and any(
563                os.path.realpath(file.output_file) == os.path.realpath(os.devnull)
564                for file in self.media_files
565            )
566        ):
567            raise FFmpegNormalizeError(
568                "--verify requires an output file, not the null device"
569            )
570        if not self.replaygain:
571            self.validate_output_files(
572                [media_file.input_file for media_file in self.media_files],
573                [media_file.output_file for media_file in self.media_files],
574            )
575        with ProgressDisplay(enabled=self.progress) as display:
576            self.progress_display = display
577            try:
578                self._process_media_files()
579            finally:
580                self.progress_display = ProgressDisplay(enabled=False)
581
582        if self.print_stats:
583            json.dump(
584                list(
585                    chain.from_iterable(
586                        media_file.get_stats() for media_file in self.media_files
587                    )
588                ),
589                sys.stdout,
590                indent=4,
591            )
592            print()
593
594        if self.print_summary:
595            console = get_console()
596            if console.is_terminal:
597                console.print(self.summary_renderable())
598            else:
599                print(self.format_summary(), file=sys.stderr)
600
601    def _process_media_files(self) -> None:
602        """Run both passes for all media files, in batch or per-file mode."""
603        if self.batch:
604            # Batch mode: analyze all files first, then normalize with relative adjustments
605            _logger.info(
606                f"Batch mode enabled: processing {self.file_count} file(s) while preserving relative loudness"
607            )
608
609            # Recommend RMS/Peak for album normalization instead of EBU
610            if self.normalization_type == "ebu":
611                _logger.warning(
612                    "Using EBU R128 normalization with --batch. For true album normalization where "
613                    "all tracks are shifted by the same amount, consider using --normalization-type rms "
614                    "or --normalization-type peak instead. EBU normalization applies different processing "
615                    "to each track based on its loudness characteristics, which may alter relative levels "
616                    "slightly due to psychoacoustic adjustments."
617                )
618
619            # Warn if using dynamic EBU mode with batch
620            if self.dynamic and self.normalization_type == "ebu":
621                _logger.warning(
622                    "ffmpeg uses dynamic EBU normalization. This may change relative "
623                    "loudness within a file. Use linear mode for true album normalization, or "
624                    "switch to --normalization-type peak or --normalization-type rms instead. "
625                    "To force linear mode, use --keep-lra-above-loudness-range-target or "
626                    "--keep-loudness-range-target."
627                )
628
629            # Phase 1: Run first pass on all files to collect measurements
630            _logger.info("Phase 1: Analyzing all files...")
631            for index, media_file in self._iter_media_files("Analysis"):
632                _logger.info(
633                    f"Analyzing file {media_file} ({index + 1} of {self.file_count})"
634                )
635
636                try:
637                    # Only run first pass if not in dynamic EBU mode
638                    if not (self.dynamic and self.normalization_type == "ebu"):
639                        media_file._first_pass()
640                    else:
641                        _logger.debug(
642                            "Dynamic EBU mode: First pass skipped for this file."
643                        )
644                except Exception as e:
645                    self._record_failure(media_file, e, "analyzing")
646                    continue
647
648            # Phase 2: Calculate batch reference loudness
649            batch_reference = self._calculate_batch_reference()
650
651            # Phase 3: Run second pass on all files with batch reference
652            _logger.info("Phase 2: Normalizing all files...")
653            for index, media_file in self._iter_media_files("Normalization"):
654                # Skip files that already failed during analysis
655                if media_file.status == "error":
656                    _logger.debug(f"Skipping {media_file} because its analysis failed")
657                    continue
658
659                _logger.info(
660                    f"Normalizing file {media_file} ({index + 1} of {self.file_count})"
661                )
662
663                try:
664                    media_file.run_normalization(batch_reference=batch_reference)
665                    if self.verify and not self.dry_run:
666                        media_file.verify_output()
667                except Exception as e:
668                    self._record_failure(media_file, e, "processing")
669                    continue
670        else:
671            # Non-batch mode: process each file completely before moving to the next
672            for index, media_file in self._iter_media_files("Files"):
673                _logger.info(
674                    f"Normalizing file {media_file} ({index + 1} of {self.file_count})"
675                )
676
677                try:
678                    media_file.run_normalization()
679                    if self.verify and not self.dry_run:
680                        media_file.verify_output()
681                except Exception as e:
682                    self._record_failure(media_file, e, "processing")
683                    continue
684
685    @staticmethod
686    def _record_failure(media_file: MediaFile, error: Exception, action: str) -> None:
687        """
688        Mark a media file as failed and log a short description of the error.
689
690        The full error (e.g. the complete ffmpeg output) is only logged in
691        debug mode.
692
693        Args:
694            media_file (MediaFile): The file that failed
695            error (Exception): The error
696            action (str): What was being done, e.g. "processing"
697        """
698        media_file.status = "error"
699        media_file.error = describe_error(error)
700        _logger.debug(f"Full error for {media_file.input_file}: {error}", exc_info=True)
701        _logger.error(f"Error {action} input file {media_file}: {media_file.error}")
702
703    def get_summary(self) -> list[SummaryRow]:
704        """
705        Return the before/after summary for all audio streams of all files.
706
707        Each entry contains the input level, output level, output peak and the
708        applied gain in dB. The level is the integrated loudness for EBU, the
709        RMS level for RMS, and the peak level for peak normalization. The
710        output peak is the true peak for EBU and the sample peak otherwise.
711        Values that are not available are None.
712
713        Returns:
714            list[SummaryRow]: One summary entry per audio stream
715        """
716        return list(
717            chain.from_iterable(
718                media_file.get_summary() for media_file in self.media_files
719            )
720        )
721
722    def _summary_parts(
723        self,
724    ) -> tuple[str, list[str], list[list[str]], list[tuple[str, bool]], list[str]]:
725        """
726        Collect the pieces of the before/after summary.
727
728        Returns:
729            tuple: The header, the column headings, the table rows, the
730                verification lines (text and whether the check passed), and
731                additional notes
732        """
733        if self.normalization_type == "ebu":
734            header = (
735                f"EBU R128 normalization, target: {self.target_level:.1f} LUFS, "
736                f"true peak: {self.true_peak:.1f} dBTP"
737            )
738            if self.dynamic:
739                header += ", dynamic mode"
740            columns = ["Input (LUFS)", "Output (LUFS)", "True peak (dBTP)", "Gain (dB)"]
741        elif self.normalization_type == "rms":
742            header = f"RMS normalization, target: {self.target_level:.1f} dBFS"
743            columns = [
744                "Input RMS (dBFS)",
745                "Output RMS (dBFS)",
746                "Peak (dBFS)",
747                "Gain (dB)",
748            ]
749        else:
750            header = f"Peak normalization, target: {self.target_level:.1f} dBFS"
751            columns = ["Input peak (dBFS)", "Output peak (dBFS)", "Gain (dB)"]
752
753        if self.batch:
754            header += ", batch mode (relative loudness preserved)"
755        if self.dry_run:
756            header += ", dry run"
757
758        def fmt(value: float | None, signed: bool = False) -> str:
759            if value is None:
760                return "-"
761            return f"{value:+.1f}" if signed else f"{value:.1f}"
762
763        rows = self.get_summary()
764        table: list[list[str]] = []
765        for row in rows:
766            values = [fmt(row["input_level"]), fmt(row["output_level"])]
767            if self.normalization_type != "peak":
768                values.append(fmt(row["output_peak"]))
769            values.append(fmt(row["gain"], signed=True))
770            table.append(
771                [row["input_file"], str(row["stream_id"]), *values, row["status"]]
772            )
773
774        verifications: list[tuple[str, bool]] = []
775        notes: list[str] = []
776        verified = [row for row in rows if "verification" in row]
777        if verified:
778            level_unit = "LUFS" if self.normalization_type == "ebu" else "dBFS"
779            peak_unit = "dBTP" if self.normalization_type == "ebu" else "dBFS"
780            for row in verified:
781                result = row["verification"]
782                outcome = "passed" if result["passed"] else "FAILED"
783                verifications.append(
784                    (
785                        f"{row['output_file']} stream {result['output_stream_id']}: "
786                        f"level {fmt(result['output_level'])} {level_unit}, "
787                        f"peak {fmt(result['output_peak'])} {peak_unit}, {outcome}",
788                        result["passed"],
789                    )
790                )
791        elif self.verify and self.dry_run:
792            notes.append("Encoded-output verification skipped: dry run.")
793
794        return (
795            header,
796            ["File", "Stream", *columns, "Status"],
797            table,
798            verifications,
799            notes,
800        )
801
802    _SUMMARY_FOOTNOTE = (
803        "Output values above: loudnorm filter statistics for EBU; "
804        "calculated from applied gain for RMS/peak; input levels for skipped files."
805    )
806
807    def format_summary(self) -> str:
808        """
809        Return the before/after summary as a human-readable table.
810
811        Returns:
812            str: The formatted table, including a header line with the target
813        """
814        header, headings, table, verifications, notes = self._summary_parts()
815        if not table:
816            return f"Summary ({header}): no files processed"
817
818        widths = [
819            max(len(headings[i]), *(len(line[i]) for line in table))
820            for i in range(len(headings))
821        ]
822
823        def fmt_line(cells: list[str]) -> str:
824            # Left-align the file name and status, right-align everything else
825            parts = [
826                cell.ljust(widths[i])
827                if i in (0, len(cells) - 1)
828                else cell.rjust(widths[i])
829                for i, cell in enumerate(cells)
830            ]
831            return "  ".join(parts).rstrip()
832
833        lines = [f"Summary ({header}):", "", fmt_line(headings)]
834        lines.append(fmt_line(["-" * w for w in widths]))
835        lines.extend(fmt_line(line) for line in table)
836        lines.append("\n" + self._SUMMARY_FOOTNOTE)
837        if verifications:
838            lines.append("\nEncoded-output verification (measured after encoding):")
839            lines.extend(text for text, _ in verifications)
840        for note in notes:
841            lines.append("\n" + note)
842        return "\n".join(lines)
843
844    def summary_renderable(self) -> RenderableType:
845        """
846        Return the before/after summary as a rich renderable for terminals.
847
848        Returns:
849            RenderableType: A table with the same content as `format_summary()`
850        """
851        header, headings, table, verifications, notes = self._summary_parts()
852        if not table:
853            return Text(f"Summary ({header}): no files processed")
854
855        status_styles = {"normalized": "status.ok", "skipped": "status.skipped"}
856        summary = Table(
857            title=f"Summary ({header})",
858            title_justify="left",
859            title_style="bold",
860            caption=self._SUMMARY_FOOTNOTE,
861            caption_justify="left",
862            caption_style="dim",
863            header_style="bold",
864            box=box.SIMPLE_HEAD,
865        )
866        last = len(headings) - 1
867        for i, heading in enumerate(headings):
868            summary.add_column(
869                heading,
870                justify="left" if i in (0, last) else "right",
871                overflow="fold",
872                no_wrap=i != 0,
873            )
874        for line in table:
875            status = line[-1]
876            summary.add_row(
877                *line[:-1],
878                Text(status, style=status_styles.get(status, "status.error")),
879            )
880
881        parts: list[RenderableType] = [summary]
882        if verifications:
883            parts.append(
884                Text(
885                    "Encoded-output verification (measured after encoding):",
886                    style="bold",
887                )
888            )
889            for text, passed in verifications:
890                parts.append(
891                    Text(
892                        f"  {'✔' if passed else '✘'} {text}",
893                        style="status.ok" if passed else "status.error",
894                    )
895                )
896        parts.extend(Text(note, style="dim") for note in notes)
897        return Group(*parts)

ffmpeg-normalize class.

Arguments:
  • normalization_type (str, optional): Normalization type. Defaults to "ebu".
  • target_level (float, optional): Target level. Defaults to -23.0.
  • print_stats (bool, optional): Print loudnorm stats. Defaults to False.
  • print_summary (bool, optional): Print a before/after summary table to stderr after processing. Defaults to False.
  • threshold (float, optional): When set to a positive value, skip normalization when the input is already within this many dB/LU of the target level, copying it through unchanged. Defaults to 0 (disabled, always normalize).
  • loudness_range_target (float, optional): Loudness range target. Defaults to 7.0.
  • keep_loudness_range_target (bool, optional): Keep loudness range target. Defaults to False.
  • keep_lra_above_loudness_range_target (bool, optional): Keep input loudness range above loudness range target. Defaults to False.
  • true_peak (float, optional): True peak. Defaults to -2.0.
  • offset (float, optional): Offset. Defaults to 0.0.
  • lower_only (bool, optional): Whether the audio should not increase in loudness. Defaults to False.
  • auto_lower_loudness_target (bool, optional): Automatically lower EBU Integrated Loudness Target.
  • dual_mono (bool, optional): Dual mono. Defaults to False.
  • dynamic (bool, optional): Use dynamic EBU R128 normalization. This is a one-pass algorithm and skips the initial media scan. Defaults to False.
  • audio_codec (str, optional): Audio codec. Defaults to "pcm_s16le".
  • audio_bitrate (float, optional): Audio bitrate. Defaults to None.
  • sample_rate (int, optional): Sample rate. Defaults to None.
  • audio_channels (int | None, optional): Audio channels. Defaults to None.
  • keep_original_audio (bool, optional): Keep original audio. Defaults to False.
  • pre_filter (str, optional): Pre filter. Defaults to None.
  • post_filter (str, optional): Post filter. Defaults to None.
  • video_codec (str, optional): Video codec. Defaults to "copy".
  • video_disable (bool, optional): Disable video. Defaults to False.
  • subtitle_disable (bool, optional): Disable subtitles. Defaults to False.
  • metadata_disable (bool, optional): Disable metadata. Defaults to False.
  • chapters_disable (bool, optional): Disable chapters. Defaults to False.
  • write_encoder_settings (bool, optional): Write the effective encoder settings (codec, bitrate, sample rate, channels and the normalization filter including the measured loudnorm values) as an ENCODER_SETTINGS tag on each normalized audio stream. Defaults to False.
  • extra_input_options (list, optional): Extra input options. Defaults to None.
  • extra_output_options (list, optional): Extra output options. Defaults to None.
  • output_format (str, optional): Output format. Defaults to None.
  • extension (str, optional): Output file extension to use for output files that were not explicitly specified. Defaults to "mkv".
  • dry_run (bool, optional): Dry run. Defaults to False.
  • debug (bool, optional): Debug. Defaults to False.
  • progress (bool, optional): Progress. Defaults to False.
  • replaygain (bool, optional): Write ReplayGain tags without normalizing. Defaults to False.
  • batch (bool, optional): Preserve relative loudness between files (album mode). Defaults to False.
  • audio_streams (list[int] | None, optional): List of audio stream indices to normalize. Defaults to None (all streams).
  • audio_default_only (bool, optional): Only normalize audio streams with default disposition. Defaults to False.
  • keep_other_audio (bool, optional): Keep non-selected audio streams in output (copy without normalization). Defaults to False.
  • keep_mtime (bool, optional): Copy the input file's modification time to the output file. Defaults to False.
  • keep_bit_depth (bool, optional): Carry the detected input bit depth through to the output encoder. Defaults to True.
  • verify (bool, optional): Measure the encoded output and check its effective target and peak ceiling. Defaults to False. Not available with ReplayGain; skipped during dry runs.
  • verify_loudness_tolerance (float, optional): Allowed level deviation in dB/LU. Defaults to 0.5.
  • verify_peak_tolerance (float, optional): Allowed peak overshoot in dB. Defaults to 0.1.
Raises:
  • FFmpegNormalizeError: If the ffmpeg executable is not found or does not support the loudnorm filter.
FFmpegNormalize( normalization_type: Literal['ebu', 'rms', 'peak'] = 'ebu', target_level: float = -23.0, print_stats: bool = False, print_summary: bool = False, threshold: float = 0.0, loudness_range_target: float = 7.0, keep_loudness_range_target: bool = False, keep_lra_above_loudness_range_target: bool = False, true_peak: float = -2.0, offset: float = 0.0, lower_only: bool = False, auto_lower_loudness_target: bool = False, dual_mono: bool = False, dynamic: bool = False, audio_codec: str = 'pcm_s16le', audio_bitrate: float | None = None, sample_rate: float | int | None = None, audio_channels: int | None = None, keep_original_audio: bool = False, pre_filter: str | None = None, post_filter: str | None = None, video_codec: str = 'copy', video_disable: bool = False, subtitle_disable: bool = False, metadata_disable: bool = False, chapters_disable: bool = False, write_encoder_settings: bool = False, extra_input_options: list[str] | None = None, extra_output_options: list[str] | None = None, output_format: str | None = None, extension: str = 'mkv', dry_run: bool = False, debug: bool = False, progress: bool = False, replaygain: bool = False, batch: bool = False, audio_streams: list[int] | None = None, audio_default_only: bool = False, keep_other_audio: bool = False, keep_mtime: bool = False, keep_bit_depth: bool = True, verify: bool = False, verify_loudness_tolerance: float = 0.5, verify_peak_tolerance: float = 0.1)
166    def __init__(
167        self,
168        normalization_type: Literal["ebu", "rms", "peak"] = "ebu",
169        target_level: float = -23.0,
170        print_stats: bool = False,
171        print_summary: bool = False,
172        threshold: float = 0.0,
173        loudness_range_target: float = 7.0,
174        keep_loudness_range_target: bool = False,
175        keep_lra_above_loudness_range_target: bool = False,
176        true_peak: float = -2.0,
177        offset: float = 0.0,
178        lower_only: bool = False,
179        auto_lower_loudness_target: bool = False,
180        dual_mono: bool = False,
181        dynamic: bool = False,
182        audio_codec: str = "pcm_s16le",
183        audio_bitrate: float | None = None,
184        sample_rate: float | int | None = None,
185        audio_channels: int | None = None,
186        keep_original_audio: bool = False,
187        pre_filter: str | None = None,
188        post_filter: str | None = None,
189        video_codec: str = "copy",
190        video_disable: bool = False,
191        subtitle_disable: bool = False,
192        metadata_disable: bool = False,
193        chapters_disable: bool = False,
194        write_encoder_settings: bool = False,
195        extra_input_options: list[str] | None = None,
196        extra_output_options: list[str] | None = None,
197        output_format: str | None = None,
198        extension: str = "mkv",
199        dry_run: bool = False,
200        debug: bool = False,
201        progress: bool = False,
202        replaygain: bool = False,
203        batch: bool = False,
204        audio_streams: list[int] | None = None,
205        audio_default_only: bool = False,
206        keep_other_audio: bool = False,
207        keep_mtime: bool = False,
208        keep_bit_depth: bool = True,
209        verify: bool = False,
210        verify_loudness_tolerance: float = 0.5,
211        verify_peak_tolerance: float = 0.1,
212    ):
213        self.ffmpeg_exe = get_ffmpeg_exe()
214        self.has_loudnorm_capabilities = ffmpeg_has_loudnorm()
215
216        if normalization_type not in NORMALIZATION_TYPES:
217            raise FFmpegNormalizeError(
218                "Normalization type must be: 'ebu', 'rms', or 'peak'"
219            )
220        self.normalization_type = normalization_type
221
222        if not self.has_loudnorm_capabilities and self.normalization_type == "ebu":
223            raise FFmpegNormalizeError(
224                "Your ffmpeg does not support the 'loudnorm' EBU R128 filter. "
225                "Please install ffmpeg v4.2 or above, or choose another normalization type."
226            )
227
228        if self.normalization_type == "ebu":
229            self.target_level = check_range(target_level, -70, -5, name="target_level")
230        else:
231            self.target_level = check_range(target_level, -99, 0, name="target_level")
232
233        self.print_stats = print_stats
234        self.print_summary = print_summary
235
236        self.threshold = check_range(threshold, 0, 99, name="threshold")
237
238        self.loudness_range_target = check_range(
239            loudness_range_target, 1, 50, name="loudness_range_target"
240        )
241
242        self.keep_loudness_range_target = keep_loudness_range_target
243
244        if self.keep_loudness_range_target and loudness_range_target != 7.0:
245            _logger.warning(
246                "Setting --keep-loudness-range-target will override your set loudness range target value! "
247                "Remove --keep-loudness-range-target or remove the --lrt/--loudness-range-target option."
248            )
249
250        self.keep_lra_above_loudness_range_target = keep_lra_above_loudness_range_target
251
252        if (
253            self.keep_loudness_range_target
254            and self.keep_lra_above_loudness_range_target
255        ):
256            raise FFmpegNormalizeError(
257                "Options --keep-loudness-range-target and --keep-lra-above-loudness-range-target are mutually exclusive! "
258                "Please choose just one of the two options."
259            )
260
261        self.true_peak = check_range(true_peak, -9, 0, name="true_peak")
262        self.offset = check_range(offset, -99, 99, name="offset")
263        self.lower_only = lower_only
264        self.auto_lower_loudness_target = auto_lower_loudness_target
265
266        # Ensure library user is passing correct types
267        assert isinstance(dual_mono, bool), "dual_mono must be bool"
268        assert isinstance(dynamic, bool), "dynamic must be bool"
269
270        self.dual_mono = dual_mono
271        self.dynamic = dynamic
272        self.sample_rate = None if sample_rate is None else int(sample_rate)
273        self.audio_channels = None if audio_channels is None else int(audio_channels)
274
275        self.audio_codec = audio_codec
276        self.audio_bitrate = audio_bitrate
277        self.keep_original_audio = keep_original_audio
278        self.video_codec = video_codec
279        self.video_disable = video_disable
280        self.subtitle_disable = subtitle_disable
281        self.metadata_disable = metadata_disable
282        self.chapters_disable = chapters_disable
283        self.write_encoder_settings = write_encoder_settings
284
285        if self.write_encoder_settings and self.metadata_disable:
286            _logger.warning(
287                "write_encoder_settings has no effect together with metadata_disable; "
288                "no metadata will be written to the output."
289            )
290
291        self.extra_input_options = extra_input_options
292        self.extra_output_options = extra_output_options
293        self.pre_filter = pre_filter
294        self.post_filter = post_filter
295
296        self.output_format = output_format
297        self.extension = extension
298        self.dry_run = dry_run
299        self.debug = debug
300        self.progress = progress
301        self.progress_display = ProgressDisplay(enabled=False)
302        self.replaygain = replaygain
303        self.batch = batch
304
305        # Stream selection options
306        self.audio_streams = audio_streams
307        self.audio_default_only = audio_default_only
308        self.keep_other_audio = keep_other_audio
309
310        self.keep_mtime = keep_mtime
311        self.keep_bit_depth = keep_bit_depth
312        self.verify = verify
313        self.verify_loudness_tolerance = check_range(
314            verify_loudness_tolerance, 0, 99, name="verify_loudness_tolerance"
315        )
316        self.verify_peak_tolerance = check_range(
317            verify_peak_tolerance, 0, 99, name="verify_peak_tolerance"
318        )
319        if not all(
320            math.isfinite(value)
321            for value in (self.verify_loudness_tolerance, self.verify_peak_tolerance)
322        ):
323            raise FFmpegNormalizeError("Verification tolerances must be finite")
324        if verify and replaygain:
325            raise FFmpegNormalizeError("--verify cannot be combined with --replaygain")
326
327        if self.output_format in PCM_INCOMPATIBLE_FORMATS:
328            if self.audio_codec is not None and "pcm" in self.audio_codec:
329                raise FFmpegNormalizeError(
330                    f"Output format {self.output_format} does not support PCM audio. "
331                    "Please choose a suitable audio codec with the -c:a option."
332                )
333            if (
334                self.audio_codec is None
335                and get_muxer_default_audio_encoder(self.output_format) is None
336            ):
337                raise FFmpegNormalizeError(
338                    f"Output format {self.output_format} does not support PCM audio, "
339                    "and a default audio codec could not be determined. Please choose "
340                    "a suitable audio codec with the -c:a option."
341                )
342
343        # replaygain only works for EBU for now
344        if self.replaygain and self.normalization_type != "ebu":
345            raise FFmpegNormalizeError(
346                "ReplayGain only works for EBU normalization type for now."
347            )
348
349        # Validate stream selection options
350        if self.audio_streams is not None and self.audio_default_only:
351            raise FFmpegNormalizeError(
352                "Cannot use both audio_streams and audio_default_only together."
353            )
354
355        if self.keep_other_audio and self.keep_original_audio:
356            raise FFmpegNormalizeError(
357                "Cannot use both --keep-other-audio and --keep-original-audio together. "
358                "Use --keep-original-audio to keep all original streams alongside normalized ones, "
359                "or --keep-other-audio to keep only non-selected streams as passthrough."
360            )
361
362        self.stats: list[LoudnessStatisticsWithMetadata] = []
363        self.media_files: list[MediaFile] = []
364        self.file_count = 0
DEFAULTS = {'normalization_type': 'ebu', 'target_level': -23.0, 'print_stats': False, 'print_summary': False, 'threshold': 0.0, 'loudness_range_target': 7.0, 'keep_loudness_range_target': False, 'keep_lra_above_loudness_range_target': False, 'true_peak': -2.0, 'offset': 0.0, 'lower_only': False, 'auto_lower_loudness_target': False, 'dual_mono': False, 'dynamic': False, 'audio_codec': 'pcm_s16le', 'audio_bitrate': None, 'sample_rate': None, 'audio_channels': None, 'keep_original_audio': False, 'pre_filter': None, 'post_filter': None, 'video_codec': 'copy', 'video_disable': False, 'subtitle_disable': False, 'metadata_disable': False, 'chapters_disable': False, 'write_encoder_settings': False, 'extra_input_options': None, 'extra_output_options': None, 'output_format': None, 'output_folder': 'normalized', 'extension': 'mkv', 'dry_run': False, 'debug': False, 'progress': False, 'replaygain': False, 'batch': False, 'audio_streams': None, 'audio_default_only': False, 'keep_other_audio': False, 'keep_mtime': False, 'keep_bit_depth': True, 'verify': False, 'verify_loudness_tolerance': 0.5, 'verify_peak_tolerance': 0.1}
ffmpeg_exe
has_loudnorm_capabilities
normalization_type
print_stats
print_summary
threshold
loudness_range_target
keep_loudness_range_target
keep_lra_above_loudness_range_target
true_peak
offset
lower_only
auto_lower_loudness_target
dual_mono
dynamic
sample_rate
audio_channels
audio_codec
audio_bitrate
keep_original_audio
video_codec
video_disable
subtitle_disable
metadata_disable
chapters_disable
write_encoder_settings
extra_input_options
extra_output_options
pre_filter
post_filter
output_format
extension
dry_run
debug
progress
progress_display
replaygain
batch
audio_streams
audio_default_only
keep_other_audio
keep_mtime
keep_bit_depth
verify
verify_loudness_tolerance
verify_peak_tolerance
stats: list[ffmpeg_normalize._streams.LoudnessStatisticsWithMetadata]
media_files: list[MediaFile]
file_count
def add_media_file(self, input_file: str, output_file: str) -> None:
366    def add_media_file(self, input_file: str, output_file: str) -> None:
367        """
368        Add a media file to normalize
369
370        Args:
371            input_file (str): Path to input file
372            output_file (str): Path to output file
373        """
374        if not os.path.exists(input_file):
375            raise FFmpegNormalizeError(f"file {input_file} does not exist")
376
377        ext = os.path.splitext(output_file)[1][1:].lower()
378        if ext in PCM_INCOMPATIBLE_EXTS:
379            if self.audio_codec is not None and "pcm" in self.audio_codec:
380                raise FFmpegNormalizeError(
381                    f"Output extension {ext} does not support PCM audio. "
382                    "Please choose a suitable audio codec with the -c:a option."
383                )
384            if (
385                self.audio_codec is None
386                and get_muxer_default_audio_encoder(ext) is None
387            ):
388                raise FFmpegNormalizeError(
389                    f"Output extension {ext} does not support PCM audio, and a "
390                    "default audio codec could not be determined. Please choose a "
391                    "suitable audio codec with the -c:a option."
392                )
393
394        self.media_files.append(MediaFile(self, input_file, output_file))
395        self.file_count += 1

Add a media file to normalize

Arguments:
  • input_file (str): Path to input file
  • output_file (str): Path to output file
@staticmethod
def validate_input_files(input_files: list[str]) -> list[str]:
397    @staticmethod
398    def validate_input_files(input_files: list[str]) -> list[str]:
399        """
400        Validate all input files before processing.
401
402        This method checks that each input file exists, is readable, and contains
403        at least one audio stream. All files are validated upfront so that users
404        can fix all issues before rerunning the batch.
405
406        Args:
407            input_files: List of input file paths to validate
408
409        Returns:
410            list: List of error messages for invalid files. Empty if all files are valid.
411        """
412        errors = []
413        for input_file in input_files:
414            is_valid, error_msg = validate_input_file(input_file)
415            if not is_valid and error_msg:
416                errors.append(error_msg)
417        return errors

Validate all input files before processing.

This method checks that each input file exists, is readable, and contains at least one audio stream. All files are validated upfront so that users can fix all issues before rerunning the batch.

Arguments:
  • input_files: List of input file paths to validate
Returns:

list: List of error messages for invalid files. Empty if all files are valid.

@staticmethod
def validate_output_files(input_files: list[str], output_files: list[str]) -> None:
419    @staticmethod
420    def validate_output_files(input_files: list[str], output_files: list[str]) -> None:
421        """Reject duplicate destinations and outputs that overwrite another input.
422
423        Resolve symlinks and existing hard links, while allowing each file to be
424        normalized in place and multiple outputs to the null device.
425        """
426
427        def path_keys(path: str) -> list[str | tuple[int, int]]:
428            keys: list[str | tuple[int, int]] = [
429                os.path.normcase(os.path.realpath(path))
430            ]
431            if os.path.exists(path):
432                stat = os.stat(path)
433                keys.append((stat.st_dev, stat.st_ino))
434            return keys
435
436        input_owners: dict[str | tuple[int, int], set[int]] = {}
437        for index, path in enumerate(input_files):
438            for key in path_keys(path):
439                input_owners.setdefault(key, set()).add(index)
440
441        output_owners: dict[str | tuple[int, int], str] = {}
442        for index, path in enumerate(output_files):
443            if os.path.realpath(path) == os.path.realpath(os.devnull):
444                continue
445            for key in path_keys(path):
446                if key in output_owners:
447                    raise FFmpegNormalizeError(
448                        f"Output collision: '{path}' and '{output_owners[key]}' "
449                        "refer to the same destination. Specify distinct output paths."
450                    )
451                if input_owners.get(key, set()) - {index}:
452                    raise FFmpegNormalizeError(
453                        f"Output '{path}' would overwrite another input file. "
454                        "Specify a different output path."
455                    )
456                output_owners[key] = path

Reject duplicate destinations and outputs that overwrite another input.

Resolve symlinks and existing hard links, while allowing each file to be normalized in place and multiple outputs to the null device.

def run_normalization(self) -> None:
548    def run_normalization(self) -> None:
549        """
550        Run the normalization procedures.
551
552        In batch mode, all files are analyzed first (first pass), then a batch reference
553        loudness is calculated, and finally all files are normalized (second pass) with
554        adjustments relative to the batch reference to preserve relative loudness.
555
556        In non-batch mode, each file is processed completely (both passes) before
557        moving to the next file.
558        """
559        if (
560            self.verify
561            and not self.dry_run
562            and any(
563                os.path.realpath(file.output_file) == os.path.realpath(os.devnull)
564                for file in self.media_files
565            )
566        ):
567            raise FFmpegNormalizeError(
568                "--verify requires an output file, not the null device"
569            )
570        if not self.replaygain:
571            self.validate_output_files(
572                [media_file.input_file for media_file in self.media_files],
573                [media_file.output_file for media_file in self.media_files],
574            )
575        with ProgressDisplay(enabled=self.progress) as display:
576            self.progress_display = display
577            try:
578                self._process_media_files()
579            finally:
580                self.progress_display = ProgressDisplay(enabled=False)
581
582        if self.print_stats:
583            json.dump(
584                list(
585                    chain.from_iterable(
586                        media_file.get_stats() for media_file in self.media_files
587                    )
588                ),
589                sys.stdout,
590                indent=4,
591            )
592            print()
593
594        if self.print_summary:
595            console = get_console()
596            if console.is_terminal:
597                console.print(self.summary_renderable())
598            else:
599                print(self.format_summary(), file=sys.stderr)

Run the normalization procedures.

In batch mode, all files are analyzed first (first pass), then a batch reference loudness is calculated, and finally all files are normalized (second pass) with adjustments relative to the batch reference to preserve relative loudness.

In non-batch mode, each file is processed completely (both passes) before moving to the next file.

def get_summary(self) -> list[ffmpeg_normalize._streams.SummaryRow]:
703    def get_summary(self) -> list[SummaryRow]:
704        """
705        Return the before/after summary for all audio streams of all files.
706
707        Each entry contains the input level, output level, output peak and the
708        applied gain in dB. The level is the integrated loudness for EBU, the
709        RMS level for RMS, and the peak level for peak normalization. The
710        output peak is the true peak for EBU and the sample peak otherwise.
711        Values that are not available are None.
712
713        Returns:
714            list[SummaryRow]: One summary entry per audio stream
715        """
716        return list(
717            chain.from_iterable(
718                media_file.get_summary() for media_file in self.media_files
719            )
720        )

Return the before/after summary for all audio streams of all files.

Each entry contains the input level, output level, output peak and the applied gain in dB. The level is the integrated loudness for EBU, the RMS level for RMS, and the peak level for peak normalization. The output peak is the true peak for EBU and the sample peak otherwise. Values that are not available are None.

Returns:

list[SummaryRow]: One summary entry per audio stream

def format_summary(self) -> str:
807    def format_summary(self) -> str:
808        """
809        Return the before/after summary as a human-readable table.
810
811        Returns:
812            str: The formatted table, including a header line with the target
813        """
814        header, headings, table, verifications, notes = self._summary_parts()
815        if not table:
816            return f"Summary ({header}): no files processed"
817
818        widths = [
819            max(len(headings[i]), *(len(line[i]) for line in table))
820            for i in range(len(headings))
821        ]
822
823        def fmt_line(cells: list[str]) -> str:
824            # Left-align the file name and status, right-align everything else
825            parts = [
826                cell.ljust(widths[i])
827                if i in (0, len(cells) - 1)
828                else cell.rjust(widths[i])
829                for i, cell in enumerate(cells)
830            ]
831            return "  ".join(parts).rstrip()
832
833        lines = [f"Summary ({header}):", "", fmt_line(headings)]
834        lines.append(fmt_line(["-" * w for w in widths]))
835        lines.extend(fmt_line(line) for line in table)
836        lines.append("\n" + self._SUMMARY_FOOTNOTE)
837        if verifications:
838            lines.append("\nEncoded-output verification (measured after encoding):")
839            lines.extend(text for text, _ in verifications)
840        for note in notes:
841            lines.append("\n" + note)
842        return "\n".join(lines)

Return the before/after summary as a human-readable table.

Returns:

str: The formatted table, including a header line with the target

def summary_renderable(self) -> rich.console.ConsoleRenderable | rich.console.RichCast | str:
844    def summary_renderable(self) -> RenderableType:
845        """
846        Return the before/after summary as a rich renderable for terminals.
847
848        Returns:
849            RenderableType: A table with the same content as `format_summary()`
850        """
851        header, headings, table, verifications, notes = self._summary_parts()
852        if not table:
853            return Text(f"Summary ({header}): no files processed")
854
855        status_styles = {"normalized": "status.ok", "skipped": "status.skipped"}
856        summary = Table(
857            title=f"Summary ({header})",
858            title_justify="left",
859            title_style="bold",
860            caption=self._SUMMARY_FOOTNOTE,
861            caption_justify="left",
862            caption_style="dim",
863            header_style="bold",
864            box=box.SIMPLE_HEAD,
865        )
866        last = len(headings) - 1
867        for i, heading in enumerate(headings):
868            summary.add_column(
869                heading,
870                justify="left" if i in (0, last) else "right",
871                overflow="fold",
872                no_wrap=i != 0,
873            )
874        for line in table:
875            status = line[-1]
876            summary.add_row(
877                *line[:-1],
878                Text(status, style=status_styles.get(status, "status.error")),
879            )
880
881        parts: list[RenderableType] = [summary]
882        if verifications:
883            parts.append(
884                Text(
885                    "Encoded-output verification (measured after encoding):",
886                    style="bold",
887                )
888            )
889            for text, passed in verifications:
890                parts.append(
891                    Text(
892                        f"  {'✔' if passed else '✘'} {text}",
893                        style="status.ok" if passed else "status.error",
894                    )
895                )
896        parts.extend(Text(note, style="dim") for note in notes)
897        return Group(*parts)

Return the before/after summary as a rich renderable for terminals.

Returns:

RenderableType: A table with the same content as format_summary()

class FFmpegNormalizeError(builtins.Exception):
2class FFmpegNormalizeError(Exception):
3    pass

Common base class for all non-exit exceptions.

class MediaFile:
  63class MediaFile:
  64    """
  65    Class that holds a file, its streams and adjustments
  66    """
  67
  68    def __init__(
  69        self, ffmpeg_normalize: FFmpegNormalize, input_file: str, output_file: str
  70    ):
  71        """
  72        Initialize a media file for later normalization by parsing the streams.
  73
  74        Args:
  75            ffmpeg_normalize (FFmpegNormalize): reference to overall settings
  76            input_file (str): Path to input file
  77            output_file (str): Path to output file
  78        """
  79        self.ffmpeg_normalize = ffmpeg_normalize
  80        self.skip = False
  81        # Per-file outcome, reported in the --print-stats output: "normalized"
  82        # (default), "skipped" (already within threshold of target), or "error".
  83        # "error" is set by FFmpegNormalize.run_normalization when processing
  84        # fails; on failure, self.error holds the error message.
  85        self.status: str = "normalized"
  86        self.error: str | None = None
  87        self.input_file = input_file
  88        self.output_file = output_file
  89        current_ext = os.path.splitext(output_file)[1][1:]
  90        # we need to check if it's empty, e.g. /dev/null or NUL
  91        if current_ext == "" or self.output_file == os.devnull:
  92            _logger.debug(
  93                f"Current extension is unset, or output file is a null device, using extension: {self.ffmpeg_normalize.extension}"
  94            )
  95            self.output_ext = self.ffmpeg_normalize.extension
  96        else:
  97            _logger.debug(
  98                f"Current extension is set from output file, using extension: {current_ext}"
  99            )
 100            self.output_ext = current_ext
 101        self.streams: StreamDict = {"audio": {}, "video": {}, "subtitle": {}}
 102        self.temp_file: Union[str, None] = None
 103        self.batch_reference: float | None = None
 104        # Second-pass filter chain per normalized audio stream, keyed by stream
 105        # id. Populated by _get_audio_filter_cmd() and reused by
 106        # _get_encoder_settings() so the normalization filter is not built twice.
 107        self._stream_filter_chains: dict[int, list[str]] = {}
 108        # Input (access, modification) times captured before processing, used
 109        # when the keep_mtime option is enabled.
 110        self.input_timestamps: tuple[float, float] | None = None
 111
 112        self.parse_streams()
 113
 114    def _stream_ids(self) -> list[int]:
 115        """
 116        Get all stream IDs of this file.
 117
 118        Returns:
 119            list: List of stream IDs
 120        """
 121        return (
 122            list(self.streams["audio"].keys())
 123            + list(self.streams["video"].keys())
 124            + list(self.streams["subtitle"].keys())
 125        )
 126
 127    def __repr__(self) -> str:
 128        return os.path.basename(self.input_file)
 129
 130    def parse_streams(self) -> None:
 131        """
 132        Try to parse all input streams from file and set them in self.streams.
 133
 134        Raises:
 135            FFmpegNormalizeError: If no audio streams are found
 136        """
 137        _logger.debug(f"Parsing streams of {self.input_file}")
 138
 139        cmd = [
 140            self.ffmpeg_normalize.ffmpeg_exe,
 141            "-i",
 142            self.input_file,
 143            "-c",
 144            "copy",
 145            "-t",
 146            "0",
 147            "-map",
 148            "0",
 149            "-f",
 150            "null",
 151            os.devnull,
 152        ]
 153
 154        output = CommandRunner().run_command(cmd).get_output()
 155
 156        _logger.debug("Stream parsing command output:")
 157        _logger.debug(output)
 158
 159        output_lines = [line.strip() for line in output.split("\n")]
 160
 161        # First pass: parse disposition flags for each stream
 162        stream_dispositions: dict[int, bool] = {}
 163
 164        for line in output_lines:
 165            if line.startswith("Stream"):
 166                if stream_id_match := re.search(r"#0:([\d]+)", line):
 167                    stream_id = int(stream_id_match.group(1))
 168                    # Check if (default) appears on the Stream line
 169                    is_default = "(default)" in line
 170                    stream_dispositions[stream_id] = is_default
 171
 172        # Second pass: parse stream information
 173        duration = None
 174        for line in output_lines:
 175            if "Duration" in line:
 176                if duration_search := DUR_REGEX.search(line):
 177                    duration = _to_ms(**duration_search.groupdict()) / 1000
 178                    _logger.debug(f"Found duration: {duration} s")
 179                else:
 180                    _logger.warning("Could not extract duration from input file!")
 181
 182            if not line.startswith("Stream"):
 183                continue
 184
 185            if stream_id_match := re.search(r"#0:([\d]+)", line):
 186                stream_id = int(stream_id_match.group(1))
 187                if stream_id in self._stream_ids():
 188                    continue
 189            else:
 190                continue
 191
 192            is_default = stream_dispositions.get(stream_id, False)
 193
 194            if "Audio" in line:
 195                _logger.debug(
 196                    f"Found audio stream at index {stream_id} (default: {is_default})"
 197                )
 198                sample_rate_match = re.search(r"(\d+) Hz", line)
 199                sample_rate = (
 200                    int(sample_rate_match.group(1)) if sample_rate_match else None
 201                )
 202                bit_depth_match = re.search(r"([sfu])(\d+)(p|le|be)?", line)
 203                bit_depth = int(bit_depth_match.group(2)) if bit_depth_match else None
 204                is_float = bit_depth_match.group(1) == "f" if bit_depth_match else False
 205                self.streams["audio"][stream_id] = AudioStream(
 206                    self.ffmpeg_normalize,
 207                    self,
 208                    stream_id,
 209                    sample_rate,
 210                    bit_depth,
 211                    duration,
 212                    is_default,
 213                    is_float,
 214                )
 215
 216            elif "Video" in line:
 217                _logger.debug(f"Found video stream at index {stream_id}")
 218                self.streams["video"][stream_id] = VideoStream(
 219                    self.ffmpeg_normalize, self, stream_id
 220                )
 221
 222            elif "Subtitle" in line:
 223                _logger.debug(f"Found subtitle stream at index {stream_id}")
 224                self.streams["subtitle"][stream_id] = SubtitleStream(
 225                    self.ffmpeg_normalize, self, stream_id
 226                )
 227
 228        if not self.streams["audio"]:
 229            raise FFmpegNormalizeError(
 230                f"Input file {self.input_file} does not contain any audio streams"
 231            )
 232
 233        if (
 234            self.output_ext.lower() in ONE_STREAM
 235            and len(self.streams["audio"].values()) > 1
 236        ):
 237            _logger.warning(
 238                "Output file only supports one stream. Keeping only first audio stream."
 239            )
 240            first_stream = list(self.streams["audio"].values())[0]
 241            self.streams["audio"] = {first_stream.stream_id: first_stream}
 242            self.streams["video"] = {}
 243            self.streams["subtitle"] = {}
 244
 245    def _get_streams_to_normalize(self) -> list[AudioStream]:
 246        """
 247        Determine which audio streams to normalize based on configuration.
 248
 249        Returns:
 250            list[AudioStream]: List of audio streams to normalize
 251        """
 252        all_audio_streams = list(self.streams["audio"].values())
 253
 254        if self.ffmpeg_normalize.audio_streams is not None:
 255            # User specified specific stream indices
 256            selected_streams = [
 257                stream
 258                for stream in all_audio_streams
 259                if stream.stream_id in self.ffmpeg_normalize.audio_streams
 260            ]
 261            if not selected_streams:
 262                _logger.warning(
 263                    f"No audio streams found matching indices {self.ffmpeg_normalize.audio_streams}. "
 264                    f"Available streams: {[s.stream_id for s in all_audio_streams]}"
 265                )
 266            else:
 267                _logger.info(
 268                    f"Normalizing selected audio streams: {[s.stream_id for s in selected_streams]}"
 269                )
 270            return selected_streams
 271
 272        elif self.ffmpeg_normalize.audio_default_only:
 273            # Only normalize streams with default disposition
 274            default_streams = [
 275                stream for stream in all_audio_streams if stream.is_default
 276            ]
 277            if not default_streams:
 278                _logger.warning(
 279                    "No audio streams with 'default' disposition found. "
 280                    f"Available streams: {[s.stream_id for s in all_audio_streams]}"
 281                )
 282            else:
 283                _logger.info(
 284                    f"Normalizing default audio streams: {[s.stream_id for s in default_streams]}"
 285                )
 286            return default_streams
 287
 288        else:
 289            # Normalize all streams (default behavior)
 290            return all_audio_streams
 291
 292    def run_normalization(self, batch_reference: float | None = None) -> None:
 293        """
 294        Run the normalization process for this file.
 295
 296        Args:
 297            batch_reference (float | None, optional): Reference loudness for batch mode.
 298                If provided, the first pass is skipped (assumed already done) and this
 299                reference is used to calculate relative adjustments. Defaults to None.
 300        """
 301        _logger.debug(f"Running normalization for {self.input_file}")
 302
 303        # Store batch reference for use in second pass
 304        self.batch_reference = batch_reference
 305
 306        # Capture the input file's timestamps before processing, since an
 307        # in-place overwrite would otherwise lose the original modification time.
 308        if self.ffmpeg_normalize.keep_mtime:
 309            try:
 310                stat = os.stat(self.input_file)
 311                self.input_timestamps = (stat.st_atime, stat.st_mtime)
 312            except OSError as e:
 313                _logger.warning(
 314                    f"Could not read timestamps from {self.input_file}: {e}"
 315                )
 316
 317        # run the first pass to get loudness stats, unless in dynamic EBU mode or batch mode
 318        # (in batch mode, first pass is already done in FFmpegNormalize.run_normalization)
 319        if batch_reference is None:
 320            if not (
 321                self.ffmpeg_normalize.dynamic
 322                and self.ffmpeg_normalize.normalization_type == "ebu"
 323            ):
 324                self._first_pass()
 325            else:
 326                _logger.debug(
 327                    "Dynamic EBU mode: First pass will not run, as it is not needed."
 328                )
 329        else:
 330            _logger.debug(
 331                f"Batch mode: Skipping first pass (already completed), using batch reference = {batch_reference:.2f}"
 332            )
 333
 334        # If the file is already within the configured threshold of the target
 335        # level, skip normalization entirely and copy the input through to the
 336        # output unchanged. This avoids needless re-encoding of files that are
 337        # already at the target level.
 338        if self._is_within_threshold():
 339            self._handle_skip()
 340            return
 341
 342        temp_dir = None
 343
 344        if self.ffmpeg_normalize.replaygain:
 345            _logger.debug(
 346                "ReplayGain mode: Second pass will run with temporary file to get stats."
 347            )
 348            temp_dir = mkdtemp()
 349            self.temp_file = os.path.join(temp_dir, f"out.{self.output_ext}")
 350            self.output_file = self.temp_file
 351
 352        # run the second pass as a whole.
 353        with self.ffmpeg_normalize.progress_display.task("Second pass") as update:
 354            for progress in self._second_pass():
 355                update(progress)
 356
 357        # remove temp dir; this will remove the temp file as well if it has not been renamed (e.g. for replaygain)
 358        if temp_dir and os.path.exists(temp_dir):
 359            rmtree(temp_dir, ignore_errors=True)
 360
 361        # This will use stats from ebu_pass2 if available (from the main second pass),
 362        # or fall back to ebu_pass1.
 363        if self.ffmpeg_normalize.replaygain:
 364            _logger.debug(
 365                "ReplayGain tagging is enabled. Proceeding with tag calculation/application."
 366            )
 367            self._run_replaygain()
 368        else:
 369            # Strip any existing ReplayGain tags from the output file
 370            # since they are no longer accurate after normalization
 371            self._strip_replaygain_tags(self.output_file)
 372            # Copy input timestamps last, after any tag modifications, so the
 373            # output ends up with the original modification time.
 374            if self.ffmpeg_normalize.keep_mtime and not self.ffmpeg_normalize.dry_run:
 375                self._apply_input_timestamps()
 376            _logger.info(f"Normalized file written to {self.output_file}")
 377
 378    def verify_output(self) -> None:
 379        """Verify encoded audio, restoring requested timestamps after reading it."""
 380        try:
 381            self._verify_output()
 382        finally:
 383            if self.ffmpeg_normalize.keep_mtime:
 384                self._apply_input_timestamps()
 385
 386    def _verify_output(self) -> None:
 387        """Measure encoded audio without reapplying filters or input options.
 388
 389        Only normalized streams are checked. They precede passthrough and
 390        original audio in encoded outputs; skipped files retain input indices.
 391        Verification keeps the encoded file even if a check fails.
 392        """
 393        config = copy(self.ffmpeg_normalize)
 394        config.pre_filter = config.post_filter = None
 395        config.extra_input_options = None
 396        config.audio_channels = None
 397        measured_file = MediaFile(config, self.output_file, os.devnull)
 398        selected = self._get_streams_to_normalize()
 399        output_streams = list(measured_file.streams["audio"].values())
 400        if self.status == "skipped":
 401            output_streams = [
 402                measured_file.streams["audio"][stream.stream_id] for stream in selected
 403            ]
 404        if not selected or len(output_streams) < len(selected):
 405            raise FFmpegNormalizeError(
 406                "Cannot verify output: selected audio streams are missing"
 407            )
 408
 409        failures: list[str] = []
 410        for source, measured in zip(selected, output_streams):
 411            summary = source.get_summary()
 412            expected = summary["output_level"]
 413            if config.normalization_type == "ebu":
 414                for _ in measured.parse_loudnorm_stats():
 415                    pass
 416                stats = measured.loudness_statistics["ebu_pass1"]
 417                if stats is None:
 418                    raise FFmpegNormalizeError(
 419                        "Cannot verify output: loudness measurement is missing"
 420                    )
 421                level, peak = float(stats["input_i"]), float(stats["input_tp"])
 422                if self.status != "skipped":
 423                    expected = source.verification_target_level
 424                    if expected is None:
 425                        expected = summary["input_level"]
 426                peak_limit = config.true_peak
 427            else:
 428                for _ in measured.parse_astats():
 429                    pass
 430                level = measured.loudness_statistics[
 431                    "mean" if config.normalization_type == "rms" else "max"
 432                ]
 433                peak = measured.loudness_statistics["max"]
 434                peak_limit = (
 435                    config.target_level if config.normalization_type == "peak" else 0.0
 436                )
 437
 438            if self.status == "skipped" and summary["output_peak"] is not None:
 439                peak_limit = summary["output_peak"]
 440
 441            def finite(value: float | None) -> float | None:
 442                return value if value is not None and math.isfinite(value) else None
 443
 444            level, peak, expected = finite(level), finite(peak), finite(expected)
 445            errors: list[str] = []
 446            if level is None or expected is None:
 447                errors.append("output level or expected level is not finite")
 448            elif abs(level - expected) > config.verify_loudness_tolerance:
 449                errors.append(
 450                    f"level {level:.2f} differs from expected {expected:.2f} "
 451                    f"by more than {config.verify_loudness_tolerance:g} dB/LU"
 452                )
 453            if peak is None:
 454                errors.append("output peak is not finite")
 455            elif peak > peak_limit + config.verify_peak_tolerance:
 456                errors.append(
 457                    f"peak {peak:.2f} exceeds ceiling {peak_limit:.2f} "
 458                    f"plus {config.verify_peak_tolerance:g} dB tolerance"
 459                )
 460            result: VerificationResult = {
 461                "output_stream_id": measured.stream_id,
 462                "output_level": level,
 463                "output_peak": peak,
 464                "expected_level": expected,
 465                "peak_limit": peak_limit,
 466                "loudness_tolerance": config.verify_loudness_tolerance,
 467                "peak_tolerance": config.verify_peak_tolerance,
 468                "passed": not errors,
 469                "errors": errors,
 470            }
 471            source.verification = result
 472            if errors:
 473                failures.append(f"stream {source.stream_id}: " + "; ".join(errors))
 474        if failures:
 475            raise FFmpegNormalizeError(
 476                "Encoded-output verification failed: " + "; ".join(failures)
 477            )
 478        _logger.info(f"Encoded-output verification passed for {self.output_file}")
 479
 480    def _is_within_threshold(self) -> bool:
 481        """
 482        Return whether every stream selected for normalization is already
 483        within the configured threshold of the target level, meaning the file
 484        can be copied through unchanged instead of being re-normalized.
 485
 486        The check compares the measured level against the absolute target level
 487        (integrated loudness for EBU, peak/RMS level otherwise). It is disabled
 488        when the threshold is zero or less, in batch mode (where files are
 489        adjusted relative to a shared reference rather than an absolute target),
 490        in ReplayGain mode (which only writes tags), when a pre/post filter or
 491        channel downmix is requested (since these change the audio), and when
 492        the output extension differs from the input (since the file is copied
 493        verbatim, a container change would otherwise produce an invalid file).
 494
 495        Returns:
 496            bool: True if the file should be skipped, False otherwise.
 497        """
 498        threshold = self.ffmpeg_normalize.threshold
 499        if threshold <= 0:
 500            return False
 501
 502        if self.ffmpeg_normalize.batch or self.ffmpeg_normalize.replaygain:
 503            return False
 504
 505        if (
 506            self.ffmpeg_normalize.pre_filter
 507            or self.ffmpeg_normalize.post_filter
 508            or self.ffmpeg_normalize.audio_channels
 509        ):
 510            return False
 511
 512        # A skipped file is copied verbatim, which only yields a valid file when
 513        # the container stays the same. If the output extension differs, fall
 514        # back to normal normalization so the requested format is produced.
 515        input_ext = os.path.splitext(self.input_file)[1][1:].lower()
 516        if input_ext != self.output_ext.lower():
 517            return False
 518
 519        norm_type = self.ffmpeg_normalize.normalization_type
 520        target = self.ffmpeg_normalize.target_level
 521        streams = self._get_streams_to_normalize()
 522        if not streams:
 523            return False
 524
 525        for stream in streams:
 526            measured: float | None
 527            if norm_type == "ebu":
 528                ebu_stats = stream.loudness_statistics["ebu_pass1"]
 529                if ebu_stats is None:
 530                    return False
 531                measured = ebu_stats["input_i"]
 532            elif norm_type == "peak":
 533                measured = stream.loudness_statistics["max"]
 534            else:  # rms
 535                measured = stream.loudness_statistics["mean"]
 536
 537            if measured is None:
 538                return False
 539            if abs(target - float(measured)) > threshold:
 540                return False
 541
 542        return True
 543
 544    def _handle_skip(self) -> None:
 545        """
 546        Mark this file as skipped (already at target) and copy the input
 547        through to the output unchanged.
 548
 549        The input is copied verbatim (codec and other output options are not
 550        applied to skipped files; use a threshold of 0 to always re-encode).
 551        Stale ReplayGain tags are still stripped from the output, and the input
 552        modification time is preserved if requested.
 553        """
 554        self.status = "skipped"
 555        _logger.info(
 556            f"{self.input_file}: already within {self.ffmpeg_normalize.threshold} "
 557            f"of target level {self.ffmpeg_normalize.target_level}, "
 558            "skipping normalization"
 559        )
 560
 561        if self.ffmpeg_normalize.dry_run:
 562            _logger.warning("Dry run used, not actually copying the file")
 563            return
 564
 565        if self.output_file == os.devnull:
 566            return
 567
 568        if os.path.realpath(self.input_file) != os.path.realpath(self.output_file):
 569            try:
 570                copyfile(self.input_file, self.output_file)
 571            except OSError as e:
 572                raise FFmpegNormalizeError(
 573                    f"Could not copy {self.input_file} to {self.output_file}: {e}"
 574                )
 575        else:
 576            _logger.debug(
 577                "Output file is the same as the input file, leaving it unchanged"
 578            )
 579
 580        # Remove any existing ReplayGain tags from the output, matching the
 581        # behavior of a normal run.
 582        self._strip_replaygain_tags(self.output_file)
 583
 584        if self.ffmpeg_normalize.keep_mtime:
 585            self._apply_input_timestamps()
 586
 587        _logger.info(f"Skipped file copied to {self.output_file}")
 588
 589    def _apply_input_timestamps(self) -> None:
 590        """
 591        Copy the input file's access and modification times to the output file.
 592
 593        Used when the ``keep_mtime`` option is enabled. Only the access and
 594        modification times are copied; a file's creation time (which some
 595        operating systems such as Windows track separately) is not affected.
 596        """
 597        if self.input_timestamps is None:
 598            return
 599        atime, mtime = self.input_timestamps
 600        try:
 601            os.utime(self.output_file, (atime, mtime))
 602            _logger.debug(
 603                f"Copied input timestamps to {self.output_file} "
 604                f"(atime={atime}, mtime={mtime})"
 605            )
 606        except OSError as e:
 607            _logger.warning(f"Could not copy timestamps to {self.output_file}: {e}")
 608
 609    def _run_replaygain(self) -> None:
 610        """
 611        Run the replaygain process for this file.
 612        """
 613        _logger.debug(f"Running replaygain for {self.input_file}")
 614
 615        # get the audio streams
 616        audio_streams = list(self.streams["audio"].values())
 617
 618        # Attempt to use EBU pass 2 statistics, which account for pre-filters.
 619        # These are populated by the main second pass if it runs (not a dry run)
 620        # and normalization_type is 'ebu'.
 621        loudness_stats_source = "ebu_pass2"
 622        loudnorm_stats = audio_streams[0].loudness_statistics.get("ebu_pass2")
 623
 624        if loudnorm_stats is None:
 625            _logger.warning(
 626                "ReplayGain: Second pass EBU statistics (ebu_pass2) not found. "
 627                "Falling back to first pass EBU statistics (ebu_pass1). "
 628                "This may not account for pre-filters if any are used."
 629            )
 630            loudness_stats_source = "ebu_pass1"
 631            loudnorm_stats = audio_streams[0].loudness_statistics.get("ebu_pass1")
 632
 633        if loudnorm_stats is None:
 634            _logger.error(
 635                f"ReplayGain: No loudness statistics available from {loudness_stats_source} (and fallback) for stream 0. "
 636                "Cannot calculate ReplayGain tags."
 637            )
 638            return
 639
 640        _logger.debug(
 641            f"Using statistics from {loudness_stats_source} for ReplayGain calculation."
 642        )
 643
 644        # apply the replaygain tag from the first audio stream (to all audio streams)
 645        if len(audio_streams) > 1:
 646            _logger.warning(
 647                f"Your input file has {len(audio_streams)} audio streams. "
 648                "Only the first audio stream's replaygain tag will be applied. "
 649                "All audio streams will receive the same tag."
 650            )
 651
 652        target_level = self.ffmpeg_normalize.target_level
 653        # Use 'input_i' and 'input_tp' from the chosen stats.
 654        # For ebu_pass2, these are measurements *after* pre-filter but *before* loudnorm adjustment.
 655        input_i = loudnorm_stats.get("input_i")
 656        input_tp = loudnorm_stats.get("input_tp")
 657
 658        if input_i is None or input_tp is None:
 659            _logger.error(
 660                f"ReplayGain: 'input_i' or 'input_tp' missing from {loudness_stats_source} statistics. "
 661                "Cannot calculate ReplayGain tags."
 662            )
 663            return
 664
 665        track_gain = -(input_i - target_level)  # dB
 666        track_peak = 10 ** (input_tp / 20)  # linear scale
 667
 668        _logger.debug(f"Calculated Track gain: {track_gain:.2f} dB")
 669        _logger.debug(f"Calculated Track peak: {track_peak:.2f}")
 670
 671        if not self.ffmpeg_normalize.dry_run:  # This uses the overall dry_run state
 672            self._write_replaygain_tags(track_gain, track_peak)
 673        else:
 674            _logger.warning(
 675                "Overall dry_run is enabled, not actually writing ReplayGain tags to the file. "
 676                "Tag calculation based on available stats was performed."
 677            )
 678
 679    def _write_replaygain_tags(self, track_gain: float, track_peak: float) -> None:
 680        """
 681        Write the replaygain tags to the input file.
 682
 683        This is based on the code from bohning/usdb_syncer, licensed under the MIT license.
 684        See: https://github.com/bohning/usdb_syncer/blob/2fa638c4f487dffe9f5364f91e156ba54cb20233/src/usdb_syncer/resource_dl.py
 685        """
 686        _logger.debug(f"Writing ReplayGain tags to {self.input_file}")
 687
 688        input_file_ext = os.path.splitext(self.input_file)[1]
 689        if input_file_ext == ".mp3":
 690            mp3 = MP3(self.input_file, ID3=ID3)
 691            if not mp3.tags:
 692                return
 693            mp3.tags.add(
 694                TXXX(desc="REPLAYGAIN_TRACK_GAIN", text=[f"{track_gain:.2f} dB"])
 695            )
 696            mp3.tags.add(TXXX(desc="REPLAYGAIN_TRACK_PEAK", text=[f"{track_peak:.6f}"]))
 697            mp3.save()
 698        elif input_file_ext in [".mp4", ".m4a", ".m4v", ".mov"]:
 699            mp4 = MP4(self.input_file)
 700            if not mp4.tags:
 701                mp4.add_tags()
 702            if not mp4.tags:
 703                return
 704            mp4.tags["----:com.apple.iTunes:REPLAYGAIN_TRACK_GAIN"] = [
 705                f"{track_gain:.2f} dB".encode()
 706            ]
 707            mp4.tags["----:com.apple.iTunes:REPLAYGAIN_TRACK_PEAK"] = [
 708                f"{track_peak:.6f}".encode()
 709            ]
 710            mp4.save()
 711        elif input_file_ext == ".ogg":
 712            ogg = OggVorbis(self.input_file)
 713            ogg["REPLAYGAIN_TRACK_GAIN"] = [f"{track_gain:.2f} dB"]
 714            ogg["REPLAYGAIN_TRACK_PEAK"] = [f"{track_peak:.6f}"]
 715            ogg.save()
 716        elif input_file_ext == ".opus":
 717            opus = OggOpus(self.input_file)
 718            # See https://datatracker.ietf.org/doc/html/rfc7845#section-5.2.1
 719            opus["R128_TRACK_GAIN"] = [str(round(256 * track_gain))]
 720            opus.save()
 721        else:
 722            _logger.error(
 723                f"Unsupported input file extension: {input_file_ext} for writing replaygain tags. "
 724                "Only .mp3, .mp4/.m4a, .ogg, .opus are supported. "
 725                "If you think this should support more formats, please let me know at "
 726                "https://github.com/slhck/ffmpeg-normalize/issues"
 727            )
 728            return
 729
 730        _logger.info(
 731            f"Successfully wrote replaygain tags to input file {self.input_file}"
 732        )
 733
 734    def _strip_replaygain_tags(self, output_file: str) -> None:
 735        """
 736        Strip ReplayGain tags from the output file after normalization.
 737
 738        This ensures that old ReplayGain tags from the input are removed,
 739        since they are no longer accurate after normalization.
 740
 741        Args:
 742            output_file (str): Path to the output file to strip tags from
 743        """
 744        _logger.debug(f"Stripping ReplayGain tags from {output_file}")
 745
 746        output_file_ext = os.path.splitext(output_file)[1]
 747        if output_file_ext == ".mp3":
 748            try:
 749                mp3 = MP3(output_file, ID3=ID3)
 750                if not mp3.tags:
 751                    return
 752                # Remove REPLAYGAIN_* tags
 753                tags_to_remove = [
 754                    key for key in mp3.tags if key.startswith("TXXX:REPLAYGAIN_")
 755                ]
 756                for tag in tags_to_remove:
 757                    del mp3.tags[tag]
 758                if tags_to_remove:
 759                    mp3.save()
 760                    _logger.debug(
 761                        f"Stripped {len(tags_to_remove)} ReplayGain tag(s) from {output_file}"
 762                    )
 763            except Exception as e:
 764                _logger.warning(
 765                    f"Could not strip ReplayGain tags from {output_file}: {e}"
 766                )
 767        elif output_file_ext in [".mp4", ".m4a", ".m4v", ".mov"]:
 768            try:
 769                mp4 = MP4(output_file)
 770                if not mp4.tags:
 771                    return
 772                # Remove REPLAYGAIN_* tags
 773                tags_to_remove = [
 774                    key
 775                    for key in mp4.tags
 776                    if "REPLAYGAIN_" in key.upper() or "REPLAYGAIN" in key.upper()
 777                ]
 778                for tag in tags_to_remove:
 779                    del mp4.tags[tag]
 780                if tags_to_remove:
 781                    mp4.save()
 782                    _logger.debug(
 783                        f"Stripped {len(tags_to_remove)} ReplayGain tag(s) from {output_file}"
 784                    )
 785            except Exception as e:
 786                _logger.warning(
 787                    f"Could not strip ReplayGain tags from {output_file}: {e}"
 788                )
 789        elif output_file_ext == ".ogg":
 790            try:
 791                ogg = OggVorbis(output_file)
 792                # Remove REPLAYGAIN_* tags (case-insensitive)
 793                tags_to_remove = [
 794                    key for key in ogg.keys() if key.upper().startswith("REPLAYGAIN_")
 795                ]
 796                for tag in tags_to_remove:
 797                    del ogg[tag]
 798                if tags_to_remove:
 799                    ogg.save()
 800                    _logger.debug(
 801                        f"Stripped {len(tags_to_remove)} ReplayGain tag(s) from {output_file}"
 802                    )
 803            except Exception as e:
 804                _logger.warning(
 805                    f"Could not strip ReplayGain tags from {output_file}: {e}"
 806                )
 807        elif output_file_ext == ".opus":
 808            try:
 809                opus = OggOpus(output_file)
 810                # Remove R128_* tags (Opus uses R128 instead of REPLAYGAIN, case-insensitive)
 811                tags_to_remove = [
 812                    key for key in opus.keys() if key.upper().startswith("R128_")
 813                ]
 814                for tag in tags_to_remove:
 815                    del opus[tag]
 816                if tags_to_remove:
 817                    opus.save()
 818                    _logger.debug(
 819                        f"Stripped {len(tags_to_remove)} R128 tag(s) from {output_file}"
 820                    )
 821            except Exception as e:
 822                _logger.warning(
 823                    f"Could not strip ReplayGain tags from {output_file}: {e}"
 824                )
 825        else:
 826            # For other formats, we don't need to strip tags
 827            _logger.debug(
 828                f"Skipping ReplayGain tag stripping for {output_file_ext} (not supported/needed)"
 829            )
 830
 831    def _can_write_output_video(self) -> bool:
 832        """
 833        Determine whether the output file can contain video at all.
 834
 835        Returns:
 836            bool: True if the output file can contain video, False otherwise
 837        """
 838        if self.output_ext.lower() in AUDIO_ONLY_FORMATS:
 839            return False
 840
 841        return not self.ffmpeg_normalize.video_disable
 842
 843    def _first_pass(self) -> None:
 844        """
 845        Run the first pass of the normalization process.
 846        """
 847        _logger.debug(f"Parsing normalization info for {self.input_file}")
 848
 849        streams_to_normalize = self._get_streams_to_normalize()
 850
 851        for index, audio_stream in enumerate(streams_to_normalize):
 852            if self.ffmpeg_normalize.normalization_type == "ebu":
 853                fun = getattr(audio_stream, "parse_loudnorm_stats")
 854            else:
 855                fun = getattr(audio_stream, "parse_astats")
 856
 857            description = f"First pass, stream {index + 1}/{len(streams_to_normalize)}"
 858            with self.ffmpeg_normalize.progress_display.task(description) as update:
 859                for progress in fun():
 860                    update(progress)
 861
 862    def _get_stream_filter_chain(self, audio_stream: AudioStream) -> list[str]:
 863        """
 864        Return the ordered list of ffmpeg audio filters applied to a single
 865        stream in the second pass: the optional pre-filter, channel conversion,
 866        the normalization filter itself (loudnorm for EBU, or the volume /
 867        dynaudnorm filter for peak / RMS), and the optional post-filter.
 868
 869        Returns:
 870            list[str]: the filters, in application order
 871        """
 872        skip_normalization = False
 873        if self.ffmpeg_normalize.lower_only and not (
 874            self.batch_reference is not None
 875            and self.ffmpeg_normalize.normalization_type in ("peak", "rms")
 876        ):
 877            if self.ffmpeg_normalize.normalization_type == "ebu":
 878                if (
 879                    audio_stream.loudness_statistics["ebu_pass1"] is not None
 880                    and audio_stream.loudness_statistics["ebu_pass1"]["input_i"]
 881                    < self.ffmpeg_normalize.target_level
 882                ):
 883                    skip_normalization = True
 884            elif self.ffmpeg_normalize.normalization_type == "peak":
 885                if (
 886                    audio_stream.loudness_statistics["max"] is not None
 887                    and audio_stream.loudness_statistics["max"]
 888                    < self.ffmpeg_normalize.target_level
 889                ):
 890                    skip_normalization = True
 891            elif self.ffmpeg_normalize.normalization_type == "rms":
 892                if (
 893                    audio_stream.loudness_statistics["mean"] is not None
 894                    and audio_stream.loudness_statistics["mean"]
 895                    < self.ffmpeg_normalize.target_level
 896                ):
 897                    skip_normalization = True
 898
 899        if skip_normalization:
 900            _logger.warning(
 901                f"Stream {audio_stream.stream_id} had measured input loudness lower than target, skipping normalization."
 902            )
 903            normalization_filter = "acopy"
 904            audio_stream.applied_gain = 0.0
 905        else:
 906            if self.ffmpeg_normalize.normalization_type == "ebu":
 907                normalization_filter = audio_stream.get_second_pass_opts_ebu(
 908                    batch_reference=self.batch_reference
 909                )
 910            else:
 911                normalization_filter = audio_stream.get_second_pass_opts_peakrms(
 912                    batch_reference=self.batch_reference
 913                )
 914
 915        filter_chain = []
 916
 917        if self.ffmpeg_normalize.pre_filter:
 918            filter_chain.append(self.ffmpeg_normalize.pre_filter)
 919
 920        # Apply channel conversion before normalization so that the
 921        # normalization filter operates on the same channel layout that
 922        # was measured in the first pass. See issue #316.
 923        if self.ffmpeg_normalize.audio_channels:
 924            filter_chain.append(
 925                f"aformat=sample_fmts=fltp:channel_layouts={self.ffmpeg_normalize.audio_channels}c"
 926            )
 927
 928        filter_chain.append(normalization_filter)
 929
 930        if self.ffmpeg_normalize.post_filter:
 931            filter_chain.append(self.ffmpeg_normalize.post_filter)
 932
 933        return filter_chain
 934
 935    def _get_audio_filter_cmd(self) -> tuple[str, list[str]]:
 936        """
 937        Return the audio filter command and output labels needed.
 938
 939        Returns:
 940            tuple[str, list[str]]: filter_complex command and the required output labels
 941        """
 942        filter_chains = []
 943        output_labels = []
 944
 945        self._stream_filter_chains = {}
 946
 947        for audio_stream in self._get_streams_to_normalize():
 948            filter_chain = self._get_stream_filter_chain(audio_stream)
 949            self._stream_filter_chains[audio_stream.stream_id] = filter_chain
 950
 951            input_label = f"[0:{audio_stream.stream_id}]"
 952            output_label = f"[norm{audio_stream.stream_id}]"
 953            output_labels.append(output_label)
 954
 955            filter_chains.append(input_label + ",".join(filter_chain) + output_label)
 956
 957        filter_complex_cmd = ";".join(filter_chains)
 958
 959        return filter_complex_cmd, output_labels
 960
 961    def _get_encoder_settings(
 962        self, audio_stream: AudioStream, audio_codec: str | None
 963    ) -> str:
 964        """
 965        Return an ffmpeg-command-equivalent description of how a single audio
 966        stream is encoded in the second pass: the codec, then the bitrate,
 967        sample rate and channel count when set, followed by the effective
 968        filter chain (which includes the loudnorm measured values).
 969
 970        Written as the ``ENCODER_SETTINGS`` stream tag when
 971        ``write_encoder_settings`` is enabled. The filter chain comes from the
 972        cache populated by :meth:`_get_audio_filter_cmd`, which must run first.
 973        The loudnorm ``print_format`` option is dropped, as it only controls
 974        first-pass diagnostics and not the normalization itself.
 975
 976        Returns:
 977            str: e.g. ``-c:a libopus -b:a 128000 -af loudnorm=i=-23.0:...``
 978        """
 979        codec = audio_codec if audio_codec else audio_stream.get_pcm_codec()
 980        args = ["-c:a", codec]
 981        if self.ffmpeg_normalize.audio_bitrate:
 982            args += ["-b:a", str(self.ffmpeg_normalize.audio_bitrate)]
 983        if self.ffmpeg_normalize.sample_rate:
 984            args += ["-ar", str(self.ffmpeg_normalize.sample_rate)]
 985        if self.ffmpeg_normalize.audio_channels:
 986            args += ["-ac", str(self.ffmpeg_normalize.audio_channels)]
 987        filter_chain = self._stream_filter_chains.get(audio_stream.stream_id, [])
 988        if filter_chain:
 989            af = re.sub(r":print_format=\w+", "", ",".join(filter_chain))
 990            args += ["-af", af]
 991        return shlex.join(args)
 992
 993    def _get_audio_codec(self) -> str | None:
 994        """
 995        Return the audio encoder to use for normalized streams, or None to use
 996        the bit-depth-aware PCM default.
 997
 998        An explicit ``--audio-codec`` (``-c:a``) always takes precedence.
 999        Otherwise, for a container that cannot store PCM (e.g. FLAC, MP3, Opus),
1000        fall back to the codec ffmpeg itself would default to for that container,
1001        so audio-only outputs work without requiring ``-c:a``. PCM-friendly
1002        containers (e.g. WAV, Matroska) keep the lossless PCM default regardless
1003        of their own muxer default.
1004
1005        Returns:
1006            str | None: The encoder name, or None to use the PCM default.
1007        """
1008        if self.ffmpeg_normalize.audio_codec:
1009            return self.ffmpeg_normalize.audio_codec
1010
1011        output_format = self.ffmpeg_normalize.output_format
1012        if output_format in PCM_INCOMPATIBLE_FORMATS:
1013            container = output_format
1014        elif self.output_ext.lower() in PCM_INCOMPATIBLE_EXTS:
1015            container = self.output_ext
1016        else:
1017            return None
1018
1019        encoder = get_muxer_default_audio_encoder(container)
1020        if encoder is not None:
1021            _logger.debug(
1022                f"No audio codec set; using ffmpeg's default '{encoder}' for "
1023                f"container '{container}'"
1024            )
1025        return encoder
1026
1027    def _second_pass(self) -> Iterator[float]:
1028        """
1029        Construct the second pass command and run it.
1030
1031        FIXME: make this method simpler
1032        """
1033        _logger.info(f"Running second pass for {self.input_file}")
1034
1035        # get the target output stream types depending on the options
1036        output_stream_types: list[Literal["audio", "video", "subtitle"]] = ["audio"]
1037        if self._can_write_output_video():
1038            output_stream_types.append("video")
1039        if not self.ffmpeg_normalize.subtitle_disable:
1040            output_stream_types.append("subtitle")
1041
1042        # base command, here we will add all other options
1043        cmd = [self.ffmpeg_normalize.ffmpeg_exe, "-hide_banner", "-y"]
1044
1045        # extra options (if any)
1046        if self.ffmpeg_normalize.extra_input_options:
1047            cmd.extend(self.ffmpeg_normalize.extra_input_options)
1048
1049        # get complex filter command
1050        audio_filter_cmd, output_labels = self._get_audio_filter_cmd()
1051
1052        # add input file and basic filter
1053        cmd.extend(["-i", self.input_file, "-filter_complex", audio_filter_cmd])
1054
1055        # map metadata, only if needed
1056        if self.ffmpeg_normalize.metadata_disable:
1057            cmd.extend(["-map_metadata", "-1"])
1058        else:
1059            # map global metadata
1060            cmd.extend(["-map_metadata", "0"])
1061            # map per-stream metadata (e.g. language tags)
1062            for stream_type in output_stream_types:
1063                stream_key = stream_type[0]
1064                if stream_type not in self.streams:
1065                    continue
1066                for idx, _ in enumerate(self.streams[stream_type].items()):
1067                    cmd.extend(
1068                        [
1069                            f"-map_metadata:s:{stream_key}:{idx}",
1070                            f"0:s:{stream_key}:{idx}",
1071                        ]
1072                    )
1073
1074        # map chapters if needed
1075        if self.ffmpeg_normalize.chapters_disable:
1076            cmd.extend(["-map_chapters", "-1"])
1077        else:
1078            cmd.extend(["-map_chapters", "0"])
1079
1080        # collect all '-map' and codecs needed for output video based on input video
1081        if self.streams["video"]:
1082            if self._can_write_output_video():
1083                for s in self.streams["video"].keys():
1084                    cmd.extend(["-map", f"0:{s}"])
1085                # set codec (copy by default)
1086                cmd.extend(["-c:v", self.ffmpeg_normalize.video_codec])
1087            else:
1088                if not self.ffmpeg_normalize.video_disable:
1089                    _logger.warning(
1090                        f"The chosen output extension {self.output_ext} does not support video/cover art. It will be disabled."
1091                    )
1092
1093        # Determine streams to normalize and passthrough
1094        streams_to_normalize = self._get_streams_to_normalize()
1095        all_audio_streams = list(self.streams["audio"].values())
1096
1097        # Determine which streams to passthrough
1098        if self.ffmpeg_normalize.keep_other_audio and (
1099            self.ffmpeg_normalize.audio_streams is not None
1100            or self.ffmpeg_normalize.audio_default_only
1101        ):
1102            streams_to_passthrough = [
1103                s for s in all_audio_streams if s not in streams_to_normalize
1104            ]
1105        else:
1106            streams_to_passthrough = []
1107
1108        # ... and map the output of the normalization filters
1109        for ol in output_labels:
1110            cmd.extend(["-map", ol])
1111
1112        # ... and map passthrough audio streams (copy without normalization)
1113        for stream in streams_to_passthrough:
1114            cmd.extend(["-map", f"0:{stream.stream_id}"])
1115
1116        # Track output audio stream index for codec assignment
1117        output_audio_idx = 0
1118
1119        # Resolve the audio codec once: an explicit --audio-codec wins, otherwise
1120        # fall back to ffmpeg's own default codec for the output container (None
1121        # means use the bit-depth-aware PCM default).
1122        audio_codec = self._get_audio_codec()
1123
1124        # set audio codec for normalized streams
1125        for audio_stream in streams_to_normalize:
1126            codec = audio_codec if audio_codec else audio_stream.get_pcm_codec()
1127            cmd.extend([f"-c:a:{output_audio_idx}", codec])
1128            output_audio_idx += 1
1129
1130        # set audio codec for passthrough streams (always copy)
1131        for _ in streams_to_passthrough:
1132            cmd.extend([f"-c:a:{output_audio_idx}", "copy"])
1133            output_audio_idx += 1
1134
1135        # other audio options (if any) - only apply to normalized streams
1136        if self.ffmpeg_normalize.audio_bitrate:
1137            if audio_codec == "libvorbis":
1138                # libvorbis takes just a "-b" option, for some reason
1139                # https://github.com/slhck/ffmpeg-normalize/issues/277
1140                cmd.extend(["-b", str(self.ffmpeg_normalize.audio_bitrate)])
1141            else:
1142                # Only apply to normalized streams
1143                for idx in range(len(streams_to_normalize)):
1144                    cmd.extend(
1145                        [f"-b:a:{idx}", str(self.ffmpeg_normalize.audio_bitrate)]
1146                    )
1147        if self.ffmpeg_normalize.sample_rate:
1148            # Only apply to normalized streams
1149            for idx in range(len(streams_to_normalize)):
1150                cmd.extend([f"-ar:a:{idx}", str(self.ffmpeg_normalize.sample_rate)])
1151        if self.ffmpeg_normalize.audio_channels:
1152            # Only apply to normalized streams
1153            for idx in range(len(streams_to_normalize)):
1154                cmd.extend([f"-ac:a:{idx}", str(self.ffmpeg_normalize.audio_channels)])
1155
1156        # record how each normalized stream was encoded as an ENCODER_SETTINGS
1157        # tag (a Matroska/WebM convention), so the output documents itself
1158        if (
1159            self.ffmpeg_normalize.write_encoder_settings
1160            and not self.ffmpeg_normalize.metadata_disable
1161        ):
1162            for idx, audio_stream in enumerate(streams_to_normalize):
1163                cmd.extend(
1164                    [
1165                        f"-metadata:s:a:{idx}",
1166                        "ENCODER_SETTINGS="
1167                        + self._get_encoder_settings(audio_stream, audio_codec),
1168                    ]
1169                )
1170
1171        # carry the input bit depth through to the output encoder, if requested
1172        if self.ffmpeg_normalize.keep_bit_depth:
1173            for idx, audio_stream in enumerate(streams_to_normalize):
1174                sample_fmt = audio_stream.get_output_sample_fmt(audio_codec)
1175                if sample_fmt is not None:
1176                    cmd.extend([f"-sample_fmt:a:{idx}", sample_fmt])
1177
1178        # ... and subtitles
1179        if not self.ffmpeg_normalize.subtitle_disable:
1180            for s in self.streams["subtitle"].keys():
1181                cmd.extend(["-map", f"0:{s}"])
1182            # copy subtitles
1183            cmd.extend(["-c:s", "copy"])
1184
1185        if self.ffmpeg_normalize.keep_original_audio:
1186            # Map all original audio streams after normalized and passthrough streams
1187            for index, _ in enumerate(self.streams["audio"].items()):
1188                cmd.extend(["-map", f"0:a:{index}"])
1189                cmd.extend([f"-c:a:{output_audio_idx}", "copy"])
1190                output_audio_idx += 1
1191
1192        # extra options (if any)
1193        if self.ffmpeg_normalize.extra_output_options:
1194            cmd.extend(self.ffmpeg_normalize.extra_output_options)
1195
1196        # output format (if any)
1197        if self.ffmpeg_normalize.output_format:
1198            cmd.extend(["-f", self.ffmpeg_normalize.output_format])
1199
1200        # if dry run, only show sample command
1201        if self.ffmpeg_normalize.dry_run:
1202            cmd.append(self.output_file)
1203            _logger.warning("Dry run used, not actually running second-pass command")
1204            CommandRunner(dry=True).run_command(cmd)
1205            yield 100
1206            return
1207
1208        is_in_place_overwrite = os.path.realpath(self.input_file) == os.path.realpath(
1209            self.output_file
1210        )
1211
1212        temp_file: Union[str, None] = None
1213        if is_in_place_overwrite:
1214            # need to create a temporary file because we cannot override
1215            # the same input file
1216            output_dir = os.path.dirname(self.output_file) or "."
1217            fd, temp_file = mkstemp(
1218                suffix=f".{self.output_ext}",
1219                prefix=f".{os.path.splitext(os.path.basename(self.output_file))[0]}.",
1220                dir=output_dir,
1221            )
1222            os.close(fd)
1223            # mkstemp creates the file with mode 0600; keep the input's mode
1224            copymode(self.input_file, temp_file)
1225            _logger.debug(
1226                f"Output file is the same as the input file, "
1227                f"encoding to temporary file {temp_file} first"
1228            )
1229            cmd.append(temp_file)
1230        else:
1231            cmd.append(self.output_file)
1232
1233        cmd_runner = CommandRunner()
1234        try:
1235            yield from cmd_runner.run_ffmpeg_command(cmd)
1236        except Exception as e:
1237            if temp_file and os.path.exists(temp_file):
1238                os.remove(temp_file)
1239            raise e
1240        else:
1241            # for in-place normalization, move the finished temp file over the input
1242            if temp_file:
1243                _logger.debug(
1244                    f"Moving temporary file from {temp_file} to {self.output_file}"
1245                )
1246                os.replace(temp_file, self.output_file)
1247
1248        output = cmd_runner.get_output()
1249        # in the second pass, we do not normalize stream-by-stream, so we set the stats based on the
1250        # overall output (which includes multiple loudnorm stats)
1251        if self.ffmpeg_normalize.normalization_type == "ebu":
1252            ebu_pass_2_stats = list(
1253                AudioStream.prune_and_parse_loudnorm_output(output).values()
1254            )
1255            # Only set second pass stats for streams that were actually normalized
1256            streams_to_normalize = self._get_streams_to_normalize()
1257            if len(ebu_pass_2_stats) == len(streams_to_normalize):
1258                for idx, audio_stream in enumerate(streams_to_normalize):
1259                    audio_stream.set_second_pass_stats(ebu_pass_2_stats[idx])
1260            else:
1261                _logger.debug(
1262                    f"Expected {len(streams_to_normalize)} EBU pass 2 statistics but got {len(ebu_pass_2_stats)}. "
1263                    "This can happen when normalization is skipped (e.g., with --lower-only)."
1264                )
1265
1266        # warn if dynamic == False and any of the second pass stats contain "normalization_type" == "dynamic"
1267        if self.ffmpeg_normalize.dynamic is False:
1268            for audio_stream in self.streams["audio"].values():
1269                pass2_stats = audio_stream.get_stats()["ebu_pass2"]
1270                if pass2_stats is None:
1271                    continue
1272                if pass2_stats["normalization_type"] == "dynamic":
1273                    pass1_stats = audio_stream.get_stats()["ebu_pass1"]
1274
1275                    reason = ""
1276                    if pass1_stats is not None:
1277                        target_level = audio_stream.verification_target_level
1278                        if target_level is None:
1279                            target_level = self.ffmpeg_normalize.target_level
1280                        linear_gain = target_level - pass1_stats["input_i"]
1281                        estimated_tp = pass1_stats["input_tp"] + linear_gain
1282                        if estimated_tp > self.ffmpeg_normalize.true_peak:
1283                            min_tp = estimated_tp
1284                            max_target = (
1285                                self.ffmpeg_normalize.true_peak
1286                                - pass1_stats["input_tp"]
1287                                + pass1_stats["input_i"]
1288                            )
1289                            reason = (
1290                                f" Reason: the input true peak ({pass1_stats['input_tp']:.2f} dBTP) is too high — "
1291                                f"after linear gain of {linear_gain:.2f} dB, "
1292                                f"the estimated true peak would be {estimated_tp:.2f} dBTP, "
1293                                f"exceeding the target of {self.ffmpeg_normalize.true_peak} dBTP. "
1294                                f"To avoid this, raise --true-peak (-tp) to at least {min_tp:.1f}, "
1295                                f"or lower the target level (-t) to at most {max_target:.1f}."
1296                            )
1297                        elif (
1298                            pass1_stats["input_lra"]
1299                            > self.ffmpeg_normalize.loudness_range_target
1300                        ):
1301                            reason = (
1302                                f" Reason: the input loudness range ({pass1_stats['input_lra']:.2f} LU) "
1303                                f"exceeds the target ({self.ffmpeg_normalize.loudness_range_target:.2f} LU). "
1304                                "Consider raising the target loudness range or using "
1305                                "--keep-loudness-range-target / --keep-lra-above-loudness-range-target."
1306                            )
1307                        elif pass1_stats["input_lra"] == 0:
1308                            reason = (
1309                                " Reason: the measured input loudness range is zero; "
1310                                "the loudnorm filter requires a nonzero measured range for linear normalization."
1311                            )
1312
1313                    _logger.warning(
1314                        f"{self.input_file}: You specified linear normalization, but the loudnorm filter "
1315                        f"reverted to dynamic normalization.{reason}"
1316                    )
1317
1318        _logger.debug("Normalization finished")
1319
1320    def get_stats(self) -> Iterable[LoudnessStatisticsWithMetadata]:
1321        return (
1322            audio_stream.get_stats() for audio_stream in self.streams["audio"].values()
1323        )
1324
1325    def get_summary(self) -> list[SummaryRow]:
1326        """
1327        Return the before/after summary for each analyzed audio stream.
1328
1329        Streams without any measurement (e.g. streams not selected for
1330        normalization) are left out, unless the file failed to process.
1331
1332        Returns:
1333            list[SummaryRow]: One summary entry per audio stream
1334        """
1335        rows = [
1336            audio_stream.get_summary()
1337            for audio_stream in self.streams["audio"].values()
1338        ]
1339        return [
1340            row
1341            for row in rows
1342            if row["status"] == "error" or row["input_level"] is not None
1343        ]

Class that holds a file, its streams and adjustments

MediaFile( ffmpeg_normalize: FFmpegNormalize, input_file: str, output_file: str)
 68    def __init__(
 69        self, ffmpeg_normalize: FFmpegNormalize, input_file: str, output_file: str
 70    ):
 71        """
 72        Initialize a media file for later normalization by parsing the streams.
 73
 74        Args:
 75            ffmpeg_normalize (FFmpegNormalize): reference to overall settings
 76            input_file (str): Path to input file
 77            output_file (str): Path to output file
 78        """
 79        self.ffmpeg_normalize = ffmpeg_normalize
 80        self.skip = False
 81        # Per-file outcome, reported in the --print-stats output: "normalized"
 82        # (default), "skipped" (already within threshold of target), or "error".
 83        # "error" is set by FFmpegNormalize.run_normalization when processing
 84        # fails; on failure, self.error holds the error message.
 85        self.status: str = "normalized"
 86        self.error: str | None = None
 87        self.input_file = input_file
 88        self.output_file = output_file
 89        current_ext = os.path.splitext(output_file)[1][1:]
 90        # we need to check if it's empty, e.g. /dev/null or NUL
 91        if current_ext == "" or self.output_file == os.devnull:
 92            _logger.debug(
 93                f"Current extension is unset, or output file is a null device, using extension: {self.ffmpeg_normalize.extension}"
 94            )
 95            self.output_ext = self.ffmpeg_normalize.extension
 96        else:
 97            _logger.debug(
 98                f"Current extension is set from output file, using extension: {current_ext}"
 99            )
100            self.output_ext = current_ext
101        self.streams: StreamDict = {"audio": {}, "video": {}, "subtitle": {}}
102        self.temp_file: Union[str, None] = None
103        self.batch_reference: float | None = None
104        # Second-pass filter chain per normalized audio stream, keyed by stream
105        # id. Populated by _get_audio_filter_cmd() and reused by
106        # _get_encoder_settings() so the normalization filter is not built twice.
107        self._stream_filter_chains: dict[int, list[str]] = {}
108        # Input (access, modification) times captured before processing, used
109        # when the keep_mtime option is enabled.
110        self.input_timestamps: tuple[float, float] | None = None
111
112        self.parse_streams()

Initialize a media file for later normalization by parsing the streams.

Arguments:
  • ffmpeg_normalize (FFmpegNormalize): reference to overall settings
  • input_file (str): Path to input file
  • output_file (str): Path to output file
ffmpeg_normalize
skip
status: str
error: str | None
input_file
output_file
streams: ffmpeg_normalize._media_file.StreamDict
temp_file: str | None
batch_reference: float | None
input_timestamps: tuple[float, float] | None
def parse_streams(self) -> None:
130    def parse_streams(self) -> None:
131        """
132        Try to parse all input streams from file and set them in self.streams.
133
134        Raises:
135            FFmpegNormalizeError: If no audio streams are found
136        """
137        _logger.debug(f"Parsing streams of {self.input_file}")
138
139        cmd = [
140            self.ffmpeg_normalize.ffmpeg_exe,
141            "-i",
142            self.input_file,
143            "-c",
144            "copy",
145            "-t",
146            "0",
147            "-map",
148            "0",
149            "-f",
150            "null",
151            os.devnull,
152        ]
153
154        output = CommandRunner().run_command(cmd).get_output()
155
156        _logger.debug("Stream parsing command output:")
157        _logger.debug(output)
158
159        output_lines = [line.strip() for line in output.split("\n")]
160
161        # First pass: parse disposition flags for each stream
162        stream_dispositions: dict[int, bool] = {}
163
164        for line in output_lines:
165            if line.startswith("Stream"):
166                if stream_id_match := re.search(r"#0:([\d]+)", line):
167                    stream_id = int(stream_id_match.group(1))
168                    # Check if (default) appears on the Stream line
169                    is_default = "(default)" in line
170                    stream_dispositions[stream_id] = is_default
171
172        # Second pass: parse stream information
173        duration = None
174        for line in output_lines:
175            if "Duration" in line:
176                if duration_search := DUR_REGEX.search(line):
177                    duration = _to_ms(**duration_search.groupdict()) / 1000
178                    _logger.debug(f"Found duration: {duration} s")
179                else:
180                    _logger.warning("Could not extract duration from input file!")
181
182            if not line.startswith("Stream"):
183                continue
184
185            if stream_id_match := re.search(r"#0:([\d]+)", line):
186                stream_id = int(stream_id_match.group(1))
187                if stream_id in self._stream_ids():
188                    continue
189            else:
190                continue
191
192            is_default = stream_dispositions.get(stream_id, False)
193
194            if "Audio" in line:
195                _logger.debug(
196                    f"Found audio stream at index {stream_id} (default: {is_default})"
197                )
198                sample_rate_match = re.search(r"(\d+) Hz", line)
199                sample_rate = (
200                    int(sample_rate_match.group(1)) if sample_rate_match else None
201                )
202                bit_depth_match = re.search(r"([sfu])(\d+)(p|le|be)?", line)
203                bit_depth = int(bit_depth_match.group(2)) if bit_depth_match else None
204                is_float = bit_depth_match.group(1) == "f" if bit_depth_match else False
205                self.streams["audio"][stream_id] = AudioStream(
206                    self.ffmpeg_normalize,
207                    self,
208                    stream_id,
209                    sample_rate,
210                    bit_depth,
211                    duration,
212                    is_default,
213                    is_float,
214                )
215
216            elif "Video" in line:
217                _logger.debug(f"Found video stream at index {stream_id}")
218                self.streams["video"][stream_id] = VideoStream(
219                    self.ffmpeg_normalize, self, stream_id
220                )
221
222            elif "Subtitle" in line:
223                _logger.debug(f"Found subtitle stream at index {stream_id}")
224                self.streams["subtitle"][stream_id] = SubtitleStream(
225                    self.ffmpeg_normalize, self, stream_id
226                )
227
228        if not self.streams["audio"]:
229            raise FFmpegNormalizeError(
230                f"Input file {self.input_file} does not contain any audio streams"
231            )
232
233        if (
234            self.output_ext.lower() in ONE_STREAM
235            and len(self.streams["audio"].values()) > 1
236        ):
237            _logger.warning(
238                "Output file only supports one stream. Keeping only first audio stream."
239            )
240            first_stream = list(self.streams["audio"].values())[0]
241            self.streams["audio"] = {first_stream.stream_id: first_stream}
242            self.streams["video"] = {}
243            self.streams["subtitle"] = {}

Try to parse all input streams from file and set them in self.streams.

Raises:
  • FFmpegNormalizeError: If no audio streams are found
def run_normalization(self, batch_reference: float | None = None) -> None:
292    def run_normalization(self, batch_reference: float | None = None) -> None:
293        """
294        Run the normalization process for this file.
295
296        Args:
297            batch_reference (float | None, optional): Reference loudness for batch mode.
298                If provided, the first pass is skipped (assumed already done) and this
299                reference is used to calculate relative adjustments. Defaults to None.
300        """
301        _logger.debug(f"Running normalization for {self.input_file}")
302
303        # Store batch reference for use in second pass
304        self.batch_reference = batch_reference
305
306        # Capture the input file's timestamps before processing, since an
307        # in-place overwrite would otherwise lose the original modification time.
308        if self.ffmpeg_normalize.keep_mtime:
309            try:
310                stat = os.stat(self.input_file)
311                self.input_timestamps = (stat.st_atime, stat.st_mtime)
312            except OSError as e:
313                _logger.warning(
314                    f"Could not read timestamps from {self.input_file}: {e}"
315                )
316
317        # run the first pass to get loudness stats, unless in dynamic EBU mode or batch mode
318        # (in batch mode, first pass is already done in FFmpegNormalize.run_normalization)
319        if batch_reference is None:
320            if not (
321                self.ffmpeg_normalize.dynamic
322                and self.ffmpeg_normalize.normalization_type == "ebu"
323            ):
324                self._first_pass()
325            else:
326                _logger.debug(
327                    "Dynamic EBU mode: First pass will not run, as it is not needed."
328                )
329        else:
330            _logger.debug(
331                f"Batch mode: Skipping first pass (already completed), using batch reference = {batch_reference:.2f}"
332            )
333
334        # If the file is already within the configured threshold of the target
335        # level, skip normalization entirely and copy the input through to the
336        # output unchanged. This avoids needless re-encoding of files that are
337        # already at the target level.
338        if self._is_within_threshold():
339            self._handle_skip()
340            return
341
342        temp_dir = None
343
344        if self.ffmpeg_normalize.replaygain:
345            _logger.debug(
346                "ReplayGain mode: Second pass will run with temporary file to get stats."
347            )
348            temp_dir = mkdtemp()
349            self.temp_file = os.path.join(temp_dir, f"out.{self.output_ext}")
350            self.output_file = self.temp_file
351
352        # run the second pass as a whole.
353        with self.ffmpeg_normalize.progress_display.task("Second pass") as update:
354            for progress in self._second_pass():
355                update(progress)
356
357        # remove temp dir; this will remove the temp file as well if it has not been renamed (e.g. for replaygain)
358        if temp_dir and os.path.exists(temp_dir):
359            rmtree(temp_dir, ignore_errors=True)
360
361        # This will use stats from ebu_pass2 if available (from the main second pass),
362        # or fall back to ebu_pass1.
363        if self.ffmpeg_normalize.replaygain:
364            _logger.debug(
365                "ReplayGain tagging is enabled. Proceeding with tag calculation/application."
366            )
367            self._run_replaygain()
368        else:
369            # Strip any existing ReplayGain tags from the output file
370            # since they are no longer accurate after normalization
371            self._strip_replaygain_tags(self.output_file)
372            # Copy input timestamps last, after any tag modifications, so the
373            # output ends up with the original modification time.
374            if self.ffmpeg_normalize.keep_mtime and not self.ffmpeg_normalize.dry_run:
375                self._apply_input_timestamps()
376            _logger.info(f"Normalized file written to {self.output_file}")

Run the normalization process for this file.

Arguments:
  • batch_reference (float | None, optional): Reference loudness for batch mode. If provided, the first pass is skipped (assumed already done) and this reference is used to calculate relative adjustments. Defaults to None.
def verify_output(self) -> None:
378    def verify_output(self) -> None:
379        """Verify encoded audio, restoring requested timestamps after reading it."""
380        try:
381            self._verify_output()
382        finally:
383            if self.ffmpeg_normalize.keep_mtime:
384                self._apply_input_timestamps()

Verify encoded audio, restoring requested timestamps after reading it.

def get_stats( self) -> Iterable[ffmpeg_normalize._streams.LoudnessStatisticsWithMetadata]:
1320    def get_stats(self) -> Iterable[LoudnessStatisticsWithMetadata]:
1321        return (
1322            audio_stream.get_stats() for audio_stream in self.streams["audio"].values()
1323        )
def get_summary(self) -> list[ffmpeg_normalize._streams.SummaryRow]:
1325    def get_summary(self) -> list[SummaryRow]:
1326        """
1327        Return the before/after summary for each analyzed audio stream.
1328
1329        Streams without any measurement (e.g. streams not selected for
1330        normalization) are left out, unless the file failed to process.
1331
1332        Returns:
1333            list[SummaryRow]: One summary entry per audio stream
1334        """
1335        rows = [
1336            audio_stream.get_summary()
1337            for audio_stream in self.streams["audio"].values()
1338        ]
1339        return [
1340            row
1341            for row in rows
1342            if row["status"] == "error" or row["input_level"] is not None
1343        ]

Return the before/after summary for each analyzed audio stream.

Streams without any measurement (e.g. streams not selected for normalization) are left out, unless the file failed to process.

Returns:

list[SummaryRow]: One summary entry per audio stream

class AudioStream(ffmpeg_normalize.MediaStream):
148class AudioStream(MediaStream):
149    def __init__(
150        self,
151        ffmpeg_normalize: FFmpegNormalize,
152        media_file: MediaFile,
153        stream_id: int,
154        sample_rate: int | None,
155        bit_depth: int | None,
156        duration: float | None,
157        is_default: bool = False,
158        is_float: bool = False,
159    ):
160        """
161        Create an AudioStream object.
162
163        Args:
164            ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
165            media_file (MediaFile): The MediaFile object.
166            stream_id (int): The stream ID.
167            sample_rate (int): sample rate in Hz
168            bit_depth (int): bit depth in bits
169            duration (float): duration in seconds
170            is_default (bool): Whether this stream has the default disposition flag
171            is_float (bool): Whether the stream uses a floating-point sample format
172        """
173        super().__init__(ffmpeg_normalize, media_file, "audio", stream_id)
174
175        self.loudness_statistics: LoudnessStatistics = {
176            "ebu_pass1": None,
177            "ebu_pass2": None,
178            "mean": None,
179            "max": None,
180        }
181
182        # Gain in dB applied by the second pass volume filter (peak/RMS), or 0
183        # when normalization is skipped for this stream (e.g. with lower_only).
184        # Stays None for EBU, where the gain is derived from the second pass stats.
185        self.applied_gain: float | None = None
186        self.verification_target_level: float | None = None
187        self.verification: VerificationResult | None = None
188
189        self.sample_rate = sample_rate
190        self.bit_depth = bit_depth
191
192        self.duration = duration
193        self.is_default = is_default
194        self.is_float = is_float
195
196    @staticmethod
197    def _constrain(
198        number: float, min_range: float, max_range: float, name: str | None = None
199    ) -> float:
200        """
201        Constrain a number between two values.
202
203        Args:
204            number (float): The number to constrain.
205            min_range (float): The minimum value.
206            max_range (float): The maximum value.
207            name (str): The name of the number (for logging).
208
209        Returns:
210            float: The constrained number.
211
212        Raises:
213            ValueError: If min_range is greater than max_range.
214        """
215        if min_range > max_range:
216            raise ValueError("min must be smaller than max")
217        result = max(min(number, max_range), min_range)
218        if result != number and name is not None:
219            _logger.warning(
220                f"Constraining {name} to range of [{min_range}, {max_range}]: {number} -> {result}"
221            )
222        return result
223
224    def get_stats(self) -> LoudnessStatisticsWithMetadata:
225        """
226        Return loudness statistics for the stream.
227
228        Returns:
229            dict: A dictionary containing the loudness statistics.
230        """
231        stats: LoudnessStatisticsWithMetadata = {
232            "input_file": self.media_file.input_file,
233            "output_file": self.media_file.output_file,
234            "stream_id": self.stream_id,
235            "ebu_pass1": self.loudness_statistics["ebu_pass1"],
236            "ebu_pass2": self.loudness_statistics["ebu_pass2"],
237            "mean": self.loudness_statistics["mean"],
238            "max": self.loudness_statistics["max"],
239            "status": self.media_file.status,
240        }
241        if self.verification is not None:
242            stats["verification"] = self.verification
243        # Only present when the file failed to process, per the per-file outcome
244        # reporting (status is "error").
245        if self.media_file.error is not None:
246            stats["error"] = self.media_file.error
247        return stats
248
249    def get_summary(self) -> SummaryRow:
250        """
251        Return the before/after levels and the applied gain for the stream.
252
253        For EBU, the input level and true peak come from the first pass (or the
254        second pass in dynamic mode), and the output level, output true peak and
255        gain come from the second pass. For RMS and peak, the input level is the
256        measured RMS or peak level, and the output values are computed from the
257        applied gain. Values that are not available are None. The output_source
258        field labels these values; verification, when present, contains separate
259        measurements of the encoded output and the check results.
260
261        Returns:
262            dict: A dictionary with the summary values.
263        """
264        normalization_type = self.ffmpeg_normalize.normalization_type
265        status = self.media_file.status
266
267        input_level: float | None = None
268        input_peak: float | None = None
269        output_level: float | None = None
270        output_peak: float | None = None
271        gain: float | None = None
272
273        if normalization_type == "ebu":
274            pass1 = self.loudness_statistics["ebu_pass1"]
275            pass2 = self.loudness_statistics["ebu_pass2"]
276            input_stats = pass1 if pass1 is not None else pass2
277            if input_stats is not None:
278                input_level = float(input_stats["input_i"])
279                input_peak = float(input_stats["input_tp"])
280            if pass2 is not None:
281                output_level = float(pass2["output_i"])
282                output_peak = float(pass2["output_tp"])
283                # Input and output of the same pass, as the first pass input
284                # measurement can differ slightly from the second pass one
285                gain = output_level - float(pass2["input_i"])
286        else:
287            measured = (
288                self.loudness_statistics["mean"]
289                if normalization_type == "rms"
290                else self.loudness_statistics["max"]
291            )
292            if measured is not None:
293                input_level = float(measured)
294            if self.loudness_statistics["max"] is not None:
295                input_peak = float(self.loudness_statistics["max"])
296
297        applied_gain = 0.0 if status == "skipped" else self.applied_gain
298        if (
299            status != "error"
300            and output_level is None
301            and applied_gain is not None
302            and input_level is not None
303        ):
304            gain = applied_gain
305            output_level = input_level + applied_gain
306            if input_peak is not None:
307                output_peak = input_peak + applied_gain
308
309        if status == "error":
310            output_level = output_peak = gain = None
311
312        source = "unavailable"
313        if output_level is not None:
314            source = (
315                "input"
316                if status == "skipped"
317                else (
318                    "filter"
319                    if normalization_type == "ebu"
320                    and self.loudness_statistics["ebu_pass2"] is not None
321                    else "calculated"
322                )
323            )
324        summary: SummaryRow = {
325            "input_file": self.media_file.input_file,
326            "output_file": self.media_file.output_file,
327            "stream_id": self.stream_id,
328            "status": status,
329            "input_level": input_level,
330            "output_level": output_level,
331            "output_peak": output_peak,
332            "gain": gain,
333            "output_source": source,
334        }
335        if self.verification is not None:
336            summary["verification"] = self.verification
337        return summary
338
339    def set_second_pass_stats(self, stats: EbuLoudnessStatistics) -> None:
340        """
341        Set the EBU loudness statistics for the second pass.
342
343        Args:
344            stats (dict): The EBU loudness statistics.
345        """
346        _logger.debug(
347            f"Setting second pass stats for stream {self.stream_id} from {stats}"
348        )
349        self.loudness_statistics["ebu_pass2"] = stats
350
351    def get_pcm_codec(self) -> str:
352        """
353        Get the PCM codec string for the stream.
354
355        Returns:
356            str: The PCM codec string.
357        """
358        if not self.bit_depth:
359            return "pcm_s16le"
360        elif self.bit_depth <= 8:
361            return "pcm_s8"
362        elif self.bit_depth in [16, 24, 32, 64]:
363            return f"pcm_s{self.bit_depth}le"
364        else:
365            _logger.warning(
366                f"{self.media_file.input_file}: Unsupported bit depth {self.bit_depth}, falling back to pcm_s16le"
367            )
368            return "pcm_s16le"
369
370    def get_output_sample_fmt(self, codec: str | None) -> str | None:
371        """
372        Choose an output sample format for the given encoder that preserves the
373        detected input bit depth as closely as possible.
374
375        Used by the ``keep_bit_depth`` option (enabled by default) so that
376        encoders such as FLAC, which would otherwise pick their own default
377        sample format, retain the input bit depth. Only integer formats are
378        considered, and floating-point sources are left to the encoder, since
379        keeping bit depth is only meaningful for integer PCM sources.
380
381        Note that ffmpeg has no 24-bit sample format; 24-bit audio is carried in
382        the 32-bit ``s32`` format, and the encoder stores it accordingly.
383
384        Args:
385            codec: The output audio codec name, or None for the PCM default.
386
387        Returns:
388            str | None: The chosen sample format, or None if none should be set
389                (unknown bit depth, floating-point source, no explicit codec, no
390                encoder info, or an encoder without integer sample formats). In
391                all of these cases the encoder default is used.
392        """
393        if not self.bit_depth:
394            _logger.debug(
395                f"{self.media_file.input_file}: Could not determine input bit depth "
396                f"for stream {self.stream_id}; leaving the sample format to the encoder."
397            )
398            return None
399
400        if self.is_float:
401            # Pinning an integer sample format would silently convert a
402            # floating-point source to integer, so leave it to the encoder.
403            _logger.debug(
404                f"{self.media_file.input_file}: Stream {self.stream_id} is "
405                "floating-point; leaving the sample format to the encoder."
406            )
407            return None
408
409        if codec is None:
410            # The PCM default path already derives the bit depth from the input
411            # via get_pcm_codec(), so there is nothing to set here.
412            _logger.debug(
413                "keep_bit_depth has no effect for the default PCM output; the "
414                "input bit depth is already preserved."
415            )
416            return None
417
418        supported = get_encoder_sample_formats(codec)
419        if not supported:
420            _logger.debug(
421                f"Could not determine supported sample formats for codec '{codec}'; "
422                "not setting an explicit sample format."
423            )
424            return None
425
426        # Only consider integer formats, since keeping bit depth is meaningful
427        # for integer PCM sources (e.g. FLAC, ALAC).
428        int_formats = [
429            fmt
430            for fmt in supported
431            if fmt in _SAMPLE_FMT_INFO and not _SAMPLE_FMT_INFO[fmt][1]
432        ]
433        if not int_formats:
434            _logger.debug(
435                f"Encoder '{codec}' supports no integer sample formats; "
436                "leaving the sample format to the encoder."
437            )
438            return None
439
440        # Prefer the smallest integer format that holds at least the input bit
441        # depth; fall back to the largest available if none is big enough.
442        candidates = sorted(int_formats, key=lambda fmt: _SAMPLE_FMT_INFO[fmt][0])
443        for fmt in candidates:
444            if _SAMPLE_FMT_INFO[fmt][0] >= self.bit_depth:
445                return fmt
446        return candidates[-1]
447
448    def _get_filter_str_with_pre_filter(self, current_filter: str) -> str:
449        """
450        Get a filter string for current_filter, with the pre-filter
451        added before. Applies the input label before.
452
453        If a target channel count is set via ``audio_channels``, a channel
454        layout conversion is inserted before the analysis/normalization
455        filter so that measurements reflect the downmixed signal.
456
457        Args:
458            current_filter (str): The current filter.
459
460        Returns:
461            str: The filter string.
462        """
463        input_label = f"[0:{self.stream_id}]"
464        filter_chain = []
465        if self.media_file.ffmpeg_normalize.pre_filter:
466            filter_chain.append(self.media_file.ffmpeg_normalize.pre_filter)
467        channel_conversion = self._get_channel_conversion_filter()
468        if channel_conversion:
469            filter_chain.append(channel_conversion)
470        filter_chain.append(current_filter)
471        filter_str = input_label + ",".join(filter_chain)
472        return filter_str
473
474    def _get_channel_conversion_filter(self) -> str | None:
475        """
476        Return an ``aformat`` filter string that downmixes/upmixes to the
477        requested channel count, or None if no conversion is configured.
478
479        The ``Nc`` channel-layout notation matches ffmpeg's default layout
480        selection for ``-ac N``, so the analysis pass measures the same
481        signal that the output will contain.
482
483        A float planar sample format is requested so the downmix is not
484        attenuated to fit an integer range. This is what the analysis
485        measurement should reflect, since the volume gain is applied in
486        the filter graph (where samples are also float) before being
487        written to the output codec.
488        """
489        audio_channels = self.media_file.ffmpeg_normalize.audio_channels
490        if not audio_channels:
491            return None
492        return f"aformat=sample_fmts=fltp:channel_layouts={audio_channels}c"
493
494    def parse_astats(self) -> Iterator[float]:
495        """
496        Use ffmpeg with astats filter to get the mean (RMS) and max (peak) volume of the input file.
497
498        Yields:
499            float: The progress of the command.
500        """
501        _logger.info(f"Running first pass astats filter for stream {self.stream_id}")
502
503        filter_str = self._get_filter_str_with_pre_filter(
504            "astats=measure_overall=Peak_level+RMS_level:measure_perchannel=0"
505        )
506
507        cmd = [
508            self.media_file.ffmpeg_normalize.ffmpeg_exe,
509            "-hide_banner",
510            "-y",
511        ]
512
513        # Add extra input options if specified
514        if self.media_file.ffmpeg_normalize.extra_input_options:
515            cmd.extend(self.media_file.ffmpeg_normalize.extra_input_options)
516
517        cmd.extend(
518            [
519                "-i",
520                self.media_file.input_file,
521                "-filter_complex",
522                filter_str,
523                "-vn",
524                "-sn",
525                "-f",
526                "null",
527                os.devnull,
528            ]
529        )
530
531        cmd_runner = CommandRunner()
532        yield from cmd_runner.run_ffmpeg_command(cmd)
533        output = cmd_runner.get_output()
534
535        _logger.debug(
536            f"astats command output: {CommandRunner.prune_ffmpeg_progress_from_output(output)}"
537        )
538
539        mean_volume_matches = re.findall(r"RMS level dB: ([\-\d\.]+)", output)
540        if mean_volume_matches:
541            if mean_volume_matches[0] == "-":
542                self.loudness_statistics["mean"] = float("-inf")
543            else:
544                self.loudness_statistics["mean"] = float(mean_volume_matches[0])
545        else:
546            raise FFmpegNormalizeError(
547                f"Could not get mean volume for {self.media_file.input_file}"
548            )
549
550        max_volume_matches = re.findall(r"Peak level dB: ([\-\d\.]+)", output)
551        if max_volume_matches:
552            if max_volume_matches[0] == "-":
553                self.loudness_statistics["max"] = float("-inf")
554            else:
555                self.loudness_statistics["max"] = float(max_volume_matches[0])
556        else:
557            raise FFmpegNormalizeError(
558                f"Could not get max volume for {self.media_file.input_file}"
559            )
560
561    def parse_loudnorm_stats(self) -> Iterator[float]:
562        """
563        Run a first pass loudnorm filter to get measured data.
564
565        Yields:
566            float: The progress of the command.
567        """
568        _logger.info(f"Running first pass loudnorm filter for stream {self.stream_id}")
569
570        opts = {
571            "i": self.media_file.ffmpeg_normalize.target_level,
572            "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
573            "tp": self.media_file.ffmpeg_normalize.true_peak,
574            "offset": self.media_file.ffmpeg_normalize.offset,
575            "print_format": "json",
576        }
577
578        if self.media_file.ffmpeg_normalize.dual_mono:
579            opts["dual_mono"] = "true"
580
581        filter_str = self._get_filter_str_with_pre_filter(
582            "loudnorm=" + dict_to_filter_opts(opts)
583        )
584
585        cmd = [
586            self.media_file.ffmpeg_normalize.ffmpeg_exe,
587            "-hide_banner",
588            "-y",
589        ]
590
591        # Add extra input options if specified
592        if self.media_file.ffmpeg_normalize.extra_input_options:
593            cmd.extend(self.media_file.ffmpeg_normalize.extra_input_options)
594
595        cmd.extend(
596            [
597                "-i",
598                self.media_file.input_file,
599                "-map",
600                f"0:{self.stream_id}",
601                "-filter_complex",
602                filter_str,
603                "-vn",
604                "-sn",
605                "-f",
606                "null",
607                os.devnull,
608            ]
609        )
610
611        cmd_runner = CommandRunner()
612        yield from cmd_runner.run_ffmpeg_command(cmd)
613        output = cmd_runner.get_output()
614
615        _logger.debug(
616            f"Loudnorm first pass command output: {CommandRunner.prune_ffmpeg_progress_from_output(output)}"
617        )
618
619        # only one stream
620        self.loudness_statistics["ebu_pass1"] = next(
621            iter(AudioStream.prune_and_parse_loudnorm_output(output).values())
622        )
623
624    @staticmethod
625    def prune_and_parse_loudnorm_output(
626        output: str,
627    ) -> dict[int, EbuLoudnessStatistics]:
628        """
629        Prune ffmpeg progress lines from output and parse the loudnorm filter output.
630        There may be multiple outputs if multiple streams were processed.
631
632        Args:
633            output (str): The output from ffmpeg.
634
635        Returns:
636            dict[int, EbuLoudnessStatistics]: The EBU loudness statistics.
637        """
638        _logger.debug("Parsing loudnorm stats from output")
639        pruned_output = CommandRunner.prune_ffmpeg_progress_from_output(output)
640        output_lines = [line.strip() for line in pruned_output.split("\n")]
641        return AudioStream._parse_loudnorm_output(output_lines)
642
643    @staticmethod
644    def _parse_loudnorm_output(
645        output_lines: list[str],
646    ) -> dict[int, EbuLoudnessStatistics]:
647        """
648        Parse the output of a loudnorm filter to get the EBU loudness statistics.
649
650        Args:
651            output_lines (list[str]): The output lines of the loudnorm filter.
652
653        Raises:
654            FFmpegNormalizeError: When the output could not be parsed.
655
656        Returns:
657            dict[int, EbuLoudnessStatistics]: stream index and the EBU loudness statistics, if found.
658        """
659        result = dict[int, EbuLoudnessStatistics]()
660        stream_index = -1
661        loudnorm_start = 0
662        for index, line in enumerate(output_lines):
663            if stream_index < 0:
664                if m := _loudnorm_pattern.match(line):
665                    loudnorm_start = index + 1
666                    stream_index = int(m.group(1))
667            else:
668                if line.startswith("}"):
669                    loudnorm_end = index + 1
670                    loudnorm_data = "\n".join(output_lines[loudnorm_start:loudnorm_end])
671
672                    try:
673                        loudnorm_stats = json.loads(loudnorm_data)
674
675                        _logger.debug(
676                            f"Loudnorm stats for stream {stream_index} parsed: {loudnorm_data}"
677                        )
678
679                        for key in [
680                            "input_i",
681                            "input_tp",
682                            "input_lra",
683                            "input_thresh",
684                            "output_i",
685                            "output_tp",
686                            "output_lra",
687                            "output_thresh",
688                            "target_offset",
689                            "normalization_type",
690                        ]:
691                            if key not in loudnorm_stats:
692                                continue
693                            if key == "normalization_type":
694                                loudnorm_stats[key] = loudnorm_stats[key].lower()
695                            # handle infinite values
696                            elif float(loudnorm_stats[key]) == -float("inf"):
697                                loudnorm_stats[key] = -99
698                            elif float(loudnorm_stats[key]) == float("inf"):
699                                loudnorm_stats[key] = 0
700                            else:
701                                # convert to floats
702                                loudnorm_stats[key] = float(loudnorm_stats[key])
703
704                        result[stream_index] = cast(
705                            EbuLoudnessStatistics, loudnorm_stats
706                        )
707                        stream_index = -1
708                    except Exception as e:
709                        raise FFmpegNormalizeError(
710                            f"Could not parse loudnorm stats; wrong JSON format in string: {e}"
711                        )
712        return result
713
714    def get_second_pass_opts_ebu(self, batch_reference: float | None = None) -> str:
715        """
716        Return second pass loudnorm filter options string for ffmpeg
717
718        Args:
719            batch_reference (float | None, optional): Reference loudness for batch mode.
720                When provided, the target level is adjusted to preserve relative loudness.
721                Defaults to None.
722        """
723
724        # In dynamic mode, we can do everything in one pass, and we do not have first pass stats
725        if self.media_file.ffmpeg_normalize.dynamic:
726            if not self.ffmpeg_normalize.sample_rate:
727                _logger.warning(
728                    "In dynamic mode, the sample rate will automatically be set to 192 kHz by the loudnorm filter. "
729                    "Specify -ar/--sample-rate to override it."
730                )
731
732            opts = {
733                "i": self.media_file.ffmpeg_normalize.target_level,
734                "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
735                "tp": self.media_file.ffmpeg_normalize.true_peak,
736                "offset": self.media_file.ffmpeg_normalize.offset,
737                "linear": "false",
738                "print_format": "json",
739            }
740
741            if self.media_file.ffmpeg_normalize.dual_mono:
742                opts["dual_mono"] = "true"
743
744            self.verification_target_level = float(opts["i"])
745            return "loudnorm=" + dict_to_filter_opts(opts)
746
747        if not self.loudness_statistics["ebu_pass1"]:
748            raise FFmpegNormalizeError(
749                "First pass not run, you must call parse_loudnorm_stats first"
750            )
751
752        if float(self.loudness_statistics["ebu_pass1"]["input_i"]) > 0:
753            _logger.warning(
754                f"{self.media_file.input_file}: Input file had measured input loudness greater than zero "
755                f"({self.loudness_statistics['ebu_pass1']['input_i']}), capping at 0"
756            )
757            self.loudness_statistics["ebu_pass1"]["input_i"] = 0
758
759        will_use_dynamic_mode: bool = self.media_file.ffmpeg_normalize.dynamic
760
761        if self.media_file.ffmpeg_normalize.keep_loudness_range_target:
762            _logger.debug(
763                "Keeping target loudness range in second pass loudnorm filter"
764            )
765            input_lra = self.loudness_statistics["ebu_pass1"]["input_lra"]
766            if input_lra < 1 or input_lra > 50:
767                _logger.warning(
768                    f"{self.media_file.input_file}: Input file had measured loudness range outside of [1,50] "
769                    f"({input_lra}), capping to allowed range"
770                )
771
772            self.media_file.ffmpeg_normalize.loudness_range_target = self._constrain(
773                self.loudness_statistics["ebu_pass1"]["input_lra"], 1, 50
774            )
775
776        if self.media_file.ffmpeg_normalize.keep_lra_above_loudness_range_target:
777            if (
778                self.loudness_statistics["ebu_pass1"]["input_lra"]
779                <= self.media_file.ffmpeg_normalize.loudness_range_target
780            ):
781                _logger.debug(
782                    "Setting loudness range target in second pass loudnorm filter"
783                )
784            else:
785                self.media_file.ffmpeg_normalize.loudness_range_target = (
786                    self.loudness_statistics["ebu_pass1"]["input_lra"]
787                )
788                _logger.debug(
789                    "Keeping target loudness range in second pass loudnorm filter"
790                )
791
792        if (
793            self.media_file.ffmpeg_normalize.loudness_range_target
794            < self.loudness_statistics["ebu_pass1"]["input_lra"]
795            and not will_use_dynamic_mode
796        ):
797            _logger.warning(
798                f"{self.media_file.input_file}: Input file had loudness range of {self.loudness_statistics['ebu_pass1']['input_lra']}. "
799                f"This is larger than the loudness range target ({self.media_file.ffmpeg_normalize.loudness_range_target}). "
800                "Normalization will revert to dynamic mode. Choose a higher target loudness range if you want linear normalization. "
801                "Alternatively, use the --keep-loudness-range-target or --keep-lra-above-loudness-range-target option to keep the target loudness range from "
802                "the input."
803            )
804            will_use_dynamic_mode = True
805
806        if will_use_dynamic_mode and not self.ffmpeg_normalize.sample_rate:
807            _logger.warning(
808                "In dynamic mode, the sample rate will automatically be set to 192 kHz by the loudnorm filter. "
809                "Specify -ar/--sample-rate to override it."
810            )
811
812        target_level = self.ffmpeg_normalize.target_level
813        target_offset = self.loudness_statistics["ebu_pass1"]["target_offset"]
814        if self.ffmpeg_normalize.auto_lower_loudness_target:
815            safe_target = (
816                self.loudness_statistics["ebu_pass1"]["input_i"]
817                - self.loudness_statistics["ebu_pass1"]["input_tp"]
818                + self.ffmpeg_normalize.true_peak
819                - 0.1
820            )
821            if safe_target < self.ffmpeg_normalize.target_level:
822                target_level = safe_target
823                # The first-pass correction belongs to the original target.
824                # Reusing it at the lowered target adds unwanted gain when
825                # loudnorm falls back to dynamic mode (e.g. for zero LRA).
826                target_offset = 0.0
827                _logger.warning(
828                    f"{self.media_file.input_file}: Using loudness target {target_level:.2f} because --auto-lower-loudness-target given.",
829                )
830
831        stats = self.loudness_statistics["ebu_pass1"]
832
833        # Check if the true peak constraint will force dynamic mode.
834        # In linear mode, a uniform gain of (target - input_i) is applied.
835        # If that would leave the true peak above the TP limit, loudnorm
836        # cannot satisfy both constraints linearly and will fall back to
837        # dynamic processing.
838        if not will_use_dynamic_mode:
839            linear_gain = target_level - stats["input_i"]
840            estimated_tp = stats["input_tp"] + linear_gain
841            if estimated_tp > self.media_file.ffmpeg_normalize.true_peak:
842                min_tp = estimated_tp
843                max_target = (
844                    self.media_file.ffmpeg_normalize.true_peak
845                    - stats["input_tp"]
846                    + stats["input_i"]
847                )
848                _logger.warning(
849                    f"{self.media_file.input_file}: Linear normalization would result in an estimated true peak of "
850                    f"{estimated_tp:.2f} dBTP (input true peak {stats['input_tp']:.2f} dBTP + gain of {linear_gain:.2f} dB), "
851                    f"which exceeds the target true peak of {self.media_file.ffmpeg_normalize.true_peak} dBTP. "
852                    "The loudnorm filter will likely use dynamic mode instead. "
853                    f"To avoid this, raise --true-peak (-tp) to at least {min_tp:.1f}, "
854                    f"or lower the target level (-t) to at most {max_target:.1f}."
855                )
856
857        # Adjust target level for batch mode to preserve relative loudness
858        if batch_reference is not None:
859            input_i = float(stats["input_i"])
860            # Formula: adjusted_target = target_level + (input_i - batch_reference)
861            # If track is quieter than average (input_i < batch_ref), offset is negative → quieter target
862            # If track is louder than average (input_i > batch_ref), offset is positive → louder target
863            adjusted_target = target_level + (input_i - batch_reference)
864            _logger.info(
865                f"Batch mode: Adjusting target from {target_level:.2f} to {adjusted_target:.2f} LUFS "
866                f"(input_i={input_i:.2f}, batch_ref={batch_reference:.2f}, offset={input_i - batch_reference:.2f})"
867            )
868            target_level = adjusted_target
869
870        opts = {
871            "i": target_level,
872            "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
873            "tp": self.media_file.ffmpeg_normalize.true_peak,
874            "offset": self._constrain(target_offset, -99, 99, name="target_offset"),
875            "measured_i": self._constrain(stats["input_i"], -99, 0, name="input_i"),
876            "measured_lra": self._constrain(
877                stats["input_lra"], 0, 99, name="input_lra"
878            ),
879            "measured_tp": self._constrain(stats["input_tp"], -99, 99, name="input_tp"),
880            "measured_thresh": self._constrain(
881                stats["input_thresh"], -99, 0, name="input_thresh"
882            ),
883            "linear": "false" if self.media_file.ffmpeg_normalize.dynamic else "true",
884            "print_format": "json",
885        }
886
887        if self.media_file.ffmpeg_normalize.dual_mono:
888            opts["dual_mono"] = "true"
889
890        self.verification_target_level = target_level
891        return "loudnorm=" + dict_to_filter_opts(opts)
892
893    def get_second_pass_opts_peakrms(self, batch_reference: float | None = None) -> str:
894        """
895        Set the adjustment gain based on chosen option and mean/max volume,
896        return the matching ffmpeg volume filter.
897
898        Args:
899            batch_reference (float | None, optional): Reference loudness for batch mode.
900                When provided, the target level is adjusted to preserve relative loudness.
901                Defaults to None.
902
903        Returns:
904            str: ffmpeg volume filter string
905        """
906        if (
907            self.loudness_statistics["max"] is None
908            or self.loudness_statistics["mean"] is None
909        ):
910            raise FFmpegNormalizeError(
911                "First pass not run, no mean/max volume to normalize to"
912            )
913
914        normalization_type = self.media_file.ffmpeg_normalize.normalization_type
915        target_level = self.media_file.ffmpeg_normalize.target_level
916
917        # Adjust target level for batch mode to preserve relative loudness
918        if batch_reference is not None:
919            if normalization_type == "peak":
920                measured_level = float(self.loudness_statistics["max"])
921            elif normalization_type == "rms":
922                measured_level = float(self.loudness_statistics["mean"])
923            else:
924                raise FFmpegNormalizeError(
925                    "Can only set adjustment for peak and RMS normalization"
926                )
927
928            # Formula: adjusted_target = target_level + (measured_level - batch_reference)
929            # If track is quieter than average (measured < batch_ref), offset is negative → quieter target
930            # If track is louder than average (measured > batch_ref), offset is positive → louder target
931            adjusted_target = target_level + (measured_level - batch_reference)
932            _logger.info(
933                f"Batch mode: Adjusting target from {target_level:.2f} to {adjusted_target:.2f} dB "
934                f"(measured={measured_level:.2f}, batch_ref={batch_reference:.2f}, offset={measured_level - batch_reference:.2f})"
935            )
936            target_level = adjusted_target
937
938        if normalization_type == "peak":
939            adjustment = 0 + target_level - self.loudness_statistics["max"]
940        elif normalization_type == "rms":
941            adjustment = target_level - self.loudness_statistics["mean"]
942        else:
943            raise FFmpegNormalizeError(
944                "Can only set adjustment for peak and RMS normalization"
945            )
946
947        _logger.info(
948            f"Adjusting stream {self.stream_id} by {adjustment} dB to reach {target_level}"
949        )
950
951        self.applied_gain = float(adjustment)
952
953        clip_amount = self.loudness_statistics["max"] + adjustment
954        if clip_amount > 0:
955            _logger.warning(
956                f"{self.media_file.input_file}: Adjusting will lead to clipping of {clip_amount} dB"
957            )
958
959        return f"volume={adjustment}dB"
AudioStream( ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int, sample_rate: int | None, bit_depth: int | None, duration: float | None, is_default: bool = False, is_float: bool = False)
149    def __init__(
150        self,
151        ffmpeg_normalize: FFmpegNormalize,
152        media_file: MediaFile,
153        stream_id: int,
154        sample_rate: int | None,
155        bit_depth: int | None,
156        duration: float | None,
157        is_default: bool = False,
158        is_float: bool = False,
159    ):
160        """
161        Create an AudioStream object.
162
163        Args:
164            ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
165            media_file (MediaFile): The MediaFile object.
166            stream_id (int): The stream ID.
167            sample_rate (int): sample rate in Hz
168            bit_depth (int): bit depth in bits
169            duration (float): duration in seconds
170            is_default (bool): Whether this stream has the default disposition flag
171            is_float (bool): Whether the stream uses a floating-point sample format
172        """
173        super().__init__(ffmpeg_normalize, media_file, "audio", stream_id)
174
175        self.loudness_statistics: LoudnessStatistics = {
176            "ebu_pass1": None,
177            "ebu_pass2": None,
178            "mean": None,
179            "max": None,
180        }
181
182        # Gain in dB applied by the second pass volume filter (peak/RMS), or 0
183        # when normalization is skipped for this stream (e.g. with lower_only).
184        # Stays None for EBU, where the gain is derived from the second pass stats.
185        self.applied_gain: float | None = None
186        self.verification_target_level: float | None = None
187        self.verification: VerificationResult | None = None
188
189        self.sample_rate = sample_rate
190        self.bit_depth = bit_depth
191
192        self.duration = duration
193        self.is_default = is_default
194        self.is_float = is_float

Create an AudioStream object.

Arguments:
  • ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
  • media_file (MediaFile): The MediaFile object.
  • stream_id (int): The stream ID.
  • sample_rate (int): sample rate in Hz
  • bit_depth (int): bit depth in bits
  • duration (float): duration in seconds
  • is_default (bool): Whether this stream has the default disposition flag
  • is_float (bool): Whether the stream uses a floating-point sample format
loudness_statistics: ffmpeg_normalize._streams.LoudnessStatistics
applied_gain: float | None
verification_target_level: float | None
verification: ffmpeg_normalize._streams.VerificationResult | None
sample_rate
bit_depth
duration
is_default
is_float
def get_stats(self) -> ffmpeg_normalize._streams.LoudnessStatisticsWithMetadata:
224    def get_stats(self) -> LoudnessStatisticsWithMetadata:
225        """
226        Return loudness statistics for the stream.
227
228        Returns:
229            dict: A dictionary containing the loudness statistics.
230        """
231        stats: LoudnessStatisticsWithMetadata = {
232            "input_file": self.media_file.input_file,
233            "output_file": self.media_file.output_file,
234            "stream_id": self.stream_id,
235            "ebu_pass1": self.loudness_statistics["ebu_pass1"],
236            "ebu_pass2": self.loudness_statistics["ebu_pass2"],
237            "mean": self.loudness_statistics["mean"],
238            "max": self.loudness_statistics["max"],
239            "status": self.media_file.status,
240        }
241        if self.verification is not None:
242            stats["verification"] = self.verification
243        # Only present when the file failed to process, per the per-file outcome
244        # reporting (status is "error").
245        if self.media_file.error is not None:
246            stats["error"] = self.media_file.error
247        return stats

Return loudness statistics for the stream.

Returns:

dict: A dictionary containing the loudness statistics.

def get_summary(self) -> ffmpeg_normalize._streams.SummaryRow:
249    def get_summary(self) -> SummaryRow:
250        """
251        Return the before/after levels and the applied gain for the stream.
252
253        For EBU, the input level and true peak come from the first pass (or the
254        second pass in dynamic mode), and the output level, output true peak and
255        gain come from the second pass. For RMS and peak, the input level is the
256        measured RMS or peak level, and the output values are computed from the
257        applied gain. Values that are not available are None. The output_source
258        field labels these values; verification, when present, contains separate
259        measurements of the encoded output and the check results.
260
261        Returns:
262            dict: A dictionary with the summary values.
263        """
264        normalization_type = self.ffmpeg_normalize.normalization_type
265        status = self.media_file.status
266
267        input_level: float | None = None
268        input_peak: float | None = None
269        output_level: float | None = None
270        output_peak: float | None = None
271        gain: float | None = None
272
273        if normalization_type == "ebu":
274            pass1 = self.loudness_statistics["ebu_pass1"]
275            pass2 = self.loudness_statistics["ebu_pass2"]
276            input_stats = pass1 if pass1 is not None else pass2
277            if input_stats is not None:
278                input_level = float(input_stats["input_i"])
279                input_peak = float(input_stats["input_tp"])
280            if pass2 is not None:
281                output_level = float(pass2["output_i"])
282                output_peak = float(pass2["output_tp"])
283                # Input and output of the same pass, as the first pass input
284                # measurement can differ slightly from the second pass one
285                gain = output_level - float(pass2["input_i"])
286        else:
287            measured = (
288                self.loudness_statistics["mean"]
289                if normalization_type == "rms"
290                else self.loudness_statistics["max"]
291            )
292            if measured is not None:
293                input_level = float(measured)
294            if self.loudness_statistics["max"] is not None:
295                input_peak = float(self.loudness_statistics["max"])
296
297        applied_gain = 0.0 if status == "skipped" else self.applied_gain
298        if (
299            status != "error"
300            and output_level is None
301            and applied_gain is not None
302            and input_level is not None
303        ):
304            gain = applied_gain
305            output_level = input_level + applied_gain
306            if input_peak is not None:
307                output_peak = input_peak + applied_gain
308
309        if status == "error":
310            output_level = output_peak = gain = None
311
312        source = "unavailable"
313        if output_level is not None:
314            source = (
315                "input"
316                if status == "skipped"
317                else (
318                    "filter"
319                    if normalization_type == "ebu"
320                    and self.loudness_statistics["ebu_pass2"] is not None
321                    else "calculated"
322                )
323            )
324        summary: SummaryRow = {
325            "input_file": self.media_file.input_file,
326            "output_file": self.media_file.output_file,
327            "stream_id": self.stream_id,
328            "status": status,
329            "input_level": input_level,
330            "output_level": output_level,
331            "output_peak": output_peak,
332            "gain": gain,
333            "output_source": source,
334        }
335        if self.verification is not None:
336            summary["verification"] = self.verification
337        return summary

Return the before/after levels and the applied gain for the stream.

For EBU, the input level and true peak come from the first pass (or the second pass in dynamic mode), and the output level, output true peak and gain come from the second pass. For RMS and peak, the input level is the measured RMS or peak level, and the output values are computed from the applied gain. Values that are not available are None. The output_source field labels these values; verification, when present, contains separate measurements of the encoded output and the check results.

Returns:

dict: A dictionary with the summary values.

def set_second_pass_stats(self, stats: ffmpeg_normalize._streams.EbuLoudnessStatistics) -> None:
339    def set_second_pass_stats(self, stats: EbuLoudnessStatistics) -> None:
340        """
341        Set the EBU loudness statistics for the second pass.
342
343        Args:
344            stats (dict): The EBU loudness statistics.
345        """
346        _logger.debug(
347            f"Setting second pass stats for stream {self.stream_id} from {stats}"
348        )
349        self.loudness_statistics["ebu_pass2"] = stats

Set the EBU loudness statistics for the second pass.

Arguments:
  • stats (dict): The EBU loudness statistics.
def get_pcm_codec(self) -> str:
351    def get_pcm_codec(self) -> str:
352        """
353        Get the PCM codec string for the stream.
354
355        Returns:
356            str: The PCM codec string.
357        """
358        if not self.bit_depth:
359            return "pcm_s16le"
360        elif self.bit_depth <= 8:
361            return "pcm_s8"
362        elif self.bit_depth in [16, 24, 32, 64]:
363            return f"pcm_s{self.bit_depth}le"
364        else:
365            _logger.warning(
366                f"{self.media_file.input_file}: Unsupported bit depth {self.bit_depth}, falling back to pcm_s16le"
367            )
368            return "pcm_s16le"

Get the PCM codec string for the stream.

Returns:

str: The PCM codec string.

def get_output_sample_fmt(self, codec: str | None) -> str | None:
370    def get_output_sample_fmt(self, codec: str | None) -> str | None:
371        """
372        Choose an output sample format for the given encoder that preserves the
373        detected input bit depth as closely as possible.
374
375        Used by the ``keep_bit_depth`` option (enabled by default) so that
376        encoders such as FLAC, which would otherwise pick their own default
377        sample format, retain the input bit depth. Only integer formats are
378        considered, and floating-point sources are left to the encoder, since
379        keeping bit depth is only meaningful for integer PCM sources.
380
381        Note that ffmpeg has no 24-bit sample format; 24-bit audio is carried in
382        the 32-bit ``s32`` format, and the encoder stores it accordingly.
383
384        Args:
385            codec: The output audio codec name, or None for the PCM default.
386
387        Returns:
388            str | None: The chosen sample format, or None if none should be set
389                (unknown bit depth, floating-point source, no explicit codec, no
390                encoder info, or an encoder without integer sample formats). In
391                all of these cases the encoder default is used.
392        """
393        if not self.bit_depth:
394            _logger.debug(
395                f"{self.media_file.input_file}: Could not determine input bit depth "
396                f"for stream {self.stream_id}; leaving the sample format to the encoder."
397            )
398            return None
399
400        if self.is_float:
401            # Pinning an integer sample format would silently convert a
402            # floating-point source to integer, so leave it to the encoder.
403            _logger.debug(
404                f"{self.media_file.input_file}: Stream {self.stream_id} is "
405                "floating-point; leaving the sample format to the encoder."
406            )
407            return None
408
409        if codec is None:
410            # The PCM default path already derives the bit depth from the input
411            # via get_pcm_codec(), so there is nothing to set here.
412            _logger.debug(
413                "keep_bit_depth has no effect for the default PCM output; the "
414                "input bit depth is already preserved."
415            )
416            return None
417
418        supported = get_encoder_sample_formats(codec)
419        if not supported:
420            _logger.debug(
421                f"Could not determine supported sample formats for codec '{codec}'; "
422                "not setting an explicit sample format."
423            )
424            return None
425
426        # Only consider integer formats, since keeping bit depth is meaningful
427        # for integer PCM sources (e.g. FLAC, ALAC).
428        int_formats = [
429            fmt
430            for fmt in supported
431            if fmt in _SAMPLE_FMT_INFO and not _SAMPLE_FMT_INFO[fmt][1]
432        ]
433        if not int_formats:
434            _logger.debug(
435                f"Encoder '{codec}' supports no integer sample formats; "
436                "leaving the sample format to the encoder."
437            )
438            return None
439
440        # Prefer the smallest integer format that holds at least the input bit
441        # depth; fall back to the largest available if none is big enough.
442        candidates = sorted(int_formats, key=lambda fmt: _SAMPLE_FMT_INFO[fmt][0])
443        for fmt in candidates:
444            if _SAMPLE_FMT_INFO[fmt][0] >= self.bit_depth:
445                return fmt
446        return candidates[-1]

Choose an output sample format for the given encoder that preserves the detected input bit depth as closely as possible.

Used by the keep_bit_depth option (enabled by default) so that encoders such as FLAC, which would otherwise pick their own default sample format, retain the input bit depth. Only integer formats are considered, and floating-point sources are left to the encoder, since keeping bit depth is only meaningful for integer PCM sources.

Note that ffmpeg has no 24-bit sample format; 24-bit audio is carried in the 32-bit s32 format, and the encoder stores it accordingly.

Arguments:
  • codec: The output audio codec name, or None for the PCM default.
Returns:

str | None: The chosen sample format, or None if none should be set (unknown bit depth, floating-point source, no explicit codec, no encoder info, or an encoder without integer sample formats). In all of these cases the encoder default is used.

def parse_astats(self) -> Iterator[float]:
494    def parse_astats(self) -> Iterator[float]:
495        """
496        Use ffmpeg with astats filter to get the mean (RMS) and max (peak) volume of the input file.
497
498        Yields:
499            float: The progress of the command.
500        """
501        _logger.info(f"Running first pass astats filter for stream {self.stream_id}")
502
503        filter_str = self._get_filter_str_with_pre_filter(
504            "astats=measure_overall=Peak_level+RMS_level:measure_perchannel=0"
505        )
506
507        cmd = [
508            self.media_file.ffmpeg_normalize.ffmpeg_exe,
509            "-hide_banner",
510            "-y",
511        ]
512
513        # Add extra input options if specified
514        if self.media_file.ffmpeg_normalize.extra_input_options:
515            cmd.extend(self.media_file.ffmpeg_normalize.extra_input_options)
516
517        cmd.extend(
518            [
519                "-i",
520                self.media_file.input_file,
521                "-filter_complex",
522                filter_str,
523                "-vn",
524                "-sn",
525                "-f",
526                "null",
527                os.devnull,
528            ]
529        )
530
531        cmd_runner = CommandRunner()
532        yield from cmd_runner.run_ffmpeg_command(cmd)
533        output = cmd_runner.get_output()
534
535        _logger.debug(
536            f"astats command output: {CommandRunner.prune_ffmpeg_progress_from_output(output)}"
537        )
538
539        mean_volume_matches = re.findall(r"RMS level dB: ([\-\d\.]+)", output)
540        if mean_volume_matches:
541            if mean_volume_matches[0] == "-":
542                self.loudness_statistics["mean"] = float("-inf")
543            else:
544                self.loudness_statistics["mean"] = float(mean_volume_matches[0])
545        else:
546            raise FFmpegNormalizeError(
547                f"Could not get mean volume for {self.media_file.input_file}"
548            )
549
550        max_volume_matches = re.findall(r"Peak level dB: ([\-\d\.]+)", output)
551        if max_volume_matches:
552            if max_volume_matches[0] == "-":
553                self.loudness_statistics["max"] = float("-inf")
554            else:
555                self.loudness_statistics["max"] = float(max_volume_matches[0])
556        else:
557            raise FFmpegNormalizeError(
558                f"Could not get max volume for {self.media_file.input_file}"
559            )

Use ffmpeg with astats filter to get the mean (RMS) and max (peak) volume of the input file.

Yields:

float: The progress of the command.

def parse_loudnorm_stats(self) -> Iterator[float]:
561    def parse_loudnorm_stats(self) -> Iterator[float]:
562        """
563        Run a first pass loudnorm filter to get measured data.
564
565        Yields:
566            float: The progress of the command.
567        """
568        _logger.info(f"Running first pass loudnorm filter for stream {self.stream_id}")
569
570        opts = {
571            "i": self.media_file.ffmpeg_normalize.target_level,
572            "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
573            "tp": self.media_file.ffmpeg_normalize.true_peak,
574            "offset": self.media_file.ffmpeg_normalize.offset,
575            "print_format": "json",
576        }
577
578        if self.media_file.ffmpeg_normalize.dual_mono:
579            opts["dual_mono"] = "true"
580
581        filter_str = self._get_filter_str_with_pre_filter(
582            "loudnorm=" + dict_to_filter_opts(opts)
583        )
584
585        cmd = [
586            self.media_file.ffmpeg_normalize.ffmpeg_exe,
587            "-hide_banner",
588            "-y",
589        ]
590
591        # Add extra input options if specified
592        if self.media_file.ffmpeg_normalize.extra_input_options:
593            cmd.extend(self.media_file.ffmpeg_normalize.extra_input_options)
594
595        cmd.extend(
596            [
597                "-i",
598                self.media_file.input_file,
599                "-map",
600                f"0:{self.stream_id}",
601                "-filter_complex",
602                filter_str,
603                "-vn",
604                "-sn",
605                "-f",
606                "null",
607                os.devnull,
608            ]
609        )
610
611        cmd_runner = CommandRunner()
612        yield from cmd_runner.run_ffmpeg_command(cmd)
613        output = cmd_runner.get_output()
614
615        _logger.debug(
616            f"Loudnorm first pass command output: {CommandRunner.prune_ffmpeg_progress_from_output(output)}"
617        )
618
619        # only one stream
620        self.loudness_statistics["ebu_pass1"] = next(
621            iter(AudioStream.prune_and_parse_loudnorm_output(output).values())
622        )

Run a first pass loudnorm filter to get measured data.

Yields:

float: The progress of the command.

@staticmethod
def prune_and_parse_loudnorm_output( output: str) -> dict[int, ffmpeg_normalize._streams.EbuLoudnessStatistics]:
624    @staticmethod
625    def prune_and_parse_loudnorm_output(
626        output: str,
627    ) -> dict[int, EbuLoudnessStatistics]:
628        """
629        Prune ffmpeg progress lines from output and parse the loudnorm filter output.
630        There may be multiple outputs if multiple streams were processed.
631
632        Args:
633            output (str): The output from ffmpeg.
634
635        Returns:
636            dict[int, EbuLoudnessStatistics]: The EBU loudness statistics.
637        """
638        _logger.debug("Parsing loudnorm stats from output")
639        pruned_output = CommandRunner.prune_ffmpeg_progress_from_output(output)
640        output_lines = [line.strip() for line in pruned_output.split("\n")]
641        return AudioStream._parse_loudnorm_output(output_lines)

Prune ffmpeg progress lines from output and parse the loudnorm filter output. There may be multiple outputs if multiple streams were processed.

Arguments:
  • output (str): The output from ffmpeg.
Returns:

dict[int, EbuLoudnessStatistics]: The EBU loudness statistics.

def get_second_pass_opts_ebu(self, batch_reference: float | None = None) -> str:
714    def get_second_pass_opts_ebu(self, batch_reference: float | None = None) -> str:
715        """
716        Return second pass loudnorm filter options string for ffmpeg
717
718        Args:
719            batch_reference (float | None, optional): Reference loudness for batch mode.
720                When provided, the target level is adjusted to preserve relative loudness.
721                Defaults to None.
722        """
723
724        # In dynamic mode, we can do everything in one pass, and we do not have first pass stats
725        if self.media_file.ffmpeg_normalize.dynamic:
726            if not self.ffmpeg_normalize.sample_rate:
727                _logger.warning(
728                    "In dynamic mode, the sample rate will automatically be set to 192 kHz by the loudnorm filter. "
729                    "Specify -ar/--sample-rate to override it."
730                )
731
732            opts = {
733                "i": self.media_file.ffmpeg_normalize.target_level,
734                "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
735                "tp": self.media_file.ffmpeg_normalize.true_peak,
736                "offset": self.media_file.ffmpeg_normalize.offset,
737                "linear": "false",
738                "print_format": "json",
739            }
740
741            if self.media_file.ffmpeg_normalize.dual_mono:
742                opts["dual_mono"] = "true"
743
744            self.verification_target_level = float(opts["i"])
745            return "loudnorm=" + dict_to_filter_opts(opts)
746
747        if not self.loudness_statistics["ebu_pass1"]:
748            raise FFmpegNormalizeError(
749                "First pass not run, you must call parse_loudnorm_stats first"
750            )
751
752        if float(self.loudness_statistics["ebu_pass1"]["input_i"]) > 0:
753            _logger.warning(
754                f"{self.media_file.input_file}: Input file had measured input loudness greater than zero "
755                f"({self.loudness_statistics['ebu_pass1']['input_i']}), capping at 0"
756            )
757            self.loudness_statistics["ebu_pass1"]["input_i"] = 0
758
759        will_use_dynamic_mode: bool = self.media_file.ffmpeg_normalize.dynamic
760
761        if self.media_file.ffmpeg_normalize.keep_loudness_range_target:
762            _logger.debug(
763                "Keeping target loudness range in second pass loudnorm filter"
764            )
765            input_lra = self.loudness_statistics["ebu_pass1"]["input_lra"]
766            if input_lra < 1 or input_lra > 50:
767                _logger.warning(
768                    f"{self.media_file.input_file}: Input file had measured loudness range outside of [1,50] "
769                    f"({input_lra}), capping to allowed range"
770                )
771
772            self.media_file.ffmpeg_normalize.loudness_range_target = self._constrain(
773                self.loudness_statistics["ebu_pass1"]["input_lra"], 1, 50
774            )
775
776        if self.media_file.ffmpeg_normalize.keep_lra_above_loudness_range_target:
777            if (
778                self.loudness_statistics["ebu_pass1"]["input_lra"]
779                <= self.media_file.ffmpeg_normalize.loudness_range_target
780            ):
781                _logger.debug(
782                    "Setting loudness range target in second pass loudnorm filter"
783                )
784            else:
785                self.media_file.ffmpeg_normalize.loudness_range_target = (
786                    self.loudness_statistics["ebu_pass1"]["input_lra"]
787                )
788                _logger.debug(
789                    "Keeping target loudness range in second pass loudnorm filter"
790                )
791
792        if (
793            self.media_file.ffmpeg_normalize.loudness_range_target
794            < self.loudness_statistics["ebu_pass1"]["input_lra"]
795            and not will_use_dynamic_mode
796        ):
797            _logger.warning(
798                f"{self.media_file.input_file}: Input file had loudness range of {self.loudness_statistics['ebu_pass1']['input_lra']}. "
799                f"This is larger than the loudness range target ({self.media_file.ffmpeg_normalize.loudness_range_target}). "
800                "Normalization will revert to dynamic mode. Choose a higher target loudness range if you want linear normalization. "
801                "Alternatively, use the --keep-loudness-range-target or --keep-lra-above-loudness-range-target option to keep the target loudness range from "
802                "the input."
803            )
804            will_use_dynamic_mode = True
805
806        if will_use_dynamic_mode and not self.ffmpeg_normalize.sample_rate:
807            _logger.warning(
808                "In dynamic mode, the sample rate will automatically be set to 192 kHz by the loudnorm filter. "
809                "Specify -ar/--sample-rate to override it."
810            )
811
812        target_level = self.ffmpeg_normalize.target_level
813        target_offset = self.loudness_statistics["ebu_pass1"]["target_offset"]
814        if self.ffmpeg_normalize.auto_lower_loudness_target:
815            safe_target = (
816                self.loudness_statistics["ebu_pass1"]["input_i"]
817                - self.loudness_statistics["ebu_pass1"]["input_tp"]
818                + self.ffmpeg_normalize.true_peak
819                - 0.1
820            )
821            if safe_target < self.ffmpeg_normalize.target_level:
822                target_level = safe_target
823                # The first-pass correction belongs to the original target.
824                # Reusing it at the lowered target adds unwanted gain when
825                # loudnorm falls back to dynamic mode (e.g. for zero LRA).
826                target_offset = 0.0
827                _logger.warning(
828                    f"{self.media_file.input_file}: Using loudness target {target_level:.2f} because --auto-lower-loudness-target given.",
829                )
830
831        stats = self.loudness_statistics["ebu_pass1"]
832
833        # Check if the true peak constraint will force dynamic mode.
834        # In linear mode, a uniform gain of (target - input_i) is applied.
835        # If that would leave the true peak above the TP limit, loudnorm
836        # cannot satisfy both constraints linearly and will fall back to
837        # dynamic processing.
838        if not will_use_dynamic_mode:
839            linear_gain = target_level - stats["input_i"]
840            estimated_tp = stats["input_tp"] + linear_gain
841            if estimated_tp > self.media_file.ffmpeg_normalize.true_peak:
842                min_tp = estimated_tp
843                max_target = (
844                    self.media_file.ffmpeg_normalize.true_peak
845                    - stats["input_tp"]
846                    + stats["input_i"]
847                )
848                _logger.warning(
849                    f"{self.media_file.input_file}: Linear normalization would result in an estimated true peak of "
850                    f"{estimated_tp:.2f} dBTP (input true peak {stats['input_tp']:.2f} dBTP + gain of {linear_gain:.2f} dB), "
851                    f"which exceeds the target true peak of {self.media_file.ffmpeg_normalize.true_peak} dBTP. "
852                    "The loudnorm filter will likely use dynamic mode instead. "
853                    f"To avoid this, raise --true-peak (-tp) to at least {min_tp:.1f}, "
854                    f"or lower the target level (-t) to at most {max_target:.1f}."
855                )
856
857        # Adjust target level for batch mode to preserve relative loudness
858        if batch_reference is not None:
859            input_i = float(stats["input_i"])
860            # Formula: adjusted_target = target_level + (input_i - batch_reference)
861            # If track is quieter than average (input_i < batch_ref), offset is negative → quieter target
862            # If track is louder than average (input_i > batch_ref), offset is positive → louder target
863            adjusted_target = target_level + (input_i - batch_reference)
864            _logger.info(
865                f"Batch mode: Adjusting target from {target_level:.2f} to {adjusted_target:.2f} LUFS "
866                f"(input_i={input_i:.2f}, batch_ref={batch_reference:.2f}, offset={input_i - batch_reference:.2f})"
867            )
868            target_level = adjusted_target
869
870        opts = {
871            "i": target_level,
872            "lra": self.media_file.ffmpeg_normalize.loudness_range_target,
873            "tp": self.media_file.ffmpeg_normalize.true_peak,
874            "offset": self._constrain(target_offset, -99, 99, name="target_offset"),
875            "measured_i": self._constrain(stats["input_i"], -99, 0, name="input_i"),
876            "measured_lra": self._constrain(
877                stats["input_lra"], 0, 99, name="input_lra"
878            ),
879            "measured_tp": self._constrain(stats["input_tp"], -99, 99, name="input_tp"),
880            "measured_thresh": self._constrain(
881                stats["input_thresh"], -99, 0, name="input_thresh"
882            ),
883            "linear": "false" if self.media_file.ffmpeg_normalize.dynamic else "true",
884            "print_format": "json",
885        }
886
887        if self.media_file.ffmpeg_normalize.dual_mono:
888            opts["dual_mono"] = "true"
889
890        self.verification_target_level = target_level
891        return "loudnorm=" + dict_to_filter_opts(opts)

Return second pass loudnorm filter options string for ffmpeg

Arguments:
  • batch_reference (float | None, optional): Reference loudness for batch mode. When provided, the target level is adjusted to preserve relative loudness. Defaults to None.
def get_second_pass_opts_peakrms(self, batch_reference: float | None = None) -> str:
893    def get_second_pass_opts_peakrms(self, batch_reference: float | None = None) -> str:
894        """
895        Set the adjustment gain based on chosen option and mean/max volume,
896        return the matching ffmpeg volume filter.
897
898        Args:
899            batch_reference (float | None, optional): Reference loudness for batch mode.
900                When provided, the target level is adjusted to preserve relative loudness.
901                Defaults to None.
902
903        Returns:
904            str: ffmpeg volume filter string
905        """
906        if (
907            self.loudness_statistics["max"] is None
908            or self.loudness_statistics["mean"] is None
909        ):
910            raise FFmpegNormalizeError(
911                "First pass not run, no mean/max volume to normalize to"
912            )
913
914        normalization_type = self.media_file.ffmpeg_normalize.normalization_type
915        target_level = self.media_file.ffmpeg_normalize.target_level
916
917        # Adjust target level for batch mode to preserve relative loudness
918        if batch_reference is not None:
919            if normalization_type == "peak":
920                measured_level = float(self.loudness_statistics["max"])
921            elif normalization_type == "rms":
922                measured_level = float(self.loudness_statistics["mean"])
923            else:
924                raise FFmpegNormalizeError(
925                    "Can only set adjustment for peak and RMS normalization"
926                )
927
928            # Formula: adjusted_target = target_level + (measured_level - batch_reference)
929            # If track is quieter than average (measured < batch_ref), offset is negative → quieter target
930            # If track is louder than average (measured > batch_ref), offset is positive → louder target
931            adjusted_target = target_level + (measured_level - batch_reference)
932            _logger.info(
933                f"Batch mode: Adjusting target from {target_level:.2f} to {adjusted_target:.2f} dB "
934                f"(measured={measured_level:.2f}, batch_ref={batch_reference:.2f}, offset={measured_level - batch_reference:.2f})"
935            )
936            target_level = adjusted_target
937
938        if normalization_type == "peak":
939            adjustment = 0 + target_level - self.loudness_statistics["max"]
940        elif normalization_type == "rms":
941            adjustment = target_level - self.loudness_statistics["mean"]
942        else:
943            raise FFmpegNormalizeError(
944                "Can only set adjustment for peak and RMS normalization"
945            )
946
947        _logger.info(
948            f"Adjusting stream {self.stream_id} by {adjustment} dB to reach {target_level}"
949        )
950
951        self.applied_gain = float(adjustment)
952
953        clip_amount = self.loudness_statistics["max"] + adjustment
954        if clip_amount > 0:
955            _logger.warning(
956                f"{self.media_file.input_file}: Adjusting will lead to clipping of {clip_amount} dB"
957            )
958
959        return f"volume={adjustment}dB"

Set the adjustment gain based on chosen option and mean/max volume, return the matching ffmpeg volume filter.

Arguments:
  • batch_reference (float | None, optional): Reference loudness for batch mode. When provided, the target level is adjusted to preserve relative loudness. Defaults to None.
Returns:

str: ffmpeg volume filter string

class VideoStream(ffmpeg_normalize.MediaStream):
134class VideoStream(MediaStream):
135    def __init__(
136        self, ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int
137    ):
138        super().__init__(ffmpeg_normalize, media_file, "video", stream_id)
VideoStream( ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int)
135    def __init__(
136        self, ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int
137    ):
138        super().__init__(ffmpeg_normalize, media_file, "video", stream_id)

Create a MediaStream object.

Arguments:
  • ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
  • media_file (MediaFile): The MediaFile object.
  • stream_type (Literal["audio", "video", "subtitle"]): The type of the stream.
  • stream_id (int): The stream ID.
class SubtitleStream(ffmpeg_normalize.MediaStream):
141class SubtitleStream(MediaStream):
142    def __init__(
143        self, ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int
144    ):
145        super().__init__(ffmpeg_normalize, media_file, "subtitle", stream_id)
SubtitleStream( ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int)
142    def __init__(
143        self, ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_id: int
144    ):
145        super().__init__(ffmpeg_normalize, media_file, "subtitle", stream_id)

Create a MediaStream object.

Arguments:
  • ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
  • media_file (MediaFile): The MediaFile object.
  • stream_type (Literal["audio", "video", "subtitle"]): The type of the stream.
  • stream_id (int): The stream ID.
class MediaStream:
102class MediaStream:
103    def __init__(
104        self,
105        ffmpeg_normalize: FFmpegNormalize,
106        media_file: MediaFile,
107        stream_type: Literal["audio", "video", "subtitle"],
108        stream_id: int,
109    ):
110        """
111        Create a MediaStream object.
112
113        Args:
114            ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
115            media_file (MediaFile): The MediaFile object.
116            stream_type (Literal["audio", "video", "subtitle"]): The type of the stream.
117            stream_id (int): The stream ID.
118        """
119        self.ffmpeg_normalize = ffmpeg_normalize
120        self.media_file = media_file
121        self.stream_type = stream_type
122        self.stream_id = stream_id
123        _logger.debug(
124            f"Created MediaStream for {self.media_file.input_file}, {self.stream_type} stream {self.stream_id}"
125        )
126
127    def __repr__(self) -> str:
128        return (
129            f"<{os.path.basename(self.media_file.input_file)}, "
130            f"{self.stream_type} stream {self.stream_id}>"
131        )
MediaStream( ffmpeg_normalize: FFmpegNormalize, media_file: MediaFile, stream_type: Literal['audio', 'video', 'subtitle'], stream_id: int)
103    def __init__(
104        self,
105        ffmpeg_normalize: FFmpegNormalize,
106        media_file: MediaFile,
107        stream_type: Literal["audio", "video", "subtitle"],
108        stream_id: int,
109    ):
110        """
111        Create a MediaStream object.
112
113        Args:
114            ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
115            media_file (MediaFile): The MediaFile object.
116            stream_type (Literal["audio", "video", "subtitle"]): The type of the stream.
117            stream_id (int): The stream ID.
118        """
119        self.ffmpeg_normalize = ffmpeg_normalize
120        self.media_file = media_file
121        self.stream_type = stream_type
122        self.stream_id = stream_id
123        _logger.debug(
124            f"Created MediaStream for {self.media_file.input_file}, {self.stream_type} stream {self.stream_id}"
125        )

Create a MediaStream object.

Arguments:
  • ffmpeg_normalize (FFmpegNormalize): The FFmpegNormalize object.
  • media_file (MediaFile): The MediaFile object.
  • stream_type (Literal["audio", "video", "subtitle"]): The type of the stream.
  • stream_id (int): The stream ID.
ffmpeg_normalize
media_file
stream_type
stream_id
@contextmanager
def ffmpeg_env(env: dict[str, str] | None) -> Iterator[NoneType]:
26@contextmanager
27def ffmpeg_env(env: dict[str, str] | None) -> Iterator[None]:
28    """
29    Temporarily set the environment for subprocess.Popen.
30
31    Args:
32        env: Environment dict to pass to subprocess.Popen.
33    """
34    token = _ffmpeg_env_var.set(env)
35    try:
36        yield
37    finally:
38        _ffmpeg_env_var.reset(token)

Temporarily set the environment for subprocess.Popen.

Arguments:
  • env: Environment dict to pass to subprocess.Popen.
__version__ = '1.44.1'