Advertisement
MaxDjently

Ziggle Wump Media Compressor 0.2-beta.09.16.2024

Sep 15th, 2024
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 25.25 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"
  75. audio_ext="mp3 wav flac aac ogg m4a opus"
  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.     while true; do
  114.         dialog --clear --title "Menu" \
  115.         --menu "Choose an option:" 15 50 5 \
  116.         1 "Set Resolution" \
  117.         2 "Set Output FPS" \
  118.         3 "Set Video Bitrate" \
  119.         4 "Set Audio Bitrate" \
  120.         5 "Confirm and Exit" 2>~/menu_choice.txt
  121.  
  122.         menu_choice=$(<~/menu_choice.txt)
  123.         rm -f ~/menu_choice.txt
  124.  
  125.         case $menu_choice in
  126.             1)
  127.                 resolution=$(dialog --inputbox "Enter resolution height:" 8 40 2>&1 >/dev/tty)
  128.                 ;;
  129.             2)
  130.                 output_fps=$(dialog --inputbox "Enter output FPS:" 8 40 2>&1 >/dev/tty)
  131.                 ;;
  132.             3)
  133.                 max_video_bitrate=$(dialog --inputbox "Enter max video bitrate (kbps):" 8 40 2>&1 >/dev/tty)
  134.                 ;;
  135.             4)
  136.                 avg_audio_bitrate=$(dialog --inputbox "Enter average audio bitrate (kbps):" 8 40 2>&1 >/dev/tty)
  137.                 ;;
  138.             5)
  139.                 break
  140.                 ;;
  141.             *)
  142.                 tput sgr0  # Reset terminal colors
  143.                 clear
  144.                 exit 0
  145.                 ;;
  146.         esac
  147.     done
  148. }
  149.  
  150. # Function to display help message
  151. show_help() {
  152.     width=$(tput cols)
  153.     script_name=$(basename "$0")
  154.     echo "Place your media files in $video_drop_dir_echo." | tee -a "$log_file" | fmt -w $width
  155.     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
  156.     echo "  -r resolution ex. bash $script_name -r 720               Custom resolution height preserving aspect ratio" | fmt -w $width
  157.     echo "  -d Check and upgrade dependencies." | fmt -w $width
  158.     echo "  -y Automatically say yes to prompts." | fmt -w $width
  159.     echo "  -o output_fps Set custom output FPS. ex. bash $script_name -o 60" | fmt -w $width
  160.     echo "  -b max_video_bitrate Set custom max video bitrate in kilobits per second. ex. bash $script_name -b 2000" | fmt -w $width
  161.     echo " -a avg_audio_bitrate Set custom average audio bitrate in kilobits per second. ex. bash $script_name -a 128" | fmt -w $width
  162.     echo "  -i Install the script to /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
  163.     echo "  -u Uninstall the script from /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
  164.     echo "  -m Show menu" | fmt -w $width
  165.     echo "  -h, --help Display this help message" | fmt -w $width
  166.     exit 0
  167. }
  168.  
  169. install_script() {
  170.     if [ -f /data/data/com.termux/files/usr/bin/zwmc ]; then
  171.         current_dir=$(dirname "$0")
  172.         if [ "$current_dir" != "/data/data/com.termux/files/usr/bin" ]; then
  173.             echo "Script is installed but not running from the bin directory. Reinstalling..."
  174.             cp "$0" /data/data/com.termux/files/usr/bin/zwmc
  175.             chmod +x /data/data/com.termux/files/usr/bin/zwmc
  176.             if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  177.                 echo "Script reinstalled to /data/data/com.termux/files/usr/bin/zwmc"
  178.             else
  179.                 echo "Reinstallation failed"
  180.             fi
  181.         else
  182.             echo "Script is already installed and running from the bin directory."
  183.         fi
  184.     else
  185.         cp "$0" /data/data/com.termux/files/usr/bin/zwmc
  186.         chmod +x /data/data/com.termux/files/usr/bin/zwmc
  187.         if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  188.             echo "Script installed to /data/data/com.termux/files/usr/bin/zwmc"
  189.         else
  190.             echo "Installation failed"
  191.         fi
  192.     fi
  193.     exit 0
  194. }
  195.  
  196. uninstall_script() {
  197.     if [ ! -f /data/data/com.termux/files/usr/bin/zwmc ]; then
  198.         echo "Script is not installed."
  199.         exit 0
  200.     else
  201.         rm -f /data/data/com.termux/files/usr/bin/zwmc
  202.         if ! whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
  203.             echo "Script uninstalled from /data/data/com.termux/files/usr/bin/zwmc"
  204.         else
  205.             echo "Uninstallation failed"
  206.         fi
  207.     fi
  208.     exit 0
  209. }
  210.  
  211. # Parse command-line options
  212. auto_yes=false
  213. check_deps=false
  214. while getopts "r:dyho:b:a:ium" opt; do
  215.     case $opt in
  216.         r) resolution="$OPTARG" ;;  # Set custom resolution by height
  217.         d) check_deps=true ;;  # Check and upgrade dependencies
  218.         y) auto_yes=true ;;  # Automatically say yes to prompts
  219.         o) output_fps="$OPTARG" ;;  # Set custom output FPS
  220.         b) max_video_bitrate="$OPTARG" ;;  # Set custom max video bitrate
  221.         a) avg_audio_bitrate="$OPTARG" ;;  # Set custom average audio bitrate
  222.         i) install_script ;;  # Install the script
  223.         u) uninstall_script ;;  # Uninstall the script
  224.         m) show_menu ;;  # Show menu
  225.         h) show_help ;;  # Display help
  226.         *) show_help ;;  # Display help for invalid options
  227.     esac
  228. done
  229.  
  230. shift $((OPTIND -1))
  231.  
  232. # ---------------------------------
  233. #       Dependencies
  234. # ---------------------------------
  235.  
  236. if $check_deps; then
  237.     echo "Checking and upgrading dependencies, please wait..."
  238.     pkg update && pkg upgrade -y
  239.     if ! command -v bc &> /dev/null; then
  240.         pkg install bc -y
  241.     fi
  242.     if ! command -v ffmpeg &> /dev/null; then
  243.         pkg install ffmpeg -y
  244.     fi
  245.     if ! command -v ncurses-utils &> /dev/null; then
  246.         pkg install ncurses-utils -y
  247.     fi
  248.     echo "Update complete."
  249. fi
  250.  
  251. # -----------------------------------------------------
  252. #     Create Directories and log file
  253. # -----------------------------------------------------
  254.  
  255. # Create necessary directories if they don't exist
  256. mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
  257.  
  258. # Change to the VideoDrop directory
  259. cd "$video_drop_dir" || { echo "Directory change failed"; exit 1; }
  260.  
  261. # Check if log file exists
  262. if [ -f "$log_file" ]; then
  263.     echo "Old log file found.  Deleting..."
  264.     rm "$log_file"
  265.     echo "File deleted."
  266. else
  267.     echo "Log File does not exist.  The script will create $log_file_echo"
  268. fi
  269.  
  270. # ------------------------
  271. #     Start script
  272. # ------------------------
  273.  
  274. width=$(tput cols)
  275.  
  276. echo "Running... Press Ctrl+C to stop."
  277.  
  278. echo ""
  279. echo "$instructions" | tee -a "$log_file" | fmt -w $width
  280.  
  281. echo ""
  282. # Function to prompt the user to continue or quit
  283. prompt_continue_or_quit() {
  284.     while true; do
  285.         # Recursively find and process videos and audio
  286.         video_count=$(eval "find \"$video_drop_dir\" -type f \( $filetypes \) | wc -l")
  287.         echo "Detected $video_count compatible video and/or audio file(s) in:" | tee -a "$log_file" | fmt -w $width
  288.    
  289.         if [ "$video_count"  -eq 0 ]; then
  290.             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.  
  291.  
  292. Supported File Types:
  293.  
  294. Video: $video_ext
  295. Audio: $audio_ext" | tee -a "$log_file" | fmt -w $width
  296.             exit 0
  297.         fi
  298.  
  299.         # Prompt text
  300.         prompt_text="$video_drop_dir_echo. You can start encoding now. Do you wish to proceed? (Y/N): "
  301.  
  302.         # Format the prompt text
  303.         formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
  304.  
  305.         if $auto_yes; then
  306.             echo "$formatted_prompt"
  307.             echo "Y"
  308.             return 0  # Automatically continue
  309.         else
  310.             # Read user input with formatted prompt
  311.             read -p "$formatted_prompt" yn
  312.             case $yn in
  313.                 [Yy]* ) return 0;;  # Continue
  314.                 [Nn]* ) echo "Exiting script."; exit 0;;  # Quit
  315.                 * ) echo "Please answer Y or N.";;
  316.             esac
  317.         fi
  318.     done
  319. }
  320.  
  321. # Function to clean up file names
  322. clean_file_names() {
  323.     eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
  324.         dir=$(dirname "$file")
  325.         base=$(basename "$file")
  326.         new_base=$(echo "$base" | sed 's/[^a-zA-Z0-9 ._-]//g' | tr -s ' ')
  327.         new_file="$dir/$new_base"
  328.         if [ "$file" != "$new_file" ]; then
  329.             mv "$file" "$new_file"
  330.         fi
  331.     done
  332. }
  333.  
  334. # Clean up file names before processing
  335. clean_file_names
  336.  
  337. # Prompt the user to continue or quit?
  338. prompt_continue_or_quit
  339.  
  340. echo "Starting conversion process..." | tee -a "$log_file"
  341.  
  342. # Initialize ffmpeg_custom_options
  343. 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\""
  344.  
  345. # Add avg audio bitrate if avg_audio_bitrate is set
  346. if [ -n "$avg_audio_bitrate" ]; then
  347.     ffmpeg_custom_options="$ffmpeg_custom_options -b:a ${avg_audio_bitrate}k"
  348. fi
  349.  
  350. # Add maxrate and bufsize options if max_video_bitrate is set
  351. if [ -n "$max_video_bitrate" ]; then
  352.     ffmpeg_custom_options="$ffmpeg_custom_options -maxrate ${max_video_bitrate}k -bufsize 60M"
  353. fi
  354.  
  355.  
  356. # -----------------------------
  357. #    Audio Encoder
  358. # -----------------------------
  359.  
  360. width=$(tput cols)
  361.  
  362. # Function to check the log file for "Killed" message
  363. check_for_killed_message() {
  364.     if grep -q " Killed     " "$log_file"; then
  365.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
  366.         return 1
  367.     fi
  368.     return 0
  369. }
  370.  
  371. # Function to process audio files
  372. process_audio() {
  373.     local audio="$1"
  374.     local audio_echo=$(echo "$audio" | sed 's|/data/data/com.termux/files/home|/home|g')
  375.     local relative_path="${audio#$video_drop_dir/}"
  376.     local dir_path=$(dirname "$relative_path")
  377.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  378.     local output_dir="$output_dir_base/$dir_path"
  379.     local output_file="$output_dir/${base_name}_converted.opus"
  380.     local temp_output_file="$output_file.tmp"
  381.  
  382.     mkdir -p "$output_dir"  # Create output directory
  383.  
  384.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
  385.  
  386.     # Construct the FFmpeg command for audio processing
  387.     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\""
  388.  
  389.     echo "$ffmpeg_command" | tee -a "$log_file"
  390.  
  391.     # Execute the FFmpeg command
  392.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  393.  
  394.     # Check for "Killed" message in the log file
  395.     if ! check_for_killed_message; then
  396.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
  397.         exit 1
  398.     fi
  399.  
  400.     if [ $? -eq 0 ]; then
  401.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  402.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  403.         mv "$audio" "$video_processing_dir/$relative_path"
  404.         echo ""
  405.         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
  406.     else
  407.         echo ""
  408.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
  409.         exit 1
  410.     fi
  411. }
  412.  
  413. # ------------------------------
  414. #      Video Encoder
  415. # ------------------------------
  416.  
  417. width=$(tput cols)
  418.  
  419. # Function to check the log file for "Killed" message
  420. check_for_killed_message() {
  421.     if grep -q " Killed     " "$log_file"; then
  422.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
  423.         exit 1
  424.     fi
  425. }
  426.  
  427. process_video() {
  428.     local video="$1"
  429.     local video_echo=$(echo "$video" | sed 's|/data/data/com.termux/files/home|.../home|g')
  430.     local relative_path="${video#$video_drop_dir/}"
  431.     local dir_path=$(dirname "$relative_path")
  432.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  433.     local output_dir="$output_dir_base/$dir_path"
  434.     local output_file="$output_dir/${base_name}_converted.mkv"
  435.     local scale_filter=""
  436.  
  437.     # Get input video resolution
  438.     input_resolution=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$video" | tr -d '[:space:],')
  439.  
  440.     if [ -n "$resolution" ]; then
  441.         if [ "$input_resolution" -gt "$resolution" ]; then
  442.             scale_filter="scale=-2:$resolution:flags=lanczos"
  443.             echo "Input resolution ($input_resolution) is higher than user-defined resolution ($resolution). Using user-defined resolution." | tee -a "$log_file"
  444.         else
  445.             echo "Input resolution ($input_resolution) is lower or equal to user-defined resolution ($resolution). Keeping original resolution." | tee -a "$log_file"
  446.         fi
  447.     else
  448.         echo "Resolution set to: original" | tee -a "$log_file"
  449.     fi
  450.  
  451.     mkdir -p "$output_dir"  # Create output directory
  452.  
  453.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
  454.  
  455.     # Get the frame rate of the input video
  456.     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)
  457.  
  458.     # Define common frame rates
  459.     common_fps=(23.976 24 25 29.97 30 50 59.94 60)
  460.  
  461.     # Function to find the nearest valid frame rate
  462.     nearest_fps() {
  463.         local fps=$1
  464.         local nearest=${common_fps[0]}
  465.         local min_diff=$(echo "scale=5; $fps - ${common_fps[0]}" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
  466.         for rate in "${common_fps[@]}"; do
  467.             local diff=$(echo "scale=5; $fps - $rate" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
  468.             if (( $(echo "$diff < $min_diff" | bc -l) )); then
  469.                 min_diff=$diff
  470.                 nearest=$rate
  471.             fi
  472.         done
  473.         echo $nearest
  474.     }
  475.  
  476.     # Round the frame rate to the nearest valid frame rate
  477.     rounded_fps=$(nearest_fps $input_fps)
  478.  
  479.     # Determine the lower frame rate
  480.     if (( $(echo "$rounded_fps > $output_fps" | bc -l) )); then
  481.         final_fps=$output_fps
  482.     else
  483.         final_fps=$rounded_fps
  484.     fi
  485.  
  486. # Set the initial video filter option
  487. video_filter_option="yadif=2,fps=$final_fps,${scale_filter}"
  488.  
  489. # Detect the pixel format using ffprobe
  490. input_file="$video"
  491. 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}')
  492.  
  493. echo "Pixel format: $pix_fmt"
  494.  
  495. # Validate the pixel format
  496. valid_pix_fmt=$(ffmpeg -pix_fmts | grep -w "$pix_fmt")
  497.  
  498. # Check if 10-bit encoding is selected
  499. if [[ "$pix_fmt" == *"10le"* || "$pix_fmt" == *"10be"* ]]; then
  500.     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"
  501. fi
  502.  
  503. # Define a variable for probe size and analyze duration
  504. probe_analyze_opts="-probesize 2147483647 -analyzeduration 2147483647"
  505.  
  506. # Detect subtitle codecs and convert unsupported ones
  507. subtitle_codecs=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=codec_name -of csv=p=0 "$input_file")
  508. subtitle_map=""
  509. if [ -n "$subtitle_codecs" ]; then
  510.     subtitle_map="-map 0:s"  # Include all subtitle streams
  511.     i=0
  512.     while read -r codec; do
  513.         case "$codec" in
  514.             # Text-based subtitles to be copied directly
  515.             srt)
  516.                 subtitle_map="$subtitle_map -c:s:$i copy"
  517.                 ;;
  518.             # Other text-based subtitles to be converted to SRT
  519.             ass|ssa|webvtt|eia_608|eia_708|scc|sami|ttml|smi|teletext|mov_text|microdvd|subviewer)
  520.                 subtitle_map="$subtitle_map -c:s:$i srt"
  521.                 ;;
  522.             # Bitmap-based subtitles to be converted to DVD subtitles
  523.             dvdsub|pgs|vobsub|hdmv_pgs_subtitle|dvd_subtitle)
  524.                 subtitle_map="$subtitle_map -c:s:$i dvdsub"
  525.                 ;;
  526.             # Copy other compatible subtitles
  527.             *)
  528.                 subtitle_map="$subtitle_map -c:s:$i copy"
  529.                 ;;
  530.         esac
  531.         i=$((i + 1))
  532.     done <<< "$subtitle_codecs"
  533. else
  534.     echo "No subtitle streams detected." | tee -a "$log_file"
  535. fi
  536.  
  537. # Combine common and custom FFmpeg options
  538. 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:0 -map_chapters 0 $ffmpeg_custom_options"
  539.  
  540. # Construct the FFmpeg command
  541. local ffmpeg_command
  542. if [ -n "$valid_pix_fmt" ]; then
  543.     if [ -n "$subtitle_map" ]; then
  544.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt $subtitle_map"
  545.     else
  546.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt"
  547.     fi
  548. else
  549.     if [ -n "$subtitle_map" ]; then
  550.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" $subtitle_map"
  551.     else
  552.         ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\""
  553.     fi
  554. fi
  555.  
  556. # Ensure all subtitle streams are marked as "default: off"
  557. subtitle_streams=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=index -of csv=p=0 "$input_file")
  558. if [ -n "$subtitle_streams" ]; then
  559.     for stream_index in $subtitle_streams; do
  560.         ffmpeg_command="$ffmpeg_command -disposition:s:$stream_index 0"
  561.     done
  562. fi
  563.  
  564. # Add the output file name at the end
  565. ffmpeg_command="$ffmpeg_command \"$output_file\""
  566.  
  567. echo "FFmpeg command: $ffmpeg_command" | tee -a "$log_file"
  568.  
  569. # Execute the FFmpeg command
  570. if ! eval $ffmpeg_command 2>&1 | tee -a "$log_file"; then
  571.     echo "FFmpeg command failed. Check the log for details." | tee -a "$log_file"
  572.     exit 1
  573. fi
  574.  
  575.     # Check for "Killed" message in the log file
  576.     check_for_killed_message
  577.  
  578.    if [ $? -eq 0 ]; then
  579.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  580.         mv "$video" "$video_processing_dir/$relative_path"
  581.         echo ""
  582.         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
  583.     else
  584.         echo ""
  585.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
  586.         exit 1
  587.     fi
  588. }
  589.  
  590. # --------------------------------------
  591. #    Start Batch Encoding
  592. # --------------------------------------
  593.  
  594. width=$(tput cols)
  595.  
  596. stop_processing=false
  597.  
  598. # Process each file found
  599. eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
  600.  
  601. # Function to handle SIGINT (Ctrl+C)
  602. handle_sigint() {
  603.     echo ""
  604.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  605.     stop_processing=true
  606.     exit 1  # Exit immediately without performing cleanup
  607. }
  608.  
  609. # Trap SIGINT and call the handle_sigint function
  610. trap handle_sigint SIGINT
  611.  
  612.     if [ "$stop_processing" = true ]; then
  613.         echo "Stopping processing due to SIGINT."
  614.         exit 1
  615.     fi
  616.  
  617.     case "$file" in
  618.         *.mp3|*.wav|*.flac|*.aac|*.ogg|*.m4a|*.opus)
  619.             process_audio "$file" || exit 1
  620.             ;;
  621.         *.mp4|*.mkv|*.avi|*.mov|*.flv|*.wmv|*.webm|*.mts)
  622.             process_video "$file" || exit 1
  623.             ;;
  624.     esac
  625.  
  626.     # Remove the relative path folder if it's empty
  627.     rmdir "$(dirname "$file")" --ignore-fail-on-non-empty
  628. done
  629.  
  630. # -----------------------------
  631. #     Finishing Up
  632. # -----------------------------
  633.  
  634. width=$(tput cols)
  635.  
  636. # final output message
  637. echo ""
  638. 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
  639. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement