Skip to content

Commit 4366cf5

Browse files
committed
perform loudness normalization
1 parent 70f70ba commit 4366cf5

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

processing.jl

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,39 @@ using JSON
55
const preroll = ARGS[1]
66
const file = ARGS[2]
77

8+
const target_il = -24.0
9+
const target_lra = +11.0
10+
const target_tp = -2.0
11+
12+
const loudnorm_query = "loudnorm=dual_mono=true:I=$(target_il):LRA=$(target_lra):tp=$(target_tp)"
13+
14+
function query_loudness(file)
15+
output_lines = FFMPEG.exe(`-i $file -filter:a $(loudnorm_query*":print_format=json") -vn -sn -f null NULL`, collect=true)
16+
17+
loudnorm_start = nothing
18+
loudnorm_end = nothing
19+
for (i,line) in enumerate(output_lines)
20+
if startswith(line, "[Parsed_loudnorm")
21+
loudnorm_start = i + 1
22+
continue
23+
end
24+
25+
if loudnorm_start !== nothing && startswith(line, "}")
26+
loudnorm_end = i
27+
continue
28+
end
29+
end
30+
31+
if loudnorm_end === nothing || loudnorm_start === nothing
32+
error("Failed to parse ffmpeg output")
33+
end
34+
35+
json = join(output_lines[loudnorm_start:loudnorm_end], "\n")
36+
properties = JSON.Parser.parse(json)
37+
end
38+
39+
format_loudnorm(p) = loudnorm_query * ":linear=true:measured_I=$(p["input_i"]):measured_LRA=$(p["input_lra"]):measured_tp=$(p["input_tp"]):measured_thresh=$(p["input_thresh"]):offset=$(p["target_offset"])"
40+
841
# 1. Query properties of file
942

1043
json = join(FFMPEG.exe(`-v error -show_entries stream=width,height -of json $(file)`, command=FFMPEG.ffprobe, collect=true), "\n")
@@ -17,13 +50,22 @@ sizes = map(stream -> (stream["width"], stream["height"]), streams)
1750
unique!(sizes)
1851
width, height = only(sizes)
1952

53+
@sync begin
54+
global query0 = @async query_loudness(preroll)
55+
global query1 = @async query_loudness(file)
56+
end
57+
audio0_properties = fetch(query0)
58+
audio1_properties = fetch(query1)
59+
2060
args = ```
2161
-i $(preroll)
2262
-i $(file)
2363
-filter_complex
2464
"[0:v]scale=$(width):$(height):force_original_aspect_ratio=decrease,pad=$(width):$(height):-1:-1,setsar=1,fps=30,format=yuv420p[v0]; \
2565
[1:v]setsar=1,fps=30,format=yuv420p[v1];
26-
[v0][0:a][v1][1:a]concat=n=2:v=1:a=1[v][a]"
66+
[0:a]$(format_loudnorm(audio0_properties))[a0];
67+
[1:a]$(format_loudnorm(audio1_properties))[a1];
68+
[v0][a0][v1][a1]concat=n=2:v=1:a=1[v][a]"
2769
-map "[v]"
2870
-map "[a]"
2971
-c:v libx264
@@ -35,6 +77,4 @@ args = ```
3577
out/$(file)
3678
```
3779

38-
@show args
3980
FFMPEG.exe(args)
40-

0 commit comments

Comments
 (0)