Advertisement
-nodo-

Reencode

Nov 2nd, 2024
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.86 KB | None | 0 0
  1. #!/bin/bash
  2. #
  3. # Re-encode a video to a target size in MB.
  4. # Example:
  5. #    ./this_script.sh video.mp4 15
  6.  
  7. T_SIZE="$2" # target size in MB
  8. T_FILE="${1%.*}-$2MB.mp4" # filename out
  9.  
  10. # Original duration in seconds
  11. O_DUR=$(\
  12.     ffprobe \
  13.     -v error \
  14.     -show_entries format=duration \
  15.     -of csv=p=0 "$1")
  16.  
  17. # Original audio rate
  18. O_ARATE=$(\
  19.     ffprobe \
  20.     -v error \
  21.     -select_streams a:0 \
  22.     -show_entries stream=bit_rate \
  23.     -of csv=p=0 "$1")
  24.  
  25. # Original audio rate in KiB/s
  26. O_ARATE=$(\
  27.     awk \
  28.     -v arate="$O_ARATE" \
  29.     'BEGIN { printf "%.0f", (arate / 1024) }')
  30.  
  31. # Target size is required to be less than the size of the original audio stream
  32. T_MINSIZE=$(\
  33.     awk \
  34.     -v arate="$O_ARATE" \
  35.     -v duration="$O_DUR" \
  36.     'BEGIN { printf "%.2f", ( (arate * duration) / 8192 ) }')
  37.  
  38. # Equals 1 if target size is ok, 0 otherwise
  39. IS_MINSIZE=$(\
  40.     awk \
  41.     -v size="$T_SIZE" \
  42.     -v minsize="$T_MINSIZE" \
  43.     'BEGIN { print (minsize < size) }')
  44.  
  45. # Give useful information if size is too small
  46. if [[ $IS_MINSIZE -eq 0 ]]; then
  47.     printf "%s\n" "Target size ${T_SIZE}MB is too small!" >&2
  48.     printf "%s %s\n" "Try values larger than" "${T_MINSIZE}MB" >&2
  49.     exit 1
  50. fi
  51.  
  52. # Set target audio bitrate
  53. T_ARATE=$O_ARATE
  54.  
  55.  
  56. # Calculate target video rate - MB -> KiB/s
  57. T_VRATE=$(\
  58.     awk \
  59.     -v size="$T_SIZE" \
  60.     -v duration="$O_DUR" \
  61.     -v audio_rate="$O_ARATE" \
  62.     'BEGIN { print  ( ( size * 8192.0 ) / ( 1.048576 * duration ) - audio_rate) }')
  63.  
  64. # Perform the conversion
  65. ffmpeg \
  66.     -y \
  67.     -i "$1" \
  68.     -c:v libx264 \
  69.     -b:v "$T_VRATE"k \
  70.     -pass 1 \
  71.     -an \
  72.     -f mp4 \
  73.     /dev/null \
  74. && \
  75. ffmpeg \
  76.     -i "$1" \
  77.     -c:v libx264 \
  78.     -b:v "$T_VRATE"k \
  79.     -pass 2 \
  80.     -c:a aac \
  81.     -b:a "$T_ARATE"k \
  82.     "$T_FILE" \
  83. && \
  84. rm ffmpeg2pass-0.log && \
  85. rm ffmpeg2pass-0.log.mbtree
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement