Advertisement
MaxDjently

Ziggle Wump Media Compressor 0.1-alpha final

Aug 24th, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 16.90 KB | Source Code | 0 0
  1. #!/data/data/com.termux/files/usr/bin/bash
  2.  
  3. # --------------------
  4. #     Licence
  5. # --------------------
  6.  
  7. # 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.
  8.  
  9. # 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.
  10.  
  11. # You should have received a copy of the GNU General Public License along with  this program. If not, see <https://www.gnu.org/licenses/>.
  12.  
  13. # -----------------
  14. #     About
  15. # -----------------
  16.  
  17. # This script is for Termux on Android and is not associated with the apps it uses.
  18.  
  19. # Copyright Joshua Hansen and contributors: Microsoft Co-Pilot and ChatGPT.
  20.  
  21. # 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.
  22.  
  23. # -----------------------
  24. #   Instructions
  25. # -----------------------
  26.  
  27. # Usage: ./ziggle_wump.sh [-r resolution] [-d] [-f "ffmpeg_options"] [-h|--help]
  28. #   -r resolution        Custom resolution height for video conversion preserving aspect ratio (default: original resolution)  Downscaling your videos will significantly reduce the file size, but may introduce artifacts and shimmering.  Upscaling will only result in larger file sizes.  It will not make your video look better.
  29. #   -d                   Use default behavior (original resolution x265 video, opus audio)
  30. #   -f "ffmpeg_options" Override default FFmpeg options with custom command line options.  ex. bash ./ziggle_wump.sh -f "-c:v libx265 -c:a libopus -x265-params "aq-mode=1:psy-rd=0.75:psy-rdoq=4.0:rd=4:rdoq-level=1:rect=0:strong-intra-smoothing=0""
  31. #   -h, --help           Display this help message
  32.  
  33. # 1. Download or Copy this script to a file, and rename it if you want.  e.g., ziggle_wump.sh.  Putting it in your Movies folder will make it easy to find on both Android and Termux, although it's possible to put this in your /usr/bin to use it as a system app.  Your mileage may vary.
  34. # 2. Make it executable: chmod +x ziggle_wump.sh
  35. # 3. Run the script: bash ./ziggle_wump.sh [options]
  36.  
  37. # -------------------
  38. #    README
  39. # -------------------
  40.  
  41. # Ziggle Wump: The Simple FFmpeg Command Line Companion Script for Termux on Android
  42.  
  43. # DISCLAIMER:  THE SCRIPT DOES NOT ALLOW YOU TO CONVERT ENCRYPTED FILES, COPYRIGHTED CONTENT IS GENERALLY ENCRYPTED. THE SCRIPT IN ITSELF DOES NOT VIOLATE COPYRIGHT BUT THE USER MIGHT.  CODE TO PREVENT CIRCUMVENTION IS BEYOND MY CAPABILITY.  NOR SHOULD IT BE MY RESPONSIBILITY, IT'S THE COPYRIGHT HOLDERS RESPONSIBILITY 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
  44.  
  45. # NOTE:  Some phones have a battery saving feature such as the Galaxy S24, that can impact the encoding process and leave you with partially encoded files.  Please make sure Termux is in focus otherwise, either full screen or split screen if you want to do other things, and keep the screen on while encoding.
  46.  
  47. # Check out https://dontkillmyapp.com/ for more information and perhaps find a fix for your particular phone.
  48.  
  49. # -----------------------------
  50. #             Title
  51. # -----------------------------
  52.  
  53. # ziggle_wump
  54.  
  55. # The Simple FFmpeg Command Line Companion Script for Termux on Android
  56.  
  57. # -----------------------------
  58. #        Variables
  59. # -----------------------------
  60.  
  61. # Full Log file path
  62. log_file="$HOME/storage/shared/Movies/VideoDrop/convert.log"
  63.  
  64. # Shortened log file path for terminal output
  65. log_file_echo=$(echo "$log_file" | sed 's|/data/data/com.termux/files/home|.../home|g')
  66.  
  67. # Default resolution (empty implies original resolution)
  68. default_resolution=""
  69.  
  70. # Full directory paths
  71. video_drop_dir="$HOME/storage/shared/Movies/VideoDrop"
  72. video_processing_dir="$HOME/storage/shared/Movies/VideoProcessing"
  73. output_dir_base="$HOME/storage/shared/Movies/VideoConverted"
  74.  
  75. # Shortened directory paths for terminal output
  76. video_drop_dir_echo=$(echo "$video_drop_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  77. video_processing_dir_echo=$(echo "$video_processing_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  78. output_dir_base_echo=$(echo "$output_dir_base" | sed 's|/data/data/com.termux/files/home|.../home|g')
  79.  
  80. # Initialize optional variables
  81. resolution="$default_resolution"
  82. ffmpeg_custom_options=""
  83.  
  84. # -----------------------------
  85. #    Command Flags
  86. # -----------------------------
  87.  
  88. # Function to display help message
  89. show_help() {
  90.     width=$(tput cols)
  91.     echo "Ziggle Wump will create $video_drop_dir_echo the first time if it doesn't exist.  Place your media files here." | tee -a "$log_file" | fmt -w $width
  92.     echo "Usage: $0 [-r resolution] [-d] [-f \"ffmpeg_options\"] [-h|--help]" | fmt -w $width
  93.     echo "  -r resolution ex. bash ./ziggle_wump.sh -r 720                      Custom resolution height for video conversion preserving aspect ratio (default: original resolution)  Downscaling your videos will significantly reduce the file size, but may introduce artifacts and shimmering.  Upscaling will only result in larger file sizes.  It will not make your video look better." | fmt -w $width
  94.     echo "  -d                   Use default behavior"
  95.     echo "(original resolution x265 video, opus audio)"
  96.     echo "  -f \"ffmpeg_options\"  Override default FFmpeg options with custom command line options.  ex. bash ./ziggle_wump.sh -f \""-c:v libx265 -c:a libopus -x265-params "aq-mode=1:psy-rd=0.75:psy-rdoq=4.0:rd=4:rdoq-level=1:rect=0:strong-intra-smoothing=0\"\"" | fmt -w $width
  97.     echo "  -h, --help           Display this help message" | fmt -w $width
  98.     exit 0
  99. }
  100.  
  101. # Parse command-line options
  102. while getopts "r:df:h" opt; do
  103.     case $opt in
  104.         r) resolution="$OPTARG" ;;  # Set custom resolution by height
  105.         d) resolution="$default_resolution" ;;  # Use default settings
  106.         f) ffmpeg_custom_options="$OPTARG" ;;  # Set custom FFmpeg options
  107.         h) show_help ;;  # Display help
  108.         *) show_help ;;  # Display help for invalid options
  109.     esac
  110. done
  111.  
  112. shift $((OPTIND -1))
  113.  
  114. # ---------------------------------
  115. #       Dependencies
  116. # ---------------------------------
  117.  
  118. # Ensure dependencies are installed and all packages are up to date.
  119.     echo "Updating, please wait..."
  120.     sleep 1
  121.     pkg update && pkg upgrade -y
  122.     if ! command -v ffmpeg &> /dev/null; then
  123.         pkg install ffmpeg -y
  124.     fi
  125.     if ! command -v ncurses-utils &> /dev/null; then
  126.         pkg install ncurses-utils -y
  127.     fi
  128. echo "Update complete."
  129.     sleep 1
  130.  
  131. # -----------------------------------------------------
  132. #     Create Directories and log file
  133. # -----------------------------------------------------
  134.  
  135. # Create necessary directories if they don't exist
  136. mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
  137.  
  138. # Change to the VideoDrop directory
  139. cd "$video_drop_dir" || { echo "Directory change failed"; exit 1; }
  140.  
  141. # Check if log file exists
  142. if [ -f "$log_file" ]; then
  143.     echo "Old log file found.  Deleting..."
  144.     rm "$log_file"
  145.     echo "File deleted."
  146. else
  147.     echo "Log File does not exist.  The script will create $log_file_echo"
  148. fi
  149.  
  150. # ------------------------
  151. #     Start script
  152. # ------------------------
  153.  
  154. width=$(tput cols)
  155.  
  156. echo "Running... Press Ctrl+C to stop."
  157.     sleep 1
  158.  
  159. echo ""
  160. echo "Ziggle Wump will create $video_drop_dir_echo the first time if it doesn't exist.  Place your media files here." | tee -a "$log_file" | fmt -w $width
  161.  
  162. echo ""
  163. echo "NOTE:  Some phones have a battery saving feature such as the Galaxy S24, that can impact the encoding process and leave you with partially encoded files.  Please make sure Termux is in  focus, either full screen or split screen if you want to do other things, and keep the screen on while encoding." | tee -a "$log_file" | fmt -w $width
  164.  
  165. echo ""
  166. echo "Check out https://dontkillmyapp.com/ for more information and perhaps find a fix for your particular phone." | tee -a "$log_file" | fmt -w $width
  167.  
  168. echo ""
  169. # Function to prompt the user to continue or quit
  170. prompt_continue_or_quit() {
  171.     while true; do
  172. # Recursively find and process videos and audio
  173. video_count=$(find "$video_drop_dir" -type f \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.avi' -o -iname '*.mov' -o -iname '*.flv' -o -iname '*.wmv' -o -iname '*.webm' -o -iname '*.mp3' -o -iname '*.wav' -o -iname '*.flac' -o -iname '*.aac' -o -iname '*.ogg' -o -iname '*.m4a' \) | wc -l)
  174.  
  175. if [ "$video_count" -eq 0 ]; then
  176.     echo "No videos or audio found. $video_drop_dir_echo folder created. Place your videos and audio here including in folders using your favorite file manager for Android, and then run the script again." | tee -a "$log_file" | fmt -w $width
  177.     exit 0
  178. fi
  179.  
  180. # Prompt text
  181. prompt_text="Compatible media files detected in $video_drop_dir_echo. You can start encoding now. Do you wish to proceed? (Y/N): "
  182.  
  183. # Format the prompt text
  184. formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
  185.  
  186. # Read user input with formatted prompt
  187. read -p "$formatted_prompt" yn
  188. case $yn in
  189.     [Yy]* ) return 0;;  # Continue
  190.     [Nn]* ) echo "Exiting script."; exit 0;;  # Quit
  191.     * ) echo "Please answer Y or N.";;
  192. esac
  193. done
  194. }
  195.  
  196.     # Prompt the user to continue or quit
  197.     prompt_continue_or_quit
  198.  
  199. echo "Starting conversion process..." | tee -a "$log_file"
  200. sleep 1
  201.  
  202. # -----------------------------
  203. #    Audio Encoder
  204. # -----------------------------
  205.  
  206. width=$(tput cols)
  207.  
  208. # Function to check the log file for "Killed" message
  209. check_for_killed_message() {
  210.     if grep -q " Killed     " "$log_file"; then
  211.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
  212.         return 1
  213.     fi
  214.     return 0
  215. }
  216.  
  217. # Function to process audio files
  218. process_audio() {
  219.     local audio="$1"
  220.     local audio_echo=$(echo "$audio" | sed 's|/data/data/com.termux/files/home|/home|g')
  221.     local relative_path="${audio#$video_drop_dir/}"
  222.     local dir_path=$(dirname "$relative_path")
  223.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  224.     local output_dir="$output_dir_base/$dir_path"
  225.     local output_file="$output_dir/${base_name}_converted.opus"
  226.     local temp_output_file="$output_file.tmp"
  227.  
  228.     mkdir -p "$output_dir"  # Create output directory
  229.  
  230.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
  231.  
  232.     # Construct the FFmpeg command for audio processing
  233.     local ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$audio\" -c:a libopus -f opus \"$temp_output_file\""
  234.  
  235.     # Execute the FFmpeg command
  236.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  237.  
  238.     # Check for "Killed" message in the log file
  239.     if ! check_for_killed_message; then
  240.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
  241.         exit 1
  242.     fi
  243.  
  244.     if [ $? -eq 0 ]; then
  245.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  246.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  247.         mv "$audio" "$video_processing_dir/$relative_path"
  248.         echo ""
  249.         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
  250.     else
  251.         echo ""
  252.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
  253.         exit 1
  254.     fi
  255. }
  256.  
  257. # ------------------------------
  258. #      Video Encoder
  259. # ------------------------------
  260.  
  261. width=$(tput cols)
  262.  
  263. # Function to check the log file for "Killed" message
  264. check_for_killed_message() {
  265.     if grep -q " Killed     " "$log_file"; then
  266.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
  267.         exit 1
  268.     fi
  269. }
  270.  
  271. # Function to process videos
  272. process_video() {
  273.     local video="$1"
  274.     local video_echo=$(echo "$video" | sed 's|/data/data/com.termux/files/home|.../home|g')
  275.     local relative_path="${video#$video_drop_dir/}"
  276.     local dir_path=$(dirname "$relative_path")
  277.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  278.     local output_dir="$output_dir_base/$dir_path"
  279.     local output_file="$output_dir/${base_name}_converted.mkv"
  280.     local temp_output_file="$output_file.tmp"
  281.     local scale_filter=""
  282.     [ -n "$resolution" ] && scale_filter="-vf \"scale=trunc(oh*a/2)*2:$resolution,setsar=1\""
  283.  
  284.     mkdir -p "$output_dir"  # Create output directory
  285.  
  286.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
  287.    
  288.     # Construct the FFmpeg command
  289.     local ffmpeg_command
  290.     if [ -n "$ffmpeg_custom_options" ]; then
  291.         ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$video\" $ffmpeg_custom_options -f matroska \"$temp_output_file\""
  292.     else
  293.         ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$video\" -c:v libx265 -c:a libopus $scale_filter -x265-params \"keyint=250:aq-mode=1:psy-rd=0.75:psy-rdoq=4.0:rd=4:rdoq-level=1:rect=0:strong-intra-smoothing=0\" -f matroska \"$temp_output_file\""
  294.     fi
  295.  
  296.     # Execute the FFmpeg command
  297.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  298.  
  299.     # Check for "Killed" message in the log file
  300.     check_for_killed_message
  301.  
  302.     if [ $? -eq 0 ]; then
  303.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  304.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  305.         mv "$video" "$video_processing_dir/$relative_path"
  306.         echo ""
  307.         echo "$(date '+%Y-%m-%d %H:%M:%S') Converted $video_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
  308.     else
  309.         echo ""
  310.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
  311.         exit 1
  312.     fi
  313. }
  314.  
  315. # --------------------------------------
  316. #    Start Batch Encoding
  317. # --------------------------------------
  318.  
  319. width=$(tput cols)
  320.  
  321. # Recursively find and process videos and audio
  322. video_count=$(find "$video_drop_dir" -type f \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.avi' -o -iname '*.mov' -o -iname '*.flv' -o -iname '*.wmv' -o -iname '*.webm' -o -iname '*.mp3' -o -iname '*.wav' -o -iname '*.flac' -o -iname '*.aac' -o -iname '*.ogg' -o -iname '*.m4a' \) | wc -l)
  323.  
  324. # Process each audio file found
  325. find "$video_drop_dir" -type f \( -iname '*.mp3' -o -iname '*.wav' -o -iname '*.flac' -o -iname '*.aac' -o -iname '*.ogg' -o -iname '*.m4a' \) | while read -r audio; do
  326.  
  327.     stop_processing=false
  328.  
  329. # Function to handle SIGINT (Ctrl+C)
  330. handle_sigint() {
  331.     echo ""
  332.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  333.     exit 1  # Exit immediately without performing cleanup
  334. }
  335.  
  336. # Trap SIGINT and call the handle_sigint function
  337. trap handle_sigint SIGINT
  338.  
  339.     if [ "$stop_processing" = true ]; then
  340.         echo "Stopping processing due to SIGINT."
  341.         exit 1
  342.     fi
  343.     process_audio "$audio" || exit 1
  344. done
  345.  
  346. # Process each video found
  347. find "$video_drop_dir" -type f \( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.avi' -o -iname '*.mov' -o -iname '*.flv' -o -iname '*.wmv' -o -iname '*.webm' \) | while read -r video; do
  348.  
  349.     stop_processing=false
  350.  
  351. # Function to handle SIGINT (Ctrl+C)
  352. handle_sigint() {
  353.     echo ""
  354.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  355.     exit 1  # Exit immediately without performing cleanup
  356. }
  357.  
  358. # Trap SIGINT and call the handle_sigint function
  359. trap handle_sigint SIGINT
  360.  
  361.     if [ "$stop_processing" = true ]; then
  362.         echo "Stopping processing due to SIGINT."
  363.         exit 1
  364.     fi
  365.     process_video "$video" || exit 1
  366. done
  367.  
  368. # -----------------------------
  369. #     Finishing Up
  370. # -----------------------------
  371.  
  372. width=$(tput cols)
  373.  
  374. # Check for empty directories and remove them, except for the VideoDrop folder
  375. find "$video_drop_dir" -type d -empty -not -path "$video_drop_dir" -exec echo "Removing empty directory: {} Checking..." \; -exec rmdir {} \; | fmt -w $width
  376.  
  377. echo ""
  378. echo "Log file is in $video_drop_dir_echo.  There may also be nested folders that are empty, and unprocessed media files or other incompatible files.  Some files may need to be remuxed for compatibility." | tee -a "$log_file" | fmt -w $width
  379. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement