Advertisement
MaxDjently

Ziggle Wump Media Compressor 0.2-beta1

Aug 23rd, 2024 (edited)
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 16.78 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 0.2-beta1
  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] [-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 "  -f \"ffmpeg_options\"  Override default FFmpeg options with custom command line options.  ex. bash ./ziggle_wump.sh -f \""-c:v libx265 -c:a libopus\"\" | fmt -w $width
  95.     echo "  -h, --help           Display this help message" | fmt -w $width
  96.     exit 0
  97. }
  98.  
  99. # Parse command-line options
  100. while getopts "r:f:h" opt; do
  101.     case $opt in
  102.         r) resolution="$OPTARG" ;;  # Set custom resolution by height
  103.         f) ffmpeg_custom_options="$OPTARG" ;;  # Set custom FFmpeg options
  104.         h) show_help ;;  # Display help
  105.         *) show_help ;;  # Display help for invalid options
  106.     esac
  107. done
  108.  
  109. shift $((OPTIND -1))
  110.  
  111. # ---------------------------------
  112. #       Dependencies
  113. # ---------------------------------
  114.  
  115. # Ensure dependencies are installed and all packages are up to date.
  116.     echo "Updating, please wait..."
  117.     sleep 1
  118.     pkg update && pkg upgrade -y
  119.     if ! command -v ffmpeg &> /dev/null; then
  120.         pkg install ffmpeg -y
  121.     fi
  122.     if ! command -v ncurses-utils &> /dev/null; then
  123.         pkg install ncurses-utils -y
  124.     fi
  125. echo "Update complete."
  126.     sleep 1
  127.  
  128. # -----------------------------------------
  129. #     Create Directories and log file
  130. # -----------------------------------------
  131.  
  132. # Create necessary directories if they don't exist
  133. mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
  134.  
  135. # Change to the VideoDrop directory
  136. cd "$video_drop_dir" || { echo "Directory change failed"; exit 1; }
  137.  
  138. # Check if log file exists
  139. if [ -f "$log_file" ]; then
  140.     echo "Old log file found.  Deleting..."
  141.     rm "$log_file"
  142.     echo "File deleted."
  143. else
  144.     echo "Log File does not exist.  The script will create $log_file_echo"
  145. fi
  146.  
  147. # ------------------------
  148. #     Start script
  149. # ------------------------
  150.  
  151. width=$(tput cols)
  152.  
  153. echo "Running... Press Ctrl+C to stop."
  154.     sleep 1
  155.  
  156. echo ""
  157. 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
  158.  
  159. echo ""
  160. 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
  161.  
  162. echo ""
  163. 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
  164.  
  165. echo ""
  166. # Function to prompt the user to continue or quit
  167. prompt_continue_or_quit() {
  168.     while true; do
  169. # Recursively find and process videos and audio
  170. 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)
  171.  
  172. if [ "$video_count" -eq 0 ]; then
  173.     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
  174.     exit 0
  175. fi
  176.  
  177. # Prompt text
  178. prompt_text="Compatible media files detected in $video_drop_dir_echo. You can start encoding now. Do you wish to proceed? (Y/N): "
  179.  
  180. # Format the prompt text
  181. formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
  182.  
  183. # Read user input with formatted prompt
  184. read -p "$formatted_prompt" yn
  185. case $yn in
  186.     [Yy]* ) return 0;;  # Continue
  187.     [Nn]* ) echo "Exiting script."; exit 0;;  # Quit
  188.     * ) echo "Please answer Y or N.";;
  189. esac
  190. done
  191. }
  192.  
  193.     # Prompt the user to continue or quit
  194.     prompt_continue_or_quit
  195.  
  196. echo "Starting conversion process..." | tee -a "$log_file"
  197. sleep 1
  198.  
  199. # -----------------------------
  200. #    Audio Encoder
  201. # -----------------------------
  202.  
  203. width=$(tput cols)
  204.  
  205. # Function to check the log file for "Killed" message
  206. check_for_killed_message() {
  207.     if grep -q " Killed     " "$log_file"; then
  208.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
  209.         return 1
  210.     fi
  211.     return 0
  212. }
  213.  
  214. # Function to process audio files
  215. process_audio() {
  216.     local audio="$1"
  217.     local audio_echo=$(echo "$audio" | sed 's|/data/data/com.termux/files/home|/home|g')
  218.     local relative_path="${audio#$video_drop_dir/}"
  219.     local dir_path=$(dirname "$relative_path")
  220.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  221.     local output_dir="$output_dir_base/$dir_path"
  222.     local output_file="$output_dir/${base_name}_converted.opus"
  223.     local temp_output_file="$output_file.tmp"
  224.  
  225.     mkdir -p "$output_dir"  # Create output directory
  226.  
  227.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
  228.  
  229.     # Construct the FFmpeg command for audio processing
  230.     local ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$audio\" -c:a libopus -f opus \"$temp_output_file\""
  231.  
  232.     # Execute the FFmpeg command
  233.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  234.  
  235.     # Check for "Killed" message in the log file
  236.     if ! check_for_killed_message; then
  237.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
  238.         exit 1
  239.     fi
  240.  
  241.     if [ $? -eq 0 ]; then
  242.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  243.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  244.         mv "$audio" "$video_processing_dir/$relative_path"
  245.         echo ""
  246.         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
  247.     else
  248.         echo ""
  249.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
  250.         exit 1
  251.     fi
  252. }
  253.  
  254. # ------------------------------
  255. #      Video Encoder
  256. # ------------------------------
  257.  
  258. width=$(tput cols)
  259.  
  260. # Function to check the log file for "Killed" message
  261. check_for_killed_message() {
  262.     if grep -q " Killed     " "$log_file"; then
  263.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
  264.         exit 1
  265.     fi
  266. }
  267.  
  268. # Function to process videos
  269. process_video() {
  270.     local video="$1"
  271.     local video_echo=$(echo "$video" | sed 's|/data/data/com.termux/files/home|.../home|g')
  272.     local relative_path="${video#$video_drop_dir/}"
  273.     local dir_path=$(dirname "$relative_path")
  274.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  275.     local output_dir="$output_dir_base/$dir_path"
  276.     local output_file="$output_dir/${base_name}_converted.mkv"
  277.     local temp_output_file="$output_file.tmp"
  278.     local scale_filter=""
  279.     [ -n "$resolution" ] && scale_filter="-vf \"scale=trunc(oh*a/2)*2:$resolution,setsar=1\""
  280.  
  281.     mkdir -p "$output_dir"  # Create output directory
  282.  
  283.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
  284.    
  285.     # Construct the FFmpeg command
  286.     local ffmpeg_command
  287.     if [ -n "$ffmpeg_custom_options" ]; then
  288.         ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$video\" $ffmpeg_custom_options -f matroska \"$temp_output_file\""
  289.     else
  290.         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\""
  291.     fi
  292.  
  293.     # Execute the FFmpeg command
  294.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  295.  
  296.     # Check for "Killed" message in the log file
  297.     check_for_killed_message
  298.  
  299.     if [ $? -eq 0 ]; then
  300.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  301.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  302.         mv "$video" "$video_processing_dir/$relative_path"
  303.         echo ""
  304.         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
  305.     else
  306.         echo ""
  307.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
  308.         exit 1
  309.     fi
  310. }
  311.  
  312. # --------------------------------------
  313. #    Start Batch Encoding
  314. # --------------------------------------
  315.  
  316. width=$(tput cols)
  317.  
  318. # Recursively find and process videos and audio
  319. 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)
  320.  
  321. # Process each audio file found
  322. 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
  323.  
  324.     stop_processing=false
  325.  
  326. # Function to handle SIGINT (Ctrl+C)
  327. handle_sigint() {
  328.     echo ""
  329.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  330.     exit 1  # Exit immediately without performing cleanup
  331. }
  332.  
  333. # Trap SIGINT and call the handle_sigint function
  334. trap handle_sigint SIGINT
  335.  
  336.     if [ "$stop_processing" = true ]; then
  337.         echo "Stopping processing due to SIGINT."
  338.         exit 1
  339.     fi
  340.     process_audio "$audio" || exit 1
  341. done
  342.  
  343. # Process each video found
  344. 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
  345.  
  346.     stop_processing=false
  347.  
  348. # Function to handle SIGINT (Ctrl+C)
  349. handle_sigint() {
  350.     echo ""
  351.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  352.     exit 1  # Exit immediately without performing cleanup
  353. }
  354.  
  355. # Trap SIGINT and call the handle_sigint function
  356. trap handle_sigint SIGINT
  357.  
  358.     if [ "$stop_processing" = true ]; then
  359.         echo "Stopping processing due to SIGINT."
  360.         exit 1
  361.     fi
  362.     process_video "$video" || exit 1
  363. done
  364.  
  365. # -----------------------------
  366. #     Finishing Up
  367. # -----------------------------
  368.  
  369. width=$(tput cols)
  370.  
  371. # Check for empty directories and remove them, except for the VideoDrop folder itself
  372. max_iterations=10  # Set a maximum number of iterations to prevent hanging
  373. iteration=0
  374.  
  375. while find "$video_drop_dir" -depth -type d -empty -not -path "$video_drop_dir" -exec rmdir "{}" \; > /dev/null 2>&1; do
  376.     iteration=$((iteration + 1))
  377.     if [ "$iteration" -ge "$max_iterations" ]; then
  378.         break
  379.     fi
  380.     : # No-op, just repeat the loop
  381. done
  382.  
  383.  
  384. echo ""
  385. 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
  386. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement