Advertisement
MaxDjently

Ziggle Wump Media Compressor 0.2-beta.09.18.2024

Sep 17th, 2024 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 26.53 KB | Source Code | 0 0
  1. #!/data/data/com.termux/files/usr/bin/bash
  2.  
  3. # ATTENTION:
  4.  
  5. # Copying and pasting the script can introduce formatting that is improper to bash.  If the script doesn't run, you may need to use the dos2unix command to fix it.
  6.  
  7. # ex.  dos2unix ziggle_wump.sh
  8.  
  9. # --------------------
  10. #     Licence
  11. # --------------------
  12.  
  13. # This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  14.  
  15. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  16.  
  17. # You should have received a copy of the GNU General Public License along with  this program. If not, see <https://www.gnu.org/licenses/>.
  18.  
  19. # -----------------
  20. #     About
  21. # -----------------
  22.  
  23. # This script is for Termux on Android and is not associated with the apps it uses.
  24.  
  25. # Copyright Joshua Hansen and contributors: Microsoft Co-Pilot, OpenAI ChatGPT and Google Gemini.
  26.  
  27. # Shout out to Webernets https://youtu.be/0aeCfDKLfbs?si=58y58eWSiXurcHpj who gave me the inspiration for this, the one who did the heavy lifting figuring out the command line options. And this video helping me figure out how to do it in Handbrake, but I needed it all in a one-line command line option and this was it, I had to write it myself.
  28.  
  29. # -----------------------
  30. #   Instructions
  31. # -----------------------
  32.  
  33. instructions="#Ziggle Wump: The Simple FFmpeg Command Line Companion Script for Termux on Android
  34.  
  35. # Disclaimer
  36.  
  37. * This script does not allow conversion of encrypted files. Encrypted content typically indicates copyrighted material.
  38.  
  39. * The script itself does not violate copyright, but the user's actions might. The script cannot prevent users from circumventing copyright protection, nor is it the script's responsibility to do so. The onus lies with the copyright holder to encrypt their media.
  40.  
  41. * It is not recommended to use the script to violate copyright law. US copyright law allows for spaceshifting and fair use of copyrighted material.
  42.  
  43. # Note
  44.  
  45. * Some phones, like the Galaxy S24, have battery-saving features that can impact the encoding process and result in partially encoded files. Ensure Termux is in focus (full screen or split-screen) while encoding, and keep the screen on during the process.
  46.  
  47. * For more information and potential fixes for specific phones, visit https://dontkillmyapp.com/.
  48.  
  49. # Getting Started
  50.  
  51. * Download or Copy: Download or copy this script to a file and rename it if desired (e.g., ziggle_wump.sh). Placing it in your Movies folder makes it easily accessible on both Android and Termux, although you can also put it in /usr/bin to use it system-wide.
  52.  
  53. * Make it Executable: Run chmod +x ziggle_wump.sh to make the script executable.
  54. * Run the Script: Execute the script using bash ./ziggle_wump.sh [options].
  55.  
  56. # Options
  57.  
  58. * -r resolution: Sets a custom resolution height while preserving aspect ratio (e.g., bash ziggle_wump.sh -r 720).
  59. * -d: Checks and upgrades dependencies.
  60. * -y: Automatically confirms prompts.
  61. * -o output_fps: Sets a custom output FPS (e.g., bash ziggle_wump.sh -o 60).
  62. * -b max_video_bitrate: Sets a custom maximum video bitrate in kilobits per second (e.g., bash ziggle_wump.sh -b 2000).
  63. * -a avg_audio_bitrate: Sets a custom average audio bitrate in kilobits per second (e.g., bash ziggle_wump.sh -a 128).
  64. * -i: Installs the script to /data/data/com.termux/files/usr/bin/zwmc.
  65. * -u: Uninstalls the script from /data/data/com.termux/files/usr/bin/zwmc.
  66. * -m: Shows the menu for setting options.
  67. * -h, --help: Displays help message."
  68.  
  69. # -----------------------------
  70. #        Variables
  71. # -----------------------------
  72.  
  73. # Supported File Types
  74. video_ext="mp4 mkv avi mov flv wmv webm mts 3gp mpeg ogv rmvb m4v f4v vob ts m2ts asf swf m2v divx xvid mpg mpe m1v dvr-ms mxf gxf bink mng nsv"
  75. audio_ext="mp3 aac wav flac ogg m4a wma ac3 eac3 opus amr aiff alac caf dts mka mp2 ra tta voc"
  76.  
  77. # Maximum resolution by height in pixels maintaining aspect ratio. Either the user defined value or the input video original value will be selected
  78. resolution=600
  79. max_video_bitrate=688 # In Kilobits per second.
  80. # Set the audio bitrate for both videos and audio files.
  81. avg_audio_bitrate=96 # In Kilobits per second.
  82. output_fps=24 # Maximum output FPS. Original or user input, whichever is lower.
  83.  
  84. # Full Log file path
  85. log_file="$HOME/storage/shared/Movies/VideoDrop/convert.log"
  86.  
  87. # Shortened log file path for terminal output
  88. log_file_echo=$(echo "$log_file" | sed 's|/data/data/com.termux/files/home|.../home|g')
  89.  
  90. # Full directory paths
  91. video_drop_dir="$HOME/storage/shared/Movies/VideoDrop"
  92. video_processing_dir="$HOME/storage/shared/Movies/VideoProcessing"
  93. output_dir_base="$HOME/storage/shared/Movies/VideoConverted"
  94.  
  95. # Shortened directory paths for terminal output
  96. video_drop_dir_echo=$(echo "$video_drop_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  97. video_processing_dir_echo=$(echo "$video_processing_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  98. output_dir_base_echo=$(echo "$output_dir_base" | sed 's|/data/data/com.termux/files/home|.../home|g')
  99.  
  100. # combine audio and video extension variables to pass to find command.
  101. filetypes=""
  102. for ext in $audio_ext $video_ext; do
  103.     filetypes="$filetypes -iname '*.$ext' -o"
  104. done
  105. # Remove the trailing ' -o'
  106. filetypes="${filetypes% -o}"
  107.  
  108. # --------------------------------
  109. #     Command Flags
  110. # --------------------------------
  111.  
  112. show_menu() {
  113.     auto_yes=true  # Turn on auto_yes when the menu is shown
  114.     while true; do
  115.         deps_status="Off"
  116.         if [ "$check_deps" = true ]; then
  117.             deps_status="On"
  118.         fi
  119.  
  120.         menu_choice=$(dialog --menu "Choose an option:" 15 50 8 \
  121.             1 "Set Resolution Height ($resolution)" \
  122.             2 "Set Output FPS ($output_fps)" \
  123.             3 "Set Max Video Bitrate ($max_video_bitrate)" \
  124.             4 "Set Average Audio Bitrate ($avg_audio_bitrate)" \
  125.             5 "Check Dependencies ($deps_status)" \
  126.             6 "Install Script" \
  127.             7 "Uninstall Script" \
  128.             8 "Compress Files" 2>&1 >/dev/tty)
  129.  
  130.         case $menu_choice in
  131.             1)
  132.                 resolution=$(dialog --inputbox "Enter resolution height ($resolution):" 8 40 "$resolution" 2>&1 >/dev/tty)
  133.                 ;;
  134.             2)
  135.                 output_fps=$(dialog --inputbox "Enter output FPS ($output_fps):" 8 40 "$output_fps" 2>&1 >/dev/tty)
  136.                 ;;
  137.             3)
  138.                 max_video_bitrate=$(dialog --inputbox "Enter max video bitrate ($max_video_bitrate):" 8 40 "$max_video_bitrate" 2>&1 >/dev/tty)
  139.                 ;;
  140.             4)
  141.                 avg_audio_bitrate=$(dialog --inputbox "Enter average audio bitrate ($avg_audio_bitrate):" 8 40 "$avg_audio_bitrate" 2>&1 >/dev/tty)
  142.                 ;;
  143.             5)
  144.                 if [ "$check_deps" = true ]; then
  145.                     check_deps=false
  146.                 else
  147.                     check_deps=true
  148.                 fi
  149.                 ;;
  150.             6)
  151.                 clear
  152.                 install_script
  153.                 ;;
  154.             7)
  155.                 clear
  156.                 uninstall_script
  157.                 ;;
  158.             8)
  159.                 #auto_yes=true
  160.                 break
  161.                 ;;
  162.             *)
  163.                 tput sgr0  # Reset terminal colors
  164.                 clear
  165.                 exit 0
  166.                 ;;
  167.         esac
  168.     done
  169. }
  170.  
  171. # Function to display help message
  172. show_help() {
  173.     width=$(tput cols)
  174.     script_name=$(basename "$0")
  175.     echo "Place your media files in $video_drop_dir_echo." | tee -a "$log_file" | fmt -w $width
  176.     echo "Usage: bash $script_name [-r resolution] [-d] [-y] [-h|--help] [-o output_fps] [-b max_video_bitrate] [-a avg_audio_bitrate] [-i] [-u] [-m]" | fmt -w $width
  177.     echo "  -r resolution ex. bash $script_name -r 720               Custom resolution height preserving aspect ratio" | fmt -w $width
  178.     echo "  -d Check and upgrade dependencies." | fmt -w $width
  179.     echo "  -y Automatically say yes to prompts." | fmt -w $width
  180.     echo "  -o output_fps Set custom output FPS. ex. bash $script_name -o 60" | fmt -w $width
  181.     echo "  -b max_video_bitrate Set custom max video bitrate in kilobits per second. ex. bash $script_name -b 2000" | fmt -w $width
  182.     echo " -a avg_audio_bitrate Set custom average audio bitrate in kilobits per second. ex. bash $script_name -a 128" | fmt -w $width
  183.     echo "  -i Install the script to /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
  184.     echo "  -u Uninstall the script from /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
  185.     echo " -m: Shows the menu for setting options."
  186.     echo "  -h, --help Display this help message" | fmt -w $width
  187.     exit 0
  188. }
  189.  
  190. install_script() {
  191.     if [ -f /data/data/com.termux/files/usr/bin/zwmc ]; then
  192.         current_dir=$(dirname "$0")
  193.         if [ "$current_dir" != "/data/data/com.termux/files/usr/bin" ]; then
  194.             echo "Script is installed but not running from the bin directory. Reinstalling..."
  195.             cp "$0" /data/data/com.termux/files/usr/bin/zwmc
  196.             chmod +x /data/data/com.termux/files/usr/bin/zwmc
  197.             if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  198.                 echo "Script reinstalled to /data/data/com.termux/files/usr/bin/zwmc"
  199.             else
  200.                 echo "Reinstallation failed"
  201.             fi
  202.         else
  203.             echo "Script is already installed and running from the bin directory."
  204.         fi
  205.     else
  206.         cp "$0" /data/data/com.termux/files/usr/bin/zwmc
  207.         chmod +x /data/data/com.termux/files/usr/bin/zwmc
  208.         if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  209.             echo "Script installed to /data/data/com.termux/files/usr/bin/zwmc"
  210.         else
  211.             echo "Installation failed"
  212.         fi
  213.     fi
  214.     exit 0
  215. }
  216.  
  217. uninstall_script() {
  218.     if [ ! -f /data/data/com.termux/files/usr/bin/zwmc ]; then
  219.         echo "Script is not installed."
  220.         exit 0
  221.     else
  222.         rm -f /data/data/com.termux/files/usr/bin/zwmc
  223.         if ! whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  224.             echo "Script uninstalled from /data/data/com.termux/files/usr/bin/zwmc"
  225.         else
  226.             echo "Uninstallation failed"
  227.         fi
  228.     fi
  229.     exit 0
  230. }
  231.  
  232. # Parse command-line options
  233. check_deps=false
  234. auto_yes=false  # Set auto_yes to false by default
  235. while getopts "r:dyho:b:a:ium" opt; do
  236.     case $opt in
  237.         r) resolution="$OPTARG" ;;  # Set custom resolution by height
  238.         d) check_deps=true ;;  # Check and upgrade dependencies
  239.         y) auto_yes=true ;;  # Automatically say yes to prompts
  240.         o) output_fps="$OPTARG" ;;  # Set custom output FPS
  241.         b) max_video_bitrate="$OPTARG" ;;  # Set custom max video bitrate
  242.         a) avg_audio_bitrate="$OPTARG" ;;  # Set custom average audio bitrate
  243.         i) install_script ;;  # Install the script
  244.         u) uninstall_script ;;  # Uninstall the script
  245.         m) auto_yes=true; show_menu ;;  # Show menu and turn on auto_yes
  246.         h) show_help ;;  # Display help
  247.         *) show_help ;;  # Display help for invalid options
  248.     esac
  249. done
  250.  
  251. shift $((OPTIND -1))
  252.  
  253. # ---------------------------------
  254. #       Dependencies
  255. # ---------------------------------
  256.  
  257. if $check_deps; then
  258.     echo "Checking and upgrading dependencies, please wait..."
  259.     pkg update && pkg upgrade -y
  260.     if ! command -v bc &> /dev/null; then
  261.         pkg install bc -y
  262.     fi
  263.     if ! command -v ffmpeg &> /dev/null; then
  264.         pkg install ffmpeg -y
  265.     fi
  266.     if ! command -v ncurses-utils &> /dev/null; then
  267.         pkg install ncurses-utils -y
  268.     fi
  269.     echo "Update complete."
  270. fi
  271.  
  272. # -----------------------------------------------------
  273. #     Create Directories and log file
  274. # -----------------------------------------------------
  275.  
  276. # Create necessary directories if they don't exist
  277. mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
  278.  
  279. # Change to the VideoDrop directory
  280. cd "$video_drop_dir" || { echo "Directory change failed"; exit 1; }
  281.  
  282. # Check if log file exists
  283. if [ -f "$log_file" ]; then
  284.     echo "Old log file found.  Deleting..."
  285.     rm "$log_file"
  286.     echo "File deleted."
  287. else
  288.     echo "Log File does not exist.  The script will create $log_file_echo"
  289. fi
  290.  
  291. # ------------------------
  292. #     Start script
  293. # ------------------------
  294.  
  295. width=$(tput cols)
  296.  
  297. echo "Running... Press Ctrl+C to stop."
  298.  
  299. echo ""
  300. echo "$instructions" | tee -a "$log_file" | fmt -w $width
  301.  
  302. echo ""
  303. # Function to prompt the user to continue or quit
  304. prompt_continue_or_quit() {
  305.     while true; do
  306.         # Recursively find and process videos and audio
  307.         video_count=$(eval "find \"$video_drop_dir\" -type f \( $filetypes \) | wc -l")
  308.         echo "Detected $video_count compatible video and/or audio file(s) in:" | tee -a "$log_file" | fmt -w $width
  309.    
  310.         if [ "$video_count"  -eq 0 ]; then
  311.             echo "$video_drop_dir_echo folder created. Place your videos and audio here including files in folders using your favorite file manager for Android, and then run  the script again.  
  312.  
  313. Supported File Types:
  314.  
  315. Video: $video_ext
  316. Audio: $audio_ext" | tee -a "$log_file" | fmt -w $width
  317.             exit 0
  318.         fi
  319.  
  320.         # Prompt text
  321.         prompt_text="$video_drop_dir_echo. You can start encoding now. Do you wish to proceed? (Y/N): "
  322.  
  323.         # Format the prompt text
  324.         formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
  325.  
  326.         if $auto_yes; then
  327.             echo "$formatted_prompt"
  328.             echo "Y"
  329.             return 0  # Automatically continue
  330.         else
  331.             # Read user input with formatted prompt
  332.             read -p "$formatted_prompt" yn
  333.             case $yn in
  334.                 [Yy]* ) return 0;;  # Continue
  335.                 [Nn]* ) echo "Exiting script."; exit 0;;  # Quit
  336.                 * ) echo "Please answer Y or N.";;
  337.             esac
  338.         fi
  339.     done
  340. }
  341.  
  342. # Function to clean up file names
  343. clean_file_names() {
  344.     eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
  345.         dir=$(dirname "$file")
  346.         base=$(basename "$file")
  347.         new_base=$(echo "$base" | sed 's/[^a-zA-Z0-9 ._-]//g' | tr -s ' ')
  348.         new_file="$dir/$new_base"
  349.         if [ "$file" != "$new_file" ]; then
  350.             mv "$file" "$new_file"
  351.         fi
  352.     done
  353. }
  354.  
  355. # Clean up file names before processing
  356. clean_file_names
  357.  
  358. # Prompt the user to continue or quit?
  359. prompt_continue_or_quit
  360.  
  361. echo "Starting conversion process..." | tee -a "$log_file"
  362.  
  363. # Initialize ffmpeg_custom_options
  364. ffmpeg_custom_options="-c:v libx265 -x265-params \"deblock=-1:no-sao=1:keyint=250:aq-mode=3:psy-r=0.75:psy-rdoq=2.0:rd=4:rdoq-level=1:rect=0:strong-intra-smoothing=0\" -crf 32 -preset slow -c:a libopus -vbr on -ac 2 -af \"loudnorm=I=-23:LRA=7:TP=-2\""
  365.  
  366. # Add avg audio bitrate if avg_audio_bitrate is set
  367. if [ -n "$avg_audio_bitrate" ]; then
  368.     ffmpeg_custom_options="$ffmpeg_custom_options -b:a ${avg_audio_bitrate}k"
  369. fi
  370.  
  371. # Add maxrate and bufsize options if max_video_bitrate is set
  372. if [ -n "$max_video_bitrate" ]; then
  373.     ffmpeg_custom_options="$ffmpeg_custom_options -maxrate ${max_video_bitrate}k -bufsize 60M"
  374. fi
  375.  
  376.  
  377. # -----------------------------
  378. #    Audio Encoder
  379. # -----------------------------
  380.  
  381. width=$(tput cols)
  382.  
  383. # Function to check the log file for "Killed" message
  384. check_for_killed_message() {
  385.     if grep -q " Killed     " "$log_file"; then
  386.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
  387.         return 1
  388.     fi
  389.     return 0
  390. }
  391.  
  392. # Function to process audio files
  393. process_audio() {
  394.     local audio="$1"
  395.     local audio_echo=$(echo "$audio" | sed 's|/data/data/com.termux/files/home|/home|g')
  396.     local relative_path="${audio#$video_drop_dir/}"
  397.     local dir_path=$(dirname "$relative_path")
  398.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  399.     local output_dir="$output_dir_base/$dir_path"
  400.     local output_file="$output_dir/${base_name}_converted.opus"
  401.     local temp_output_file="$output_file.tmp"
  402.  
  403.     mkdir -p "$output_dir"  # Create output directory
  404.  
  405.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
  406.  
  407.     # Construct the FFmpeg command for audio processing
  408.     local ffmpeg_command="ffmpeg -nostdin -loglevel error -stats -stats_period 1 -y -i \"$audio\" -c:a libopus -b:a ${avg_audio_bitrate}k -vbr on -ac 2 -af \"loudnorm=I=-23:LRA=7:TP=-2\" -f opus \"$temp_output_file\""
  409.  
  410.     echo "$ffmpeg_command" | tee -a "$log_file"
  411.  
  412.     # Execute the FFmpeg command
  413.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  414.  
  415.     # Check for "Killed" message in the log file
  416.     if ! check_for_killed_message; then
  417.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
  418.         exit 1
  419.     fi
  420.  
  421.     if [ $? -eq 0 ]; then
  422.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  423.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  424.         mv "$audio" "$video_processing_dir/$relative_path"
  425.         echo ""
  426.         echo "$(date '+%Y-%m-%d %H:%M:%S') Converted $audio_echo. Your original files will be in the $video_processing_dir_echo folder for comparison. Your new files are in $output_dir_base_echo" | tee -a "$log_file" | fmt -w $width
  427.     else
  428.         echo ""
  429.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
  430.         exit 1
  431.     fi
  432. }
  433.  
  434. # ------------------------------
  435. #      Video Encoder
  436. # ------------------------------
  437.  
  438. width=$(tput cols)
  439.  
  440. # Function to check the log file for "Killed" message
  441. check_for_killed_message() {
  442.     if grep -q " Killed     " "$log_file"; then
  443.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
  444.         exit 1
  445.     fi
  446. }
  447.  
  448. process_video() {
  449.     local video="$1"
  450.     local video_echo=$(echo "$video" | sed 's|/data/data/com.termux/files/home|.../home|g')
  451.     local relative_path="${video#$video_drop_dir/}"
  452.     local dir_path=$(dirname "$relative_path")
  453.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  454.     local output_dir="$output_dir_base/$dir_path"
  455.     local output_file="$output_dir/${base_name}_converted.mkv"
  456.     local scale_filter=""
  457.  
  458.     # Get input video resolution
  459.     input_resolution=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$video" | tr -d '[:space:],')
  460.  
  461.     if [ -n "$resolution" ]; then
  462.         if [ "$input_resolution" -gt "$resolution" ]; then
  463.             scale_filter="scale=-2:$resolution:flags=lanczos"
  464.             echo "Input resolution ($input_resolution) is higher than user-defined resolution ($resolution). Using user-defined resolution." | tee -a "$log_file"
  465.         else
  466.             echo "Input resolution ($input_resolution) is lower or equal to user-defined resolution ($resolution). Keeping original resolution." | tee -a "$log_file"
  467.         fi
  468.     else
  469.         echo "Resolution set to: original" | tee -a "$log_file"
  470.     fi
  471.  
  472.     mkdir -p "$output_dir"  # Create output directory
  473.  
  474.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
  475.  
  476.     # Get the frame rate of the input video
  477.     input_fps=$(ffprobe -v error -select_streams v:0 -show_entries stream=avg_frame_rate,r_frame_rate -of csv=p=0 "$video" | awk -F'/' '{if ($2) print $1/$2; else print $1}' | bc -l)
  478.  
  479.     # Define common frame rates
  480.     common_fps=(23.976 24 25 29.97 30 50 59.94 60)
  481.  
  482.     # Function to find the nearest valid frame rate
  483.     nearest_fps() {
  484.         local fps=$1
  485.         local nearest=${common_fps[0]}
  486.         local min_diff=$(echo "scale=5; $fps - ${common_fps[0]}" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
  487.         for rate in "${common_fps[@]}"; do
  488.             local diff=$(echo "scale=5; $fps - $rate" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
  489.             if (( $(echo "$diff < $min_diff" | bc -l) )); then
  490.                 min_diff=$diff
  491.                 nearest=$rate
  492.             fi
  493.         done
  494.         echo $nearest
  495.     }
  496.  
  497.     # Round the frame rate to the nearest valid frame rate
  498.     rounded_fps=$(nearest_fps $input_fps)
  499.  
  500.     # Determine the lower frame rate
  501.     if (( $(echo "$rounded_fps > $output_fps" | bc -l) )); then
  502.         final_fps=$output_fps
  503.     else
  504.         final_fps=$rounded_fps
  505.     fi
  506.  
  507. # Set the initial video filter option
  508. video_filter_option="yadif=2,fps=$final_fps,${scale_filter}"
  509.  
  510. # Detect the pixel format using ffprobe
  511. input_file="$video"
  512. pix_fmt=$(ffprobe -v repeat+level+error -select_streams v:0 -show_entries stream=pix_fmt -of default=noprint_wrappers=1:nokey=1 "$input_file" | awk 'NR==1{print $1}')
  513.  
  514. echo "Pixel format: $pix_fmt"
  515.  
  516. # Validate the pixel format
  517. valid_pix_fmt=$(ffmpeg -pix_fmts | grep -w "$pix_fmt")
  518.  
  519. # Check if 10-bit encoding is selected
  520. if [[ "$pix_fmt" == *"10le"* || "$pix_fmt" == *"10be"* ]]; then
  521.     video_filter_option="$video_filter_option,deband=1thr=0.01:2thr=0.01:3thr=0.01:4thr=0.01:range=4:direction=-3.14:blur=1:coupling=0"
  522. fi
  523.  
  524. # Define a variable for probe size and analyze duration
  525. probe_analyze_opts="-probesize 2147483647 -analyzeduration 2147483647"
  526.  
  527. # Detect subtitle codecs and convert unsupported ones
  528. subtitle_codecs=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=codec_name -of csv=p=0 "$input_file")
  529. subtitle_map=""
  530. if [ -n "$subtitle_codecs" ]; then
  531.     subtitle_map="-map 0:s"  # Include all subtitle streams
  532.     i=0
  533.     while read -r codec; do
  534.         case "$codec" in
  535.             # Text-based subtitles to be copied directly
  536.             srt)
  537.                 subtitle_map="$subtitle_map -c:s:$i copy"
  538.                 ;;
  539.             # Other text-based subtitles to be converted to SRT
  540.             ass|ssa|webvtt|eia_608|eia_708|scc|sami|ttml|smi|teletext|mov_text|microdvd|subviewer)
  541.                 subtitle_map="$subtitle_map -c:s:$i srt"
  542.                 ;;
  543.             # Bitmap-based subtitles to be converted to DVD subtitles
  544.             dvdsub|pgs|vobsub|hdmv_pgs_subtitle|dvd_subtitle)
  545.                 subtitle_map="$subtitle_map -c:s:$i dvdsub"
  546.                 ;;
  547.             # Copy other compatible subtitles
  548.             *)
  549.                 subtitle_map="$subtitle_map -c:s:$i copy"
  550.                 ;;
  551.         esac
  552.         i=$((i + 1))
  553.     done <<< "$subtitle_codecs"
  554. else
  555.     echo "No subtitle streams detected." | tee -a "$log_file"
  556. fi
  557.  
  558. # Combine common and custom FFmpeg options
  559. combined_ffmpeg_options="-nostdin -loglevel error -stats -stats_period 5 $probe_analyze_opts -y -fix_sub_duration -i \"$video\" -map 0:v:0 -map 0:a:? -map_chapters 0 $ffmpeg_custom_options"
  560.  
  561. # Construct the FFmpeg command
  562. local ffmpeg_command
  563. if [ -n "$valid_pix_fmt" ]; then
  564.     if [ -n "$subtitle_map" ]; then
  565.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt $subtitle_map"
  566.     else
  567.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt"
  568.     fi
  569. else
  570.     if [ -n "$subtitle_map" ]; then
  571.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" $subtitle_map"
  572.     else
  573.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\""
  574.     fi
  575. fi
  576.  
  577. # Ensure all subtitle streams are marked as "default: off"
  578. subtitle_streams=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=index -of csv=p=0 "$input_file")
  579. if [ -n "$subtitle_streams" ]; then
  580.     for stream_index in $subtitle_streams; do
  581.         ffmpeg_command="$ffmpeg_command -disposition:s:$stream_index 0"
  582.     done
  583. fi
  584.  
  585. # Add the output file name at the end
  586. ffmpeg_command="$ffmpeg_command \"$output_file\""
  587.  
  588. echo "FFmpeg command: $ffmpeg_command" | tee -a "$log_file"
  589.  
  590. # Execute the FFmpeg command
  591. if ! eval $ffmpeg_command 2>&1 | tee -a "$log_file"; then
  592.     echo "FFmpeg command failed. Check the log for details." | tee -a "$log_file"
  593.     exit 1
  594. fi
  595.  
  596.     # Check for "Killed" message in the log file
  597.     check_for_killed_message
  598.  
  599.    if [ $? -eq 0 ]; then
  600.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  601.         mv "$video" "$video_processing_dir/$relative_path"
  602.         echo ""
  603.         echo "$(date '+%Y-%m-%d %H:%M:%S') Complete.  Your original files are in $video_processing_dir_echo.  Your new files are in $output_dir_base_echo" | tee -a "$log_file" | fmt -w $width
  604.     else
  605.         echo ""
  606.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
  607.         exit 1
  608.     fi
  609. }
  610.  
  611. # --------------------------------------
  612. #    Start Batch Encoding
  613. # --------------------------------------
  614.  
  615. width=$(tput cols)
  616.  
  617. stop_processing=false
  618.  
  619. # Function to handle SIGINT (Ctrl+C)
  620. handle_sigint() {
  621.     echo ""
  622.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  623.     stop_processing=true
  624.     exit 1  # Exit immediately without performing cleanup
  625. }
  626.  
  627. # Trap SIGINT and call the handle_sigint function
  628. trap handle_sigint SIGINT
  629.  
  630. # Process each file found
  631. eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
  632.     if [ "$stop_processing" = true ]; then
  633.         echo "Stopping processing due to SIGINT."
  634.         exit 1
  635.     fi
  636.  
  637.     case "$file" in
  638.         *.mp3|*.aac|*.wav|*.flac|*.ogg|*.m4a|*.wma|*.ac3|*.eac3|*.opus|*.amr|*.aiff|*.alac|*.caf|*.dts|*.mka|*.mp2|*.ra|*.tta|*.voc)
  639.             process_audio "$file" || exit 1
  640.             ;;
  641.  
  642.         *.mp4|*.mkv|*.avi|*.mov|*.flv|*.wmv|*.webm|*.mts|*.3gp|*.mpeg|*.ogv|*.rmvb|*.m4v|*.f4v|*.vob|*.ts|*.m2ts|*.asf|*.swf|*.m2v|*.divx|*.xvid|*.mpg|*.mpe|*.m1v|*.dvr-ms|*.mxf|*.gxf|*.bink|*.mng|*.nsv)
  643.             process_video "$file" || exit 1
  644.             ;;
  645.     esac
  646. done
  647.  
  648. # -----------------------------
  649. #     Finishing Up
  650. # -----------------------------
  651.  
  652. width=$(tput cols)
  653.  
  654. find "$PWD" -type d -empty -delete
  655. echo "removed empty folders in $video_drop_dir_echo directory"
  656.  
  657. # final output message
  658. echo ""
  659. echo "Log file is in $video_drop_dir_echo.  There may be unprocessed media files or other incompatible files.  Some files may need to be remuxed for compatibility." | tee -a "$log_file" | fmt -w $width
  660. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement