ffmpeg-normalize 1.32.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ from ._errors import FFmpegNormalizeError
2
+ from ._ffmpeg_normalize import FFmpegNormalize
3
+ from ._media_file import MediaFile
4
+ from ._streams import AudioStream, MediaStream, SubtitleStream, VideoStream
5
+ from ._version import __version__
6
+
7
+ __module_name__ = "ffmpeg_normalize"
8
+
9
+ __all__ = [
10
+ "FFmpegNormalize",
11
+ "FFmpegNormalizeError",
12
+ "MediaFile",
13
+ "AudioStream",
14
+ "VideoStream",
15
+ "SubtitleStream",
16
+ "MediaStream",
17
+ "__version__",
18
+ ]
@@ -0,0 +1,640 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ import os
7
+ import shlex
8
+ import sys
9
+ import textwrap
10
+ from json.decoder import JSONDecodeError
11
+ from typing import NoReturn
12
+
13
+ from ._errors import FFmpegNormalizeError
14
+ from ._ffmpeg_normalize import NORMALIZATION_TYPES, FFmpegNormalize
15
+ from ._logger import setup_cli_logger
16
+ from ._version import __version__
17
+
18
+ _logger = logging.getLogger(__name__)
19
+
20
+
21
+ def create_parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(
23
+ prog="ffmpeg-normalize",
24
+ description=textwrap.dedent(
25
+ """\
26
+ ffmpeg-normalize v{} -- command line tool for normalizing audio files
27
+ """.format(__version__)
28
+ ),
29
+ # manually overridden because argparse generates the wrong order of arguments, see:
30
+ # https://github.com/slhck/ffmpeg-normalize/issues/132#issuecomment-662516535
31
+ usage="%(prog)s INPUT [INPUT ...] [-o OUTPUT [OUTPUT ...]] [options]",
32
+ formatter_class=argparse.RawTextHelpFormatter,
33
+ epilog=textwrap.dedent(
34
+ """\
35
+ The program additionally respects environment variables:
36
+
37
+ - `TMP` / `TEMP` / `TMPDIR`
38
+ Sets the path to the temporary directory in which files are
39
+ stored before being moved to the final output directory.
40
+ Note: You need to use full paths.
41
+
42
+ - `FFMPEG_PATH`
43
+ Sets the full path to an `ffmpeg` executable other than
44
+ the system default.
45
+
46
+
47
+ Author: Werner Robitza
48
+ License: MIT
49
+ Homepage / Issues: https://github.com/slhck/ffmpeg-normalize
50
+ """
51
+ ),
52
+ )
53
+
54
+ group_io = parser.add_argument_group("File Input/output")
55
+ group_io.add_argument("input", nargs="+", help="Input media file(s)")
56
+ group_io.add_argument(
57
+ "-o",
58
+ "--output",
59
+ nargs="+",
60
+ help=textwrap.dedent(
61
+ """\
62
+ Output file names. Will be applied per input file.
63
+
64
+ If no output file name is specified for an input file, the output files
65
+ will be written to the default output folder with the name `<input>.<ext>`,
66
+ where `<ext>` is the output extension (see `-ext` option).
67
+
68
+ Example: ffmpeg-normalize 1.wav 2.wav -o 1n.wav 2n.wav
69
+ """
70
+ ),
71
+ )
72
+ group_io.add_argument(
73
+ "-of",
74
+ "--output-folder",
75
+ type=str,
76
+ help=textwrap.dedent(
77
+ """\
78
+ Output folder (default: `normalized`)
79
+
80
+ This folder will be used for input files that have no explicit output
81
+ name specified.
82
+ """
83
+ ),
84
+ default="normalized",
85
+ )
86
+
87
+ group_general = parser.add_argument_group("General Options")
88
+ group_general.add_argument(
89
+ "-f", "--force", action="store_true", help="Force overwrite existing files"
90
+ )
91
+ group_general.add_argument(
92
+ "-d", "--debug", action="store_true", help="Print debugging output"
93
+ )
94
+ group_general.add_argument(
95
+ "-v", "--verbose", action="store_true", help="Print verbose output"
96
+ )
97
+ group_general.add_argument(
98
+ "-q", "--quiet", action="store_true", help="Only print errors in output"
99
+ )
100
+ group_general.add_argument(
101
+ "-n",
102
+ "--dry-run",
103
+ action="store_true",
104
+ help="Do not run normalization, only print what would be done",
105
+ )
106
+ group_general.add_argument(
107
+ "-pr",
108
+ "--progress",
109
+ action="store_true",
110
+ help="Show progress bar for files and streams",
111
+ )
112
+ group_general.add_argument(
113
+ "--version",
114
+ action="version",
115
+ version=f"%(prog)s v{__version__}",
116
+ help="Print version and exit",
117
+ )
118
+
119
+ group_normalization = parser.add_argument_group("Normalization")
120
+ group_normalization.add_argument(
121
+ "-nt",
122
+ "--normalization-type",
123
+ type=str,
124
+ choices=NORMALIZATION_TYPES,
125
+ help=textwrap.dedent(
126
+ """\
127
+ Normalization type (default: `ebu`).
128
+
129
+ EBU normalization performs two passes and normalizes according to EBU
130
+ R128.
131
+
132
+ RMS-based normalization brings the input file to the specified RMS
133
+ level.
134
+
135
+ Peak normalization brings the signal to the specified peak level.
136
+ """
137
+ ),
138
+ default="ebu",
139
+ )
140
+ group_normalization.add_argument(
141
+ "-t",
142
+ "--target-level",
143
+ type=float,
144
+ help=textwrap.dedent(
145
+ """\
146
+ Normalization target level in dB/LUFS (default: -23).
147
+
148
+ For EBU normalization, it corresponds to Integrated Loudness Target
149
+ in LUFS. The range is -70.0 - -5.0.
150
+
151
+ Otherwise, the range is -99 to 0.
152
+ """
153
+ ),
154
+ default=-23.0,
155
+ )
156
+ group_normalization.add_argument(
157
+ "-p",
158
+ "--print-stats",
159
+ action="store_true",
160
+ help="Print loudness statistics for both passes formatted as JSON to stdout.",
161
+ )
162
+ group_normalization.add_argument(
163
+ "--replaygain",
164
+ action="store_true",
165
+ help=textwrap.dedent(
166
+ """\
167
+ Write ReplayGain tags to the original file without normalizing.
168
+ This mode will overwrite the input file and ignore other options.
169
+ Only works with EBU normalization, and only with .mp3, .mp4/.m4a, .ogg, .opus for now.
170
+ """
171
+ ),
172
+ )
173
+
174
+ # group_normalization.add_argument(
175
+ # '--threshold',
176
+ # type=float,
177
+ # help=textwrap.dedent("""\
178
+ # Threshold below which normalization should not be run.
179
+
180
+ # If the stream falls within the threshold, it will simply be copied.
181
+ # """),
182
+ # default=0.5
183
+ # )
184
+
185
+ group_ebu = parser.add_argument_group("EBU R128 Normalization")
186
+ group_ebu.add_argument(
187
+ "-lrt",
188
+ "--loudness-range-target",
189
+ type=float,
190
+ help=textwrap.dedent(
191
+ """\
192
+ EBU Loudness Range Target in LUFS (default: 7.0).
193
+ Range is 1.0 - 50.0.
194
+ """
195
+ ),
196
+ default=7.0,
197
+ )
198
+
199
+ group_ebu.add_argument(
200
+ "--keep-loudness-range-target",
201
+ action="store_true",
202
+ help=textwrap.dedent(
203
+ """\
204
+ Keep the input loudness range target to allow for linear normalization.
205
+ """
206
+ ),
207
+ )
208
+
209
+ group_ebu.add_argument(
210
+ "--keep-lra-above-loudness-range-target",
211
+ action="store_true",
212
+ help=textwrap.dedent(
213
+ """\
214
+ Keep input loudness range above loudness range target.
215
+ Can be used as an alternative to `--keep-loudness-range-target` to allow for linear normalization.
216
+ """
217
+ ),
218
+ )
219
+
220
+ group_ebu.add_argument(
221
+ "-tp",
222
+ "--true-peak",
223
+ type=float,
224
+ help=textwrap.dedent(
225
+ """\
226
+ EBU Maximum True Peak in dBTP (default: -2.0).
227
+ Range is -9.0 - +0.0.
228
+ """
229
+ ),
230
+ default=-2.0,
231
+ )
232
+
233
+ group_ebu.add_argument(
234
+ "--offset",
235
+ type=float,
236
+ help=textwrap.dedent(
237
+ """\
238
+ EBU Offset Gain (default: 0.0).
239
+ The gain is applied before the true-peak limiter in the first pass only.
240
+ The offset for the second pass will be automatically determined based on the first pass statistics.
241
+ Range is -99.0 - +99.0.
242
+ """
243
+ ),
244
+ default=0.0,
245
+ )
246
+
247
+ group_ebu.add_argument(
248
+ "--lower-only",
249
+ action="store_true",
250
+ help=textwrap.dedent(
251
+ """\
252
+ Whether the audio should not increase in loudness.
253
+
254
+ If the measured loudness from the first pass is lower than the target
255
+ loudness then normalization pass will be skipped for the measured audio
256
+ source.
257
+ """
258
+ ),
259
+ )
260
+
261
+ group_ebu.add_argument(
262
+ "--auto-lower-loudness-target",
263
+ action="store_true",
264
+ help=textwrap.dedent(
265
+ """\
266
+ Automatically lower EBU Integrated Loudness Target to prevent falling
267
+ back to dynamic filtering.
268
+
269
+ Makes sure target loudness is lower than measured loudness minus peak
270
+ loudness (input_i - input_tp) by a small amount (0.1 LUFS).
271
+ """
272
+ ),
273
+ )
274
+
275
+ group_ebu.add_argument(
276
+ "--dual-mono",
277
+ action="store_true",
278
+ help=textwrap.dedent(
279
+ """\
280
+ Treat mono input files as "dual-mono".
281
+
282
+ If a mono file is intended for playback on a stereo system, its EBU R128
283
+ measurement will be perceptually incorrect. If set, this option will
284
+ compensate for this effect. Multi-channel input files are not affected
285
+ by this option.
286
+ """
287
+ ),
288
+ )
289
+
290
+ group_ebu.add_argument(
291
+ "--dynamic",
292
+ action="store_true",
293
+ help=textwrap.dedent(
294
+ """\
295
+ Force dynamic normalization mode.
296
+
297
+ Instead of applying linear EBU R128 normalization, choose a dynamic
298
+ normalization. This is not usually recommended.
299
+
300
+ Dynamic mode will automatically change the sample rate to 192 kHz. Use
301
+ -ar/--sample-rate to specify a different output sample rate.
302
+ """
303
+ ),
304
+ )
305
+
306
+ group_acodec = parser.add_argument_group("Audio Encoding")
307
+ group_acodec.add_argument(
308
+ "-c:a",
309
+ "--audio-codec",
310
+ type=str,
311
+ help=textwrap.dedent(
312
+ """\
313
+ Audio codec to use for output files.
314
+ See `ffmpeg -encoders` for a list.
315
+
316
+ Will use PCM audio with input stream bit depth by default.
317
+ """
318
+ ),
319
+ )
320
+ group_acodec.add_argument(
321
+ "-b:a",
322
+ "--audio-bitrate",
323
+ type=str,
324
+ help=textwrap.dedent(
325
+ """\
326
+ Audio bitrate in bits/s, or with K suffix.
327
+
328
+ If not specified, will use codec default.
329
+ """
330
+ ),
331
+ )
332
+ group_acodec.add_argument(
333
+ "-ar",
334
+ "--sample-rate",
335
+ type=str,
336
+ help=textwrap.dedent(
337
+ """\
338
+ Audio sample rate to use for output files in Hz.
339
+
340
+ Will use input sample rate by default, except for EBU normalization,
341
+ which will change the input sample rate to 192 kHz.
342
+ """
343
+ ),
344
+ )
345
+ group_acodec.add_argument(
346
+ "-ac",
347
+ "--audio-channels",
348
+ type=int,
349
+ help=textwrap.dedent(
350
+ """\
351
+ Set the number of audio channels.
352
+ If not specified, the input channel layout will be used.
353
+ """
354
+ ),
355
+ )
356
+ group_acodec.add_argument(
357
+ "-koa",
358
+ "--keep-original-audio",
359
+ action="store_true",
360
+ help="Copy original, non-normalized audio streams to output file",
361
+ )
362
+ group_acodec.add_argument(
363
+ "-prf",
364
+ "--pre-filter",
365
+ type=str,
366
+ help=textwrap.dedent(
367
+ """\
368
+ Add an audio filter chain before applying normalization.
369
+ Multiple filters can be specified by comma-separating them.
370
+ """
371
+ ),
372
+ )
373
+ group_acodec.add_argument(
374
+ "-pof",
375
+ "--post-filter",
376
+ type=str,
377
+ help=textwrap.dedent(
378
+ """\
379
+ Add an audio filter chain after applying normalization.
380
+ Multiple filters can be specified by comma-separating them.
381
+
382
+ For EBU, the filter will be applied during the second pass.
383
+ """
384
+ ),
385
+ )
386
+
387
+ group_vcodec = parser.add_argument_group("Other Encoding Options")
388
+ group_vcodec.add_argument(
389
+ "-vn",
390
+ "--video-disable",
391
+ action="store_true",
392
+ help="Do not write video streams to output",
393
+ )
394
+ group_vcodec.add_argument(
395
+ "-c:v",
396
+ "--video-codec",
397
+ type=str,
398
+ help=textwrap.dedent(
399
+ """\
400
+ Video codec to use for output files (default: 'copy').
401
+ See `ffmpeg -encoders` for a list.
402
+
403
+ Will attempt to copy video codec by default.
404
+ """
405
+ ),
406
+ default="copy",
407
+ )
408
+ group_vcodec.add_argument(
409
+ "-sn",
410
+ "--subtitle-disable",
411
+ action="store_true",
412
+ help="Do not write subtitle streams to output",
413
+ )
414
+ group_vcodec.add_argument(
415
+ "-mn",
416
+ "--metadata-disable",
417
+ action="store_true",
418
+ help="Do not write metadata to output",
419
+ )
420
+ group_vcodec.add_argument(
421
+ "-cn",
422
+ "--chapters-disable",
423
+ action="store_true",
424
+ help="Do not write chapters to output",
425
+ )
426
+
427
+ group_format = parser.add_argument_group("Input/Output options")
428
+ group_format.add_argument(
429
+ "-ei",
430
+ "--extra-input-options",
431
+ type=str,
432
+ help=textwrap.dedent(
433
+ """\
434
+ Extra input options list.
435
+
436
+ A list of extra ffmpeg command line arguments valid for the input,
437
+ applied before ffmpeg's `-i`.
438
+
439
+ You can either use a JSON-formatted list (i.e., a list of
440
+ comma-separated, quoted elements within square brackets), or a simple
441
+ string of space-separated arguments.
442
+
443
+ If JSON is used, you need to wrap the whole argument in quotes to
444
+ prevent shell expansion and to preserve literal quotes inside the
445
+ string. If a simple string is used, you need to specify the argument
446
+ with `-e=`.
447
+
448
+ Examples: `-e '[ "-f", "mpegts" ]'` or `-e="-f mpegts"`
449
+ """
450
+ ),
451
+ )
452
+ group_format.add_argument(
453
+ "-e",
454
+ "--extra-output-options",
455
+ type=str,
456
+ help=textwrap.dedent(
457
+ """\
458
+ Extra output options list.
459
+
460
+ A list of extra ffmpeg command line arguments.
461
+
462
+ You can either use a JSON-formatted list (i.e., a list of
463
+ comma-separated, quoted elements within square brackets), or a simple
464
+ string of space-separated arguments.
465
+
466
+ If JSON is used, you need to wrap the whole argument in quotes to
467
+ prevent shell expansion and to preserve literal quotes inside the
468
+ string. If a simple string is used, you need to specify the argument
469
+ with `-e=`.
470
+
471
+ Examples: `-e '[ "-vbr", "3" ]'` or `-e="-vbr 3"`
472
+ """
473
+ ),
474
+ )
475
+ group_format.add_argument(
476
+ "-ofmt",
477
+ "--output-format",
478
+ type=str,
479
+ help=textwrap.dedent(
480
+ """\
481
+ Media format to use for output file(s).
482
+ See 'ffmpeg -formats' for a list.
483
+
484
+ If not specified, the format will be inferred by ffmpeg from the output
485
+ file name. If the output file name is not explicitly specified, the
486
+ extension will govern the format (see '--extension' option).
487
+ """
488
+ ),
489
+ )
490
+ group_format.add_argument(
491
+ "-ext",
492
+ "--extension",
493
+ type=str,
494
+ help=textwrap.dedent(
495
+ """\
496
+ Output file extension to use for output files that were not explicitly
497
+ specified. (Default: `mkv`)
498
+ """
499
+ ),
500
+ default="mkv",
501
+ )
502
+ return parser
503
+
504
+
505
+ def main() -> None:
506
+ cli_args = create_parser().parse_args()
507
+ setup_cli_logger(arguments=cli_args)
508
+
509
+ def error(message: object) -> NoReturn:
510
+ if _logger.getEffectiveLevel() == logging.DEBUG:
511
+ _logger.error(f"FFmpegNormalizeError: {message}")
512
+ else:
513
+ _logger.error(message)
514
+ sys.exit(1)
515
+
516
+ def _split_options(opts: str) -> list[str]:
517
+ """
518
+ Parse extra options (input or output) into a list.
519
+
520
+ Args:
521
+ opts: String of options
522
+
523
+ Returns:
524
+ list: List of options
525
+ """
526
+ if not opts:
527
+ return []
528
+ try:
529
+ if opts.startswith("["):
530
+ try:
531
+ ret = [str(s) for s in json.loads(opts)]
532
+ except JSONDecodeError:
533
+ ret = shlex.split(opts)
534
+ else:
535
+ ret = shlex.split(opts)
536
+ except Exception as e:
537
+ error(f"Could not parse extra_options: {e}")
538
+ return ret
539
+
540
+ # parse extra options
541
+ extra_input_options = _split_options(cli_args.extra_input_options)
542
+ extra_output_options = _split_options(cli_args.extra_output_options)
543
+
544
+ ffmpeg_normalize = FFmpegNormalize(
545
+ normalization_type=cli_args.normalization_type,
546
+ target_level=cli_args.target_level,
547
+ print_stats=cli_args.print_stats,
548
+ loudness_range_target=cli_args.loudness_range_target,
549
+ # threshold=cli_args.threshold,
550
+ keep_loudness_range_target=cli_args.keep_loudness_range_target,
551
+ keep_lra_above_loudness_range_target=cli_args.keep_lra_above_loudness_range_target,
552
+ true_peak=cli_args.true_peak,
553
+ offset=cli_args.offset,
554
+ lower_only=cli_args.lower_only,
555
+ auto_lower_loudness_target=cli_args.auto_lower_loudness_target,
556
+ dual_mono=cli_args.dual_mono,
557
+ dynamic=cli_args.dynamic,
558
+ audio_codec=cli_args.audio_codec,
559
+ audio_bitrate=cli_args.audio_bitrate,
560
+ sample_rate=cli_args.sample_rate,
561
+ audio_channels=cli_args.audio_channels,
562
+ keep_original_audio=cli_args.keep_original_audio,
563
+ pre_filter=cli_args.pre_filter,
564
+ post_filter=cli_args.post_filter,
565
+ video_codec=cli_args.video_codec,
566
+ video_disable=cli_args.video_disable,
567
+ subtitle_disable=cli_args.subtitle_disable,
568
+ metadata_disable=cli_args.metadata_disable,
569
+ chapters_disable=cli_args.chapters_disable,
570
+ extra_input_options=extra_input_options,
571
+ extra_output_options=extra_output_options,
572
+ output_format=cli_args.output_format,
573
+ extension=cli_args.extension,
574
+ dry_run=cli_args.dry_run,
575
+ progress=cli_args.progress,
576
+ replaygain=cli_args.replaygain,
577
+ )
578
+
579
+ if cli_args.output and len(cli_args.input) > len(cli_args.output):
580
+ _logger.warning(
581
+ "There are more input files than output file names given. "
582
+ "Please specify one output file name per input file using -o <output1> <output2> ... "
583
+ "Will apply default file naming for the remaining ones."
584
+ )
585
+
586
+ for index, input_file in enumerate(cli_args.input):
587
+ if cli_args.output is not None and index < len(cli_args.output):
588
+ if cli_args.output_folder and cli_args.output_folder != "normalized":
589
+ _logger.warning(
590
+ f"Output folder {cli_args.output_folder} is ignored for "
591
+ f"input file {input_file}"
592
+ )
593
+ output_file = cli_args.output[index]
594
+ output_dir = os.path.dirname(output_file)
595
+ if output_dir != "" and not os.path.isdir(output_dir):
596
+ error(f"Output file path {output_dir} does not exist")
597
+ else:
598
+ output_file = os.path.join(
599
+ cli_args.output_folder,
600
+ os.path.splitext(os.path.basename(input_file))[0]
601
+ + "."
602
+ + cli_args.extension,
603
+ )
604
+ if not os.path.isdir(cli_args.output_folder) and not cli_args.dry_run:
605
+ _logger.warning(
606
+ f"Output directory '{cli_args.output_folder}' does not exist, will create"
607
+ )
608
+ os.makedirs(cli_args.output_folder, exist_ok=True)
609
+
610
+ if (
611
+ os.path.exists(output_file)
612
+ and not cli_args.force
613
+ and not cli_args.replaygain
614
+ ):
615
+ _logger.warning(
616
+ f"Output file '{output_file}' already exists, skipping. Use -f to force overwriting."
617
+ )
618
+ continue
619
+
620
+ if not os.path.exists(input_file):
621
+ _logger.warning(f"Input file '{input_file}' does not exist, skipping")
622
+ continue
623
+
624
+ if not os.path.isfile(input_file):
625
+ _logger.warning(f"Input file '{input_file}' is not a file, skipping")
626
+ continue
627
+
628
+ try:
629
+ ffmpeg_normalize.add_media_file(input_file, output_file)
630
+ except FFmpegNormalizeError as e:
631
+ error(e)
632
+
633
+ try:
634
+ ffmpeg_normalize.run_normalization()
635
+ except FFmpegNormalizeError as e:
636
+ error(e)
637
+
638
+
639
+ if __name__ == "__main__":
640
+ main()