Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/data/data/com.termux/files/usr/bin/bash
- # ATTENTION:
- # 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.
- # ex. dos2unix ziggle_wump.sh
- # --------------------
- # Licence
- # --------------------
- # 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.
- # 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.
- # You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
- # -----------------
- # About
- # -----------------
- # This script is for Termux on Android and is not associated with the apps it uses.
- # Copyright Joshua Hansen and contributors: Microsoft Co-Pilot, OpenAI ChatGPT and Google Gemini.
- # 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.
- # -----------------------
- # Instructions
- # -----------------------
- instructions="Ziggle Wump: The Simple FFmpeg Command Line Companion Script for Termux on Android
- Disclaimer
- * This script does not allow conversion of encrypted files, typically indicating copyrighted material.
- * The script itself does not violate copyright, but user 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.
- * It is not recommended to use the script to violate copyright law. US copyright law allows for spaceshifting and fair use of copyrighted material.
- Note
- * Some phones, like the Galaxy S24, have battery-saving features that can impact encoding. Ensure Termux is in focus (full screen or split-screen) while encoding, and keep the screen on during the process.
- * For more information and potential fixes for specific phones, visit https://dontkillmyapp.com/.
- Getting Started
- * 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 /data/data/com.termux/files/usr/bin to use it system-wide.
- * Install Termux and Termux:Widget (Optional): Grab Termux from F-Droid if you haven't already. Termux:Widget is optional for a more user-friendly interface.
- * Obtain Storage Access: Run termux-setup-storage and allow access.
- * Run the Script: Execute the script using bash ./ziggle_wump.sh [options]. (FIRST TIME RUN: Use bash ./ziggle_wump.sh -d to install dependencies.)
- Termux:Widget (Optional):
- * Install Termux:Widget and grant it permissions.
- * Place the widget on your Home Screen.
- * Run bash ziggle_wump.sh -i to install the script to /data/data/com.termux/files/usr/bin and create a widget in $HOME/.shortcuts.
- * Reload the Widget to see 'Ziggle Wump Media Compressor.sh.'
- Options:
- * -r resolution: Sets a custom resolution height while preserving aspect ratio for both videos and images (e.g., bash ziggle_wump.sh -r 720).
- * -d: Checks and upgrades dependencies.
- * -y: Automatically confirms prompts.
- * -o output_fps: Sets a custom output video frames per second. (e.g., bash ziggle_wump.sh -o 60).
- * -b max_video_bitrate: Sets a custom maximum video bitrate in kilobits per second. (e.g., bash ziggle_wump.sh -b 2000).
- * -a avg_audio_bitrate: Sets a custom average audio bitrate in kilobits per second for both videos and audio files. (e.g., bash ziggle_wump.sh -a 128).
- * -p preset: Sets encoding speed preset for videos. (0=slowest, 8=fastest) (e.g., bash ziggle_wump.sh -p 4).
- * -P video_encoding_profile Sets the profile found in profiles.conf
- * -L Lists all profiles found in profiles.conf
- * -i: Installs the script to /data/data/com.termux/files/usr/bin/zwmc. Installs widget to ~/.shortcuts.
- * -u: Uninstalls the script from /data/data/com.termux/files/usr/bin/zwmc. Removes widget.
- * -m: Shows the menu for setting options.
- * -h, --help: Displays help message."
- # -----------------------------
- # Variables
- # -----------------------------
- # Supported File Types
- 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"
- audio_ext="mp3 aac wav flac ogg m4a wma ac3 eac3 opus amr aiff alac caf dts mka mp2 ra tta voc"
- img_ext="jpg jpeg png bmp tiff gif webp heic heif jxl ppm pgm pbm pam tga sgi pcx ras xbm xpm ico dds exr hdr svg"
- # Define an array named 'profiles' containing various video encoding profiles
- profiles=(
- # Profile format: "Profile_Name Height Frame_Rate Video_Bit_Rate Audio_Bit_Rate CRF Preset"
- "2_hour_CD 600 24 600 64 20 2"
- "2_hour_DVD 1200 24 3500 128 18 2"
- "2_hour_DL_DVD 1440 24 7000 192 18 2"
- "4_hour_CD 480 24 250 64 25 2"
- "4_hour_DVD 900 24 1750 96 23 2"
- "4_hour_DL_DVD 1080 24 3500 128 23 2"
- "6_hour_CD 360 24 140 64 28 4"
- "6_hour_DVD 720 24 850 64 28 4"
- "6_hour_DL_DVD 900 24 1700 96 28 4"
- "8_hour_DVD 600 24 700 64 26 4"
- "8_hour_DL_DVD 720 24 1400 96 26 4"
- "12_hour_DVD 480 24 470 64 27 4"
- "12_hour_DL_DVD 600 24 940 96 27 4"
- "16_hour_DVD 360 20 350 64 28 4"
- "16_hour_DL_DVD 480 20 700 64 28 4"
- "24_hour_DVD 240 15 235 64 28 4"
- "24_hour_DL_DVD 360 15 470 64 28 4"
- "2160p_Video 2160 60 10000 256 18 2"
- "1440p_Video 1440 60 6000 192 20 2"
- "1080p_Video 1080 60 4000 128 23 3"
- "900p_Video 900 60 3000 128 24 3"
- "720p_Video 720 30 2500 96 24 3"
- "600p_Video 600 30 2000 96 25 3"
- "480p_Video 480 30 1500 64 26 3"
- "360p_Video 360 30 1000 64 28 3"
- "240p_Video 240 30 500 48 30 4"
- "160p_Video 160 30 300 48 32 5"
- "10Mbps_Streaming 2160 60 9500 256 18 2"
- "5Mbps_Streaming 1440 60 4800 192 20 2"
- "3Mbps_Streaming 1080 60 2700 128 24 3"
- "1.5Mbps_Streaming 720 30 1300 96 24 3"
- "1Mbps_Streaming 480 30 900 64 26 3"
- "500kbps_Streaming 360 15 400 48 30 3"
- "128kbps_Streaming 240 15 110 32 32 5"
- "56kbps_Streaming 128 12 30 16 34 5"
- "90s_game_console 240 15 200 48 30 4"
- "Cinema_Quality 2160 24 7000 192 18 2"
- "Desktop_High-End 2160 60 10000 256 20 2"
- "Desktop_Low-End 1080 30 1500 96 24 3"
- "Desktop_Mid-Range 1440 60 3500 128 22 2"
- "DVD_Quality 480 24 1000 64 28 3"
- "Low_Bandwidth_Stream 270 15 100 48 32 5"
- "Low_Res_Mobile 360 24 300 48 28 4"
- "Mobile_High-End 1080 60 1500 96 24 3"
- "Mobile_Low_End 360 15 150 48 32 5"
- "Mobile_Mid-Range 720 30 800 64 26 3"
- "Modern_Laptop 1080 60 1500 96 24 3"
- "Old_Smartphone 360 24 300 64 28 4"
- "Retro_Computer_16-bit 320 30 150 32 32 5"
- "Retro_Computer_8-bit 240 15 100 32 32 5"
- "Retro_PC 480 15 200 64 30 4"
- "Tablet_Profile 720 30 800 64 26 3"
- "VHS_Quality 240 30 250 64 30 4"
- )
- default_profile="2_hour_CD"
- # Define an array of presets from slowest to fastest
- presets=("veryslow" "slower" "slow" "medium" "fast" "faster" "veryfast" "superfast" "ultrafast")
- preset=slow # Default Speed Preset
- profile="" # custom Ziggle Wump profile.
- # Full Log file path
- log_file="/storage/emulated/0/Movies/VideoDrop/convert.log"
- # Full directory paths
- video_drop_dir="/storage/emulated/0/Movies/VideoDrop"
- video_processing_dir="/storage/emulated/0/Movies/VideoProcessing"
- output_dir_base="/storage/emulated/0/Movies/VideoConverted"
- # combine audio and video extension variables to pass to find command.
- filetypes=""
- for ext in $audio_ext $video_ext $img_ext; do
- filetypes="$filetypes -iname '*.$ext' -o"
- done
- # Remove the trailing ' -o'
- filetypes="${filetypes% -o}"
- # Define a lock file
- LOCKFILE="/data/data/com.termux/files/usr/var/lock/zwmc.lock"
- LOCKDIR=$(dirname "$LOCKFILE")
- # Ensure the lock directory exists
- mkdir -p "$LOCKDIR"
- # Cleanup function to remove the lock file
- cleanup() {
- rm -f "$LOCKFILE"
- }
- # Set the trap to call cleanup on script exit
- trap cleanup EXIT
- # Try to acquire the lock
- exec 200>"$LOCKFILE"
- flock -n 200 || { echo "Script is already running"; exit 1; }
- # The lock file will be removed when the script exits, thanks to the trap
- # --------------------------------------------------
- # Setting up files and folders
- # --------------------------------------------------
- width=$(tput cols)
- # Create necessary directories if they don't exist
- mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
- # Check if log file exists
- if [ -f "$log_file" ]; then
- echo "Old log file found. Deleting..."
- rm "$log_file"
- echo "File deleted."
- else
- echo "Log File does not exist. The script will create $log_file"
- fi
- echo ""
- echo "$instructions" | tee -a "$log_file" | fmt -w $width
- echo "Generating profiles.conf in $video_drop_dir..." | tee -a "$log_file"
- # Define the instructions
- profile_instructions="# This file contains various video encoding profiles. Each profile specifies the resolution, frame rate, video bitrate, audio bitrate, CRF (Constant Rate Factor), and preset for encoding. These profiles are configured for x265 (HEVC) video codec and Opus audio codec. You can modify these profiles as needed for your specific use case.
- "
- # Check if profiles.conf exists, if not, create it
- if [ ! -f "$video_drop_dir/profiles.conf" ]; then
- echo "$profile_instructions" > "$video_drop_dir/profiles.conf"
- else
- # Add instructions if not present in profiles.conf
- if ! grep -q "# This file contains various video encoding profiles." "$video_drop_dir/profiles.conf"; then
- sed -i "1i $profile_instructions" "$video_drop_dir/profiles.conf"
- fi
- fi
- # Function to check if a profile exists
- profile_exists() {
- local profile_name=$1
- grep -q "^\[$profile_name\]" "$video_drop_dir/profiles.conf"
- }
- # Add profiles if they don't exist
- for profile in "${profiles[@]}"; do
- IFS=' ' read -r -a profile_params <<< "$profile"
- profile_name=${profile_params[0]}
- if ! profile_exists "$profile_name"; then
- echo "[${profile_name}]" >> "$video_drop_dir/profiles.conf"
- echo "resolution=${profile_params[1]}" >> "$video_drop_dir/profiles.conf"
- echo "frame_rate=${profile_params[2]}" >> "$video_drop_dir/profiles.conf"
- echo "video_bitrate=${profile_params[3]}" >> "$video_drop_dir/profiles.conf"
- echo "audio_bitrate=${profile_params[4]}" >> "$video_drop_dir/profiles.conf"
- echo "crf=${profile_params[5]}" >> "$video_drop_dir/profiles.conf"
- echo "preset=${profile_params[6]}" >> "$video_drop_dir/profiles.conf"
- echo "" >> "$video_drop_dir/profiles.conf"
- fi
- done
- # Function to read profile from profiles.conf
- read_profile() {
- local profile_name=$1
- resolution=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/resolution/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- output_fps=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/frame_rate/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- max_video_bitrate=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/video_bitrate/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- avg_audio_bitrate=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/audio_bitrate/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- crf=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/crf/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- preset=$(awk -F "=" "/^\[$profile_name\]/ {a=1} a==1 && \$1~/preset/ {print \$2; exit}" $video_drop_dir/profiles.conf)
- preset=${presets[$preset]}
- }
- # Function to list profiles from profiles.conf
- list_profiles() {
- awk -F "=" '/^\[.*\]/ {gsub(/[\[\]]/, "", $1); print $1}' $video_drop_dir/profiles.conf
- }
- # --------------------------------
- # Command Flags
- # --------------------------------
- read_profile "$default_profile"
- show_menu() {
- auto_yes=true # Turn on auto_yes when the menu is shown
- while true; do
- deps_status="Off"
- if [ "$check_deps" = true ]; then
- deps_status="On"
- fi
- menu_choice=$(dialog --menu "Ziggle Wump Media Compressor Chooser" 17 50 11 \
- 1 "Set Max Resolution ($resolution)" \
- 2 "Set Max Output FPS ($output_fps)" \
- 3 "Set Max Video Bitrate ($max_video_bitrate)" \
- 4 "Set Average Audio Bitrate ($avg_audio_bitrate)" \
- 5 "Set Constant Rate Factor ($crf)" \
- 6 "Set Encoding Speed ($preset)" \
- 7 "Check Dependencies ($deps_status)" \
- 8 "Install Script" \
- 9 "Uninstall Script" \
- 10 "Set Conversion Profile" \
- 11 "Compress Files in $(basename $video_drop_dir)" 2>&1 >/dev/tty)
- case $menu_choice in
- 1)
- new_resolution=$(dialog --inputbox "Enter resolution maximum height in pixels ($resolution):" 8 40 "$resolution" 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- resolution="$new_resolution"
- fi
- ;;
- 2)
- new_output_fps=$(dialog --inputbox "Enter maximum output FPS ($output_fps):" 8 40 "$output_fps" 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- output_fps="$new_output_fps"
- fi
- ;;
- 3)
- new_max_video_bitrate=$(dialog --inputbox "Enter maximum video bitrate ($max_video_bitrate):" 8 40 "$max_video_bitrate" 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- max_video_bitrate="$new_max_video_bitrate"
- fi
- ;;
- 4)
- new_avg_audio_bitrate=$(dialog --inputbox "Enter average audio bitrate ($avg_audio_bitrate):" 8 40 "$avg_audio_bitrate" 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- avg_audio_bitrate="$new_avg_audio_bitrate"
- fi
- ;;
- 5)
- dialog --msgbox "CRF (Constant Rate Factor) is a quality setting for video encoding. It ranges from 0 (lossless) to 51 (worst quality). Lower values mean better quality and larger files, while higher values mean lower quality and smaller files." 10 50
- new_crf=$(dialog --inputbox "Enter CRF value (0-51) ($crf):" 8 40 "$crf" 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- echo "User entered CRF: $new_crf" >&2 # Debug message
- if [ "$new_crf" -ge 0 ] && [ "$new_crf" -le 51 ]; then
- crf="$new_crf"
- echo "CRF set to: $crf" >&2 # Debug message
- else
- dialog --msgbox "Invalid CRF value. Please enter a value between 0 and 51." 6 40
- echo "Invalid CRF value entered: $new_crf" >&2 # Debug message
- fi
- fi
- ;;
- 6)
- dialog --msgbox "Choose an x265 speed preset. The preset determines the encoding speed and compression efficiency. Choose a preset that best fits your needs. Slower presets will provide better compression and quality but take longer to encode." 10 50
- # Your original preset selection dialog
- new_preset=$(dialog --menu "Choose x265 Speed Preset" 15 50 9 \
- ultrafast "8" \
- superfast "7" \
- veryfast "6" \
- faster "5" \
- fast "4" \
- medium "3" \
- slow "2" \
- slower "1" \
- veryslow "0" 2>&1 >/dev/tty)
- # Check if a new preset was selected
- if [ $? -eq 0 ]; then
- preset=$new_preset
- fi
- ;;
- 7)
- while true; do
- if [ "$check_deps" = true ]; then
- check_deps=false
- else
- check_deps=true
- fi
- deps_status="Off"
- if [ "$check_deps" = true ]; then
- deps_status="On"
- fi
- dialog --msgbox "Dependencies are now $deps_status" 6 40
- break
- done
- ;;
- 8)
- clear
- install_script
- ;;
- 9)
- clear
- uninstall_script
- ;;
- 10)
- profile_list=$(list_profiles)
- selected_profile=$(dialog --menu "Choose Profile" 15 50 9 $(echo "$profile_list" | awk '{print NR, $0}') 2>&1 >/dev/tty)
- if [ $? -eq 0 ]; then
- read_profile "$(echo "$profile_list" | sed -n "${selected_profile}p")"
- fi
- ;;
- 11)
- break
- ;;
- *)
- tput sgr0 # Reset terminal colors
- clear
- exit 0
- ;;
- esac
- done
- }
- # Function to display help message
- show_help() {
- width=$(tput cols)
- script_name=$(basename "$0")
- echo "Place your media files in $video_drop_dir." | tee -a "$log_file" | fmt -w $width
- echo "Usage: bash $script_name [-r resolution] [-d] [-y] [-o output_fps] [-b max_video_bitrate] [-a avg_audio_bitrate] [-p preset] [-i] [-u] [-m] [-P] [-L] [-h|--help]" | fmt -w $width
- echo " -r resolution ex. bash $script_name -r 720 Custom resolution height preserving aspect ratio" | fmt -w $width
- echo " -d Check and upgrade dependencies." | fmt -w $width
- echo " -y Automatically say yes to prompts." | fmt -w $width
- echo " -o output_fps Set custom output FPS. ex. bash $script_name -o 60" | fmt -w $width
- echo " -b max_video_bitrate Set custom max video bitrate in kilobits per second. ex. bash $script_name -b 2000" | fmt -w $width
- echo " -a avg_audio_bitrate Set custom average audio bitrate in kilobits per second. ex. bash $script_name -a 128" | fmt -w $width
- echo " -p preset Set encoding speed preset for x265 (0=slowest, 8=fastest). ex. bash $script_name -p 4" | fmt -w $width
- echo " -i Install the script to /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
- echo " -u Uninstall the script from /data/data/com.termux/files/usr/bin/zwmc" | fmt -w $width
- echo " -m Shows the menu for setting options." | fmt -w $width
- echo " -P video_encoding_profile Sets the profile found in profiles.conf" | fmt -w $width
- echo " -L List encoding profiles."
- echo " -h, --help Display this help message" | fmt -w $width
- exit 0
- }
- # Install Ziggle Wump to /data/data/com.termux/files/usr/bin folder and widget script to ~/.shortcuts
- install_script() {
- if [ -f /data/data/com.termux/files/usr/bin/zwmc ]; then
- current_dir=$(dirname "$0")
- if [ "$current_dir" != "/data/data/com.termux/files/usr/bin" ]; then
- echo "Script is installed but not running from the bin directory. Reinstalling..." | tee -a "$log_file" | fmt -w $width
- cp "$(readlink -f "$0")" /data/data/com.termux/files/usr/bin/zwmc
- chmod +x /data/data/com.termux/files/usr/bin/zwmc
- if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
- echo "Script reinstalled to /data/data/com.termux/files/usr/bin/zwmc"
- else
- echo "Reinstallation failed" | tee -a "$log_file" | fmt -w $width
- fi
- else
- echo "Script is already installed and running from the bin directory." | tee -a "$log_file" | fmt -w $width
- fi
- else
- cp "$(readlink -f "$0")" /data/data/com.termux/files/usr/bin/zwmc
- chmod +x /data/data/com.termux/files/usr/bin/zwmc
- if whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
- echo "Script installed to /data/data/com.termux/files/usr/bin/zwmc" | tee -a "$log_file" | fmt -w $width
- else
- echo "Installation failed" | tee -a "$log_file" | fmt -w $width
- fi
- fi
- # Create the shortcut script
- mkdir -p $HOME/.shortcuts
- echo '#!/data/data/com.termux/files/usr/bin/bash' > $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- echo 'zwmc -m' >> $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- echo 'read -p "Press Enter to continue. Bye!"' >> $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- echo 'case $return in' >> $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- echo ' * ) echo "Exiting script."' >> $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- echo 'esac' >> $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- chmod +x $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- exit 0
- }
- uninstall_script() {
- if [ ! -f /data/data/com.termux/files/usr/bin/zwmc ]; then
- echo "Script is not installed." | tee -a "$log_file" | fmt -w $width
- exit 0
- else
- rm -f /data/data/com.termux/files/usr/bin/zwmc
- if ! whereis zwmc | grep -q "/data/data/com.termux/files/usr/bin/zwmc"; then
- echo "Script uninstalled from /data/data/com.termux/files/usr/bin/zwmc" | tee -a "$log_file" | fmt -w $width
- else
- echo "Uninstallation failed" | tee -a "$log_file" | fmt -w $width
- fi
- fi
- # Remove the shortcut script
- rm -f $HOME/.shortcuts/Ziggle\ Wump\ Media\ Compressor.sh
- exit 0
- }
- # Parse command-line options
- check_deps=false
- auto_yes=false # Set auto_yes to false by default
- while getopts "r:dyho:b:a:c:iump:P:L" opt; do
- case $opt in
- r) resolution="$OPTARG" ;; # Set custom resolution by height
- d) check_deps=true ;; # Check and upgrade dependencies
- y) auto_yes=true ;; # Automatically say yes to prompts
- o) output_fps="$OPTARG" ;; # Set custom output FPS
- b) max_video_bitrate="$OPTARG" ;; # Set custom max video bitrate
- a) avg_audio_bitrate="$OPTARG" ;; # Set custom average audio bitrate
- c) crf="$OPTARG" ;; # Set custom CRF value
- i) install_script ;; # Install the script
- u) uninstall_script ;; # Uninstall the script
- m) auto_yes=true; show_menu ;; # Show menu and turn on auto_yes
- p) preset="${presets[$OPTARG]}" ;; # Set preset based on number 0-8
- P) profile="$OPTARG"; read_profile "$profile" ;;
- L) list_profiles # List encoding profiles.
- exit 0 ;;
- h) show_help ;; # Display help
- *) show_help ;; # Display help for invalid options
- esac
- done
- shift $((OPTIND -1))
- # ------------------------------
- # Dependencies
- # ------------------------------
- if $check_deps; then
- echo "Checking and upgrading dependencies, please wait..."
- pkg update && pkg upgrade -y
- if ! command -v bc &> /dev/null; then
- pkg install bc -y
- fi
- if ! command -v ffmpeg &> /dev/null; then
- pkg install ffmpeg -y
- fi
- if ! command -v ncurses-utils &> /dev/null; then
- pkg install ncurses-utils -y
- fi
- echo "Update complete."
- fi
- # ------------------------
- # Start script
- # ------------------------
- echo "Running... Press Ctrl+C to stop."
- echo ""
- # Function to prompt the user to continue or quit
- prompt_continue_or_quit() {
- while true; do
- # Recursively find and process videos and audio
- video_count=$(eval "find \"$video_drop_dir\" -type f \( $filetypes \) | wc -l")
- echo "Detected $video_count compatible video and/or audio file(s) in:" | tee -a "$log_file" | fmt -w $width
- if [ "$video_count" -eq 0 ]; then
- echo "$video_drop_dir 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.
- Supported File Types:
- Video: $video_ext
- Audio: $audio_ext
- Images: $img_ext" | tee -a "$log_file" | fmt -w $width
- exit 0
- fi
- # Prompt text
- prompt_text="$video_drop_dir. You can start encoding now. Do you wish to proceed? (Y/N): "
- # Format the prompt text
- formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
- if $auto_yes; then
- echo "$formatted_prompt"
- echo "Y"
- return 0 # Automatically continue
- else
- # Read user input with formatted prompt
- read -p "$formatted_prompt" yn
- case $yn in
- [Yy]* ) return 0;; # Continue
- [Nn]* ) echo "Exiting script."; exit 0;; # Quit
- * ) echo "Please answer Y or N.";;
- esac
- fi
- done
- }
- # Function to clean up file names
- clean_file_names() {
- eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
- dir=$(dirname "$file")
- base=$(basename "$file")
- new_base=$(echo "$base" | sed 's/[^a-zA-Z0-9 ._-]//g' | tr -s ' ')
- new_file="$dir/$new_base"
- if [ "$file" != "$new_file" ]; then
- mv "$file" "$new_file"
- fi
- done
- }
- # Clean up file names before processing
- clean_file_names
- # Prompt the user to continue or quit?
- prompt_continue_or_quit
- # Initialize ffmpeg_custom_options
- 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 $crf -preset $preset -c:a libopus -vbr on -ac 2 -af \"loudnorm=I=-23:LRA=7:TP=-2\""
- # Add avg audio bitrate if avg_audio_bitrate is set
- if [ -n "$avg_audio_bitrate" ]; then
- ffmpeg_custom_options="$ffmpeg_custom_options -b:a ${avg_audio_bitrate}k"
- fi
- # Add maxrate and bufsize options if max_video_bitrate is set
- if [ -n "$max_video_bitrate" ]; then
- ffmpeg_custom_options="$ffmpeg_custom_options -maxrate ${max_video_bitrate}k -bufsize 60M"
- fi
- # Function to check the log file for "Killed" message
- check_for_killed_message() {
- if grep -q " Killed " "$log_file"; then
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
- return 1
- fi
- return 0
- }
- echo "Starting conversion process..." | tee -a "$log_file"
- # -----------------------------
- # Image Encoder
- # -----------------------------
- width=$(tput cols)
- # Function to process image files
- process_image() {
- local image="$1"
- local relative_path="${image#$video_drop_dir/}"
- local dir_path=$(dirname "$relative_path")
- local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
- local output_dir="$output_dir_base/$dir_path"
- local output_file="$output_dir/${base_name}_converted.png"
- mkdir -p "$output_dir" # Create output directory
- echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $image to $output_file" | tee -a "$log_file"
- # Get input image resolution
- input_resolution=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$image" | tr -d '[:space:],')
- if [ -n "$resolution" ]; then
- if [ "$input_resolution" -gt "$resolution" ]; then
- scale_filter="scale=-2:$resolution:flags=lanczos"
- echo "Input resolution ($input_resolution) is higher than user-defined resolution ($resolution). Using user-defined resolution." | tee -a "$log_file"
- else
- echo "Input resolution ($input_resolution) is lower or equal to user-defined resolution ($resolution). Keeping original resolution." | tee -a "$log_file"
- fi
- else
- echo "Resolution set to: original" | tee -a "$log_file"
- fi
- # Construct the FFmpeg command for image processing
- ffmpeg_command="ffmpeg -nostdin -loglevel error -stats -y -i \"$image\" -compression_level 100 -vf \"$scale_filter\" \"$output_file\""
- echo "$ffmpeg_command" | tee -a "$log_file"
- # Execute the FFmpeg command
- eval $ffmpeg_command 2>&1 | tee -a "$log_file"
- # Check for "Killed" message in the log file
- if ! check_for_killed_message; then
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
- exit 1
- fi
- if [ $? -eq 0 ]; then
- # mv "$temp_output_file" "$output_file" # Rename the temporary file to the final output file
- mkdir -p "$video_processing_dir/$dir_path" # Create processing directory
- mv "$image" "$video_processing_dir/$relative_path"
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Converted $image. Your original files will be in the $video_processing_dir folder for comparison. Your new files are in $output_dir_base" | tee -a "$log_file" | fmt -w $width
- else
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$image\". Check log file for details." | tee -a "$log_file"
- exit 1
- fi
- }
- # -----------------------------
- # Audio Encoder
- # -----------------------------
- width=$(tput cols)
- # Function to process audio files
- process_audio() {
- local audio="$1"
- local relative_path="${audio#$video_drop_dir/}"
- local dir_path=$(dirname "$relative_path")
- local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
- local output_dir="$output_dir_base/$dir_path"
- local output_file="$output_dir/${base_name}_converted.opus"
- local temp_output_file="$output_file.tmp"
- mkdir -p "$output_dir" # Create output directory
- echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
- # Construct the FFmpeg command for audio processing
- 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\""
- echo "$ffmpeg_command" | tee -a "$log_file"
- # Execute the FFmpeg command
- eval $ffmpeg_command 2>&1 | tee -a "$log_file"
- # Check for "Killed" message in the log file
- if ! check_for_killed_message; then
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
- exit 1
- fi
- if [ $? -eq 0 ]; then
- mv "$temp_output_file" "$output_file" # Rename the temporary file to the final output file
- mkdir -p "$video_processing_dir/$dir_path" # Create processing directory
- mv "$audio" "$video_processing_dir/$relative_path"
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Converted $audio. Your original files will be in the $video_processing_dir folder for comparison. Your new files are in $output_dir_base" | tee -a "$log_file" | fmt -w $width
- else
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
- exit 1
- fi
- }
- # ------------------------------
- # Video Encoder
- # ------------------------------
- width=$(tput cols)
- # Function to check the log file for "Killed" message
- check_for_killed_message() {
- if grep -q " Killed " "$log_file"; then
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
- exit 1
- fi
- }
- process_video() {
- local video="$1"
- local relative_path="${video#$video_drop_dir/}"
- local dir_path=$(dirname "$relative_path")
- local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
- local output_dir="$output_dir_base/$dir_path"
- local output_file="$output_dir/${base_name}_converted.mkv"
- # Get input video resolution
- input_resolution=$(ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$video" | tr -d '[:space:],')
- if [ -n "$resolution" ]; then
- if [ "$input_resolution" -lt "$resolution" ]; then
- local scale_filter="scale=-2:$input_resolution:flags=lanczos"
- echo "Input resolution ($input_resolution) is lower than user-defined resolution ($resolution). Keeping original resolution." | tee -a "$log_file"
- else
- local scale_filter="scale=-2:$resolution:flags=lanczos"
- echo "Input resolution ($input_resolution) is higher or equal to user-defined resolution ($resolution). Using user-defined resolution." | tee -a "$log_file"
- fi
- else
- echo "Resolution set to: original" | tee -a "$log_file"
- fi
- mkdir -p "$output_dir" # Create output directory
- echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
- # Get the frame rate of the input video
- 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)
- # Define common frame rates
- common_fps=(23.976 24 25 29.97 30 50 59.94 60)
- # Function to find the nearest valid frame rate
- nearest_fps() {
- local fps=$1
- local nearest=${common_fps[0]}
- local min_diff=$(echo "scale=5; $fps - ${common_fps[0]}" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
- for rate in "${common_fps[@]}"; do
- local diff=$(echo "scale=5; $fps - $rate" | bc | awk '{print ($1 >= 0) ? $1 : -$1}')
- if (( $(echo "$diff < $min_diff" | bc -l) )); then
- min_diff=$diff
- nearest=$rate
- fi
- done
- echo $nearest
- }
- # Round the frame rate to the nearest valid frame rate
- rounded_fps=$(nearest_fps $input_fps)
- # Determine the lower frame rate
- if (( $(echo "$rounded_fps > $output_fps" | bc -l) )); then
- final_fps=$output_fps
- else
- final_fps=$rounded_fps
- fi
- # Set the initial video filter option
- video_filter_option="yadif=2,fps=$final_fps"
- # Check if scale_filter is not empty
- if [ -n "$scale_filter" ]; then
- video_filter_option="${video_filter_option},${scale_filter}"
- fi
- echo "Video filter option: $video_filter_option" | tee -a "$log_file"
- # Detect the pixel format using ffprobe
- input_file="$video"
- 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}')
- echo "Pixel format: $pix_fmt"
- # Validate the pixel format
- valid_pix_fmt=$(ffmpeg -pix_fmts | grep -w "$pix_fmt")
- # Check if 10-bit encoding is selected
- if [[ "$pix_fmt" == *"10le"* || "$pix_fmt" == *"10be"* ]]; then
- 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"
- fi
- # Define a variable for probe size and analyze duration
- probe_analyze_opts="-probesize 2147483647 -analyzeduration 2147483647"
- # Detect subtitle codecs and convert unsupported ones
- subtitle_codecs=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=codec_name -of csv=p=0 "$input_file")
- subtitle_map=""
- if [ -n "$subtitle_codecs" ]; then
- subtitle_map="-map 0:s" # Include all subtitle streams
- i=0
- while read -r codec; do
- case "$codec" in
- # Text-based subtitles to be copied directly
- srt)
- subtitle_map="$subtitle_map -c:s:$i copy"
- ;;
- # Other text-based subtitles to be converted to SRT
- ass|ssa|webvtt|eia_608|eia_708|scc|sami|ttml|smi|teletext|mov_text|microdvd|subviewer)
- subtitle_map="$subtitle_map -c:s:$i srt"
- ;;
- # Bitmap-based subtitles to be converted to DVD subtitles
- dvdsub|pgs|vobsub|hdmv_pgs_subtitle|dvd_subtitle)
- subtitle_map="$subtitle_map -c:s:$i dvdsub"
- ;;
- # Copy other compatible subtitles
- *)
- subtitle_map="$subtitle_map -c:s:$i copy"
- ;;
- esac
- i=$((i + 1))
- done <<< "$subtitle_codecs"
- else
- echo "No subtitle streams detected." | tee -a "$log_file"
- fi
- # Combine common and custom FFmpeg options
- 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"
- # Construct the FFmpeg command
- local ffmpeg_command
- if [ -n "$valid_pix_fmt" ]; then
- if [ -n "$subtitle_map" ]; then
- ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt $subtitle_map"
- else
- ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" -pix_fmt $pix_fmt"
- fi
- else
- if [ -n "$subtitle_map" ]; then
- ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\" $subtitle_map"
- else
- ffmpeg_command="ffmpeg $combined_ffmpeg_options -vf \"$video_filter_option\""
- fi
- fi
- # Ensure all subtitle streams are marked as "default: off"
- subtitle_streams=$(ffprobe -v error $probe_analyze_opts -select_streams s -show_entries stream=index -of csv=p=0 "$input_file")
- if [ -n "$subtitle_streams" ]; then
- for stream_index in $subtitle_streams; do
- ffmpeg_command="$ffmpeg_command -disposition:s:$stream_index 0"
- done
- fi
- # Add the output file name at the end
- ffmpeg_command="$ffmpeg_command \"$output_file\""
- echo "FFmpeg command: $ffmpeg_command" | tee -a "$log_file"
- # Execute the FFmpeg command
- if ! eval $ffmpeg_command 2>&1 | tee -a "$log_file"; then
- echo "FFmpeg command failed. Check the log for details." | tee -a "$log_file"
- exit 1
- fi
- # Check for "Killed" message in the log file
- check_for_killed_message
- if [ $? -eq 0 ]; then
- mkdir -p "$video_processing_dir/$dir_path" # Create processing directory
- mv "$video" "$video_processing_dir/$relative_path"
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Complete. Your original files are in $video_processing_dir. Your new files are in $output_dir_base" | tee -a "$log_file" | fmt -w $width
- else
- echo ""
- echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
- exit 1
- fi
- }
- # --------------------------------------
- # Start Batch Encoding
- # --------------------------------------
- width=$(tput cols)
- stop_processing=false
- # Function to handle SIGINT (Ctrl+C)
- handle_sigint() {
- echo ""
- echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
- stop_processing=true
- exit 1 # Exit immediately without performing cleanup
- }
- # Trap SIGINT and call the handle_sigint function
- trap handle_sigint SIGINT
- # Process each file found
- eval "find \"$video_drop_dir\" -type f \( $filetypes \)" | while read -r file; do
- if [ "$stop_processing" = true ]; then
- echo "Stopping processing due to SIGINT."
- exit 1
- fi
- case "$file" in
- *.mp3|*.aac|*.wav|*.flac|*.ogg|*.m4a|*.wma|*.ac3|*.eac3|*.opus|*.amr|*.aiff|*.alac|*.caf|*.dts|*.mka|*.mp2|*.ra|*.tta|*.voc)
- process_audio "$file" || exit 1
- ;;
- *.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)
- process_video "$file" || exit 1
- ;;
- *.jpg|*.jpeg|*.png|*.bmp|*.tiff|*.gif|*.webp|*.heic|*.heif|*.jxl|*.ppm|*.pgm|*.pbm|*.pam|*.tga|*.sgi|*.pcx|*.ras|*.xbm|*.xpm|*.ico|*.dds|*.exr|*.hdr|*.svg)
- process_image "$file" || exit 1
- ;;
- esac
- done
- # -----------------------------
- # Finishing Up
- # -----------------------------
- width=$(tput cols)
- find "$video_drop_dir" -type d -empty -delete
- echo "removed empty folders in $video_drop_dir directory"
- # final output message
- echo ""
- echo "Log file is in $video_drop_dir. 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
- exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement