loudnorm.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env ruby
  2. require 'open3'
  3. require 'json'
  4. ffmpeg_bin = 'ffmpeg'
  5. target_il = -24.0
  6. target_lra = +11.0
  7. target_tp = -2.0
  8. samplerate = '48k'
  9. if ARGF.argv.count != 2
  10. puts "Usage: #{$PROGRAM_NAME} input.wav output.wav"
  11. exit 1
  12. end
  13. ff_cmd = Array.new([
  14. ffmpeg_bin,
  15. '-hide_banner',
  16. '-i', ARGF.argv[0],
  17. '-af', "loudnorm='I=#{target_il}:LRA=#{target_lra}:tp=#{target_tp}:print_format=json'",
  18. '-f', 'null',
  19. '-']);
  20. _stdin, _stdout, stderr, wait_thr = Open3.popen3(*ff_cmd)
  21. if wait_thr.value.success?
  22. stats = JSON.parse(stderr.read.lines[-12, 12].join)
  23. loudnorm_string = 'loudnorm='
  24. loudnorm_string += 'print_format=summary:'
  25. loudnorm_string += 'linear=true:'
  26. loudnorm_string += "I=#{target_il}:"
  27. loudnorm_string += "LRA=#{target_lra}:"
  28. loudnorm_string += "tp=#{target_tp}:"
  29. loudnorm_string += "measured_I=#{stats['input_i']}:"
  30. loudnorm_string += "measured_LRA=#{stats['input_lra']}:"
  31. loudnorm_string += "measured_tp=#{stats['input_tp']}:"
  32. loudnorm_string += "measured_thresh=#{stats['input_thresh']}:"
  33. loudnorm_string += "offset=#{stats['target_offset']}"
  34. else
  35. puts stderr.read
  36. exit 1
  37. end
  38. ff_cmd = Array.new([
  39. ffmpeg_bin,
  40. '-y', '-hide_banner',
  41. '-i', ARGF.argv[0],
  42. '-af', loudnorm_string,
  43. '-ar', samplerate,
  44. ARGF.argv[1].to_s]);
  45. _stdin, _stdout, stderr, wait_thr = Open3.popen3(*ff_cmd)
  46. if wait_thr.value.success?
  47. puts stderr.read.lines[-12, 12].join
  48. exit 0
  49. else
  50. puts stderr.read
  51. exit 1
  52. end