def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None):
  """ Get R128 loudness loudness level and sample peak. """
  logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "",
                                                        ", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths)))

  # build command line
  cmd = [ffmpeg_path or "ffmpeg",
         "-hide_banner", "-nostats"]
  for i, audio_filepath in enumerate(audio_filepaths):
    if not enable_ffmpeg_threading:
      cmd.extend(("-threads:%u" % (i), "1"))  # single decoding thread
    cmd.extend(("-i", audio_filepath))
  if (get_ffmpeg_lib_versions()["libavfilter"] >= 0x06526400) and (not enable_ffmpeg_threading):
    cmd.extend(("-filter_threads", "1"))  # single filter thread
  cmd.extend(("-map", "a"))
  ebur128_filter_params = {"framelog": "verbose"}
  aformat_r128_filter_params = {"sample_fmts": "s16",
                                "sample_rates": "48000",
                                "channel_layouts": "stereo"}
  aformat_rg_filter_params = {"sample_fmts": "s16"}
  filter_chain = []
  if len(audio_filepaths) > 1:
    cmd.append("-filter_complex")
    for i in range(len(audio_filepaths)):
      if calc_peak:
        filter_chain.append("[%u:a]asplit[a_rg_in_%u][a_r128_in_%u]" % (i, i, i))
        filter_chain.append("[a_rg_in_%u]%s,replaygain,anullsink" % (i,
                                                                     format_ffmpeg_filter("aformat",
                                                                                          aformat_rg_filter_params)))
      else:
        filter_chain.append("[%u:a]anul[a_r128_in_%u]" % (i, i))
      filter_chain.append("[a_r128_in_%u]%s,afifo[a_r128_in_fmt_%u]" % (i,
                                                                        format_ffmpeg_filter("aformat",
                                                                                             aformat_r128_filter_params),
                                                                        i))
    filter_chain.append("%sconcat=n=%u:v=0:a=1[a_r128_in_concat]" % ("".join(("[a_r128_in_fmt_%u]" % (i)) for i in range(len(audio_filepaths))),
                                                                     len(audio_filepaths)))
    filter_chain.append("[a_r128_in_concat]%s" % (format_ffmpeg_filter("ebur128", ebur128_filter_params)))
    cmd.append("; ".join(filter_chain))
  else:
    if calc_peak:
      filter_chain.extend((format_ffmpeg_filter("aformat", aformat_rg_filter_params),
                           "replaygain"))
    filter_chain.append(format_ffmpeg_filter("ebur128", ebur128_filter_params))
    # filter_chain.append("anullsink")
    cmd.extend(("-filter:a", ",".join(filter_chain)))
  cmd.extend(("-f", "null", os.devnull))

  # run
  logger().debug(subprocess.list2cmdline(cmd))
  output = subprocess.run(cmd,
                          check=True,
                          stdin=subprocess.DEVNULL,
                          stderr=subprocess.PIPE).stderr
  output = output.decode("utf-8", errors="replace").splitlines()

  if calc_peak:
    # parse replaygain filter output
    sample_peaks = []
    for line in reversed(output):
      if line.startswith("[Parsed_replaygain_") and ("] track_peak = " in line):
        sample_peaks.append(float(line.rsplit("=", 1)[1]))
        if len(sample_peaks) == len(audio_filepaths):
          break
    sample_peak = max(sample_peaks)
  else:
    sample_peak = None

  # parse r128 filter output
  for i in reversed(range(len(output))):
    line = output[i]
    if line.startswith("[Parsed_ebur128_") and line.endswith("Summary:"):
      break
  output = filter(lambda x: x and not x.startswith("[Parsed_replaygain_"),
                  map(str.strip, output[i:]))
  r128_stats = dict(tuple(map(str.strip, line.split(":", 1))) for line in output if not line.endswith(":"))
  r128_stats = {k: float(v.split(" ", 1)[0]) for k, v in r128_stats.items()}

  return r128_stats["I"], sample_peak
Get R128 loudness loudness level and sample peak.