Advertisement
MaxDjently

Ziggle Wump Media Compressor 0.2-beta.09.05.2024

Sep 4th, 2024
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 17.02 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 and ChatGPT.
  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. # Usage: ./ziggle_wump.sh [-r resolution] [-f "ffmpeg_options"] [-h|--help]
  34. #   -r resolution        Custom resolution height preserving aspect ratio, Downscaling your videos will significantly reduce the file size, but may introduce artifacts and shimmering.  Upscaling will produce larger file sizes and not increase quality.
  35. #   -f "ffmpeg_options" Override default FFmpeg options with custom command line options.  ex. bash ./ziggle_wump.sh -f "-c:v libx264 -c:a libmp3lame"
  36. #   -h, --help           Display this help message
  37.  
  38. # 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.
  39. # 2. Make it executable: chmod +x ziggle_wump.sh
  40. # 3. Run the script: bash ./ziggle_wump.sh [options]
  41.  
  42. # -------------------
  43. #    README
  44. # -------------------
  45.  
  46. # Ziggle Wump: The Simple FFmpeg Command Line Companion Script for Termux on Android
  47.  
  48. # 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
  49.  
  50. # 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.
  51.  
  52. # Check out https://dontkillmyapp.com/ for more information and perhaps find a fix for your particular phone.
  53.  
  54. # Supported File Types:
  55. # Video:  mp4 mkv avi mov flv wmv webm mts
  56. # Audio: mp3 wav flac aac ogg m4a
  57.  
  58. # -----------------------------
  59. #             Title
  60. # -----------------------------
  61.  
  62. # Ziggle Wump Media Compressor 0.2-beta
  63.  
  64. # The Simple FFmpeg Command Line Companion Script for Termux on Android
  65.  
  66. # -----------------------------
  67. #        Variables
  68. # -----------------------------
  69.  
  70. # Full Log file path
  71. log_file="$HOME/storage/shared/Movies/VideoDrop/convert.log"
  72.  
  73. # Shortened log file path for terminal output
  74. log_file_echo=$(echo "$log_file" | sed 's|/data/data/com.termux/files/home|.../home|g')
  75.  
  76. # Default resolution (empty implies original resolution)
  77. default_resolution=""
  78.  
  79. # Full directory paths
  80. video_drop_dir="$HOME/storage/shared/Movies/VideoDrop"
  81. video_processing_dir="$HOME/storage/shared/Movies/VideoProcessing"
  82. output_dir_base="$HOME/storage/shared/Movies/VideoConverted"
  83.  
  84. # Shortened directory paths for terminal output
  85. video_drop_dir_echo=$(echo "$video_drop_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  86. video_processing_dir_echo=$(echo "$video_processing_dir" | sed 's|/data/data/com.termux/files/home|.../home|g')
  87. output_dir_base_echo=$(echo "$output_dir_base" | sed 's|/data/data/com.termux/files/home|.../home|g')
  88.  
  89. # Initialize optional variables
  90. resolution="$default_resolution"
  91. ffmpeg_custom_options=""
  92.  
  93. # -----------------------------
  94. #    Command Flags
  95. # -----------------------------
  96.  
  97. # Function to display help message
  98. show_help() {
  99.     width=$(tput cols)
  100.     echo "Place your media files in $video_drop_dir_echo." | tee -a "$log_file" | fmt -w $width
  101.     echo "Usage: $0 [-r resolution] [-f \"ffmpeg_options\"] [-h|--help]" | fmt -w $width
  102.     echo "  -r resolution ex. bash $0 -r 720               Custom resolution height preserving aspect ratio, Downscaling your videos will significantly reduce the file size, but may introduce artifacts and shimmering.  Upscaling will produce larger file sizes and not increase quality." | fmt -w $width
  103.     echo "  -f \"ffmpeg_options\"  Override default FFmpeg options with custom command line options.  ex. bash $0 -f \""-c:v libx264 -c:a libmp3lame\" | fmt -w $width
  104.     echo "  -h, --help           Display this help message" | fmt -w $width
  105.     exit 0
  106. }
  107.  
  108. # Parse command-line options
  109. while getopts "r:f:h" opt; do
  110.     case $opt in
  111.         r) resolution="$OPTARG" ;;  # Set custom resolution by height
  112.         f) ffmpeg_custom_options="$OPTARG" ;;  # Set custom FFmpeg options
  113.         h) show_help ;;  # Display help
  114.         *) show_help ;;  # Display help for invalid options
  115.     esac
  116. done
  117.  
  118. shift $((OPTIND -1))
  119.  
  120. # ---------------------------------
  121. #       Dependencies
  122. # ---------------------------------
  123.  
  124. # Ensure dependencies are installed and all packages are up to date.
  125.     echo "Updating, please wait..."
  126.     sleep 1
  127.     pkg update && pkg upgrade -y
  128.     if ! command -v ffmpeg &> /dev/null; then
  129.         pkg install ffmpeg -y
  130.     fi
  131.     if ! command -v ncurses-utils &> /dev/null; then
  132.         pkg install ncurses-utils -y
  133.     fi
  134. echo "Update complete."
  135.     sleep 1
  136.  
  137. # -----------------------------------------------------
  138. #     Create Directories and log file
  139. # -----------------------------------------------------
  140.  
  141. # Create necessary directories if they don't exist
  142. mkdir -p "$video_drop_dir" "$video_processing_dir" "$output_dir_base"
  143.  
  144. # Change to the VideoDrop directory
  145. cd "$video_drop_dir" || { echo "Directory change failed"; exit 1; }
  146.  
  147. # Check if log file exists
  148. if [ -f "$log_file" ]; then
  149.     echo "Old log file found.  Deleting..."
  150.     rm "$log_file"
  151.     echo "File deleted."
  152. else
  153.     echo "Log File does not exist.  The script will create $log_file_echo"
  154. fi
  155.  
  156. # ------------------------
  157. #     Start script
  158. # ------------------------
  159.  
  160. width=$(tput cols)
  161.  
  162. echo "Running... Press Ctrl+C to stop."
  163.     sleep 1
  164.  
  165. echo ""
  166. 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
  167.  
  168. echo ""
  169. 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
  170.  
  171. echo ""
  172. # Function to prompt the user to continue or quit
  173. prompt_continue_or_quit() {
  174.     while true; do
  175. # Recursively find and process videos and audio
  176. 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 '*.mts' -o -iname '*.mp3' -o -iname '*.wav' -o -iname '*.flac' -o -iname '*.aac' -o -iname '*.ogg' -o -iname '*.m4a' \) | wc -l)
  177.  
  178. if [ "$video_count" -eq 0 ]; then
  179.     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.  Supported File Types:  Video:  mp4 mkv avi mov flv wmv webm mts Audio: mp3 wav flac aac ogg m4a" | tee -a "$log_file" | fmt -w $width
  180.     exit 0
  181. fi
  182.  
  183. # Prompt text
  184. prompt_text="Compatible media files detected in $video_drop_dir_echo. You can start encoding now. Do you wish to proceed? (Y/N): "
  185.  
  186. # Format the prompt text
  187. formatted_prompt=$(echo "$prompt_text" | fmt -w $width)
  188.  
  189. # Read user input with formatted prompt
  190. read -p "$formatted_prompt" yn
  191. case $yn in
  192.     [Yy]* ) return 0;;  # Continue
  193.     [Nn]* ) echo "Exiting script."; exit 0;;  # Quit
  194.     * ) echo "Please answer Y or N.";;
  195. esac
  196. done
  197. }
  198.  
  199.     # Prompt the user to continue or quit
  200.     prompt_continue_or_quit
  201.  
  202. echo "Starting conversion process..." | tee -a "$log_file"
  203. sleep 1
  204.  
  205. # -----------------------------
  206. #    Audio Encoder
  207. # -----------------------------
  208.  
  209. width=$(tput cols)
  210.  
  211. # Function to check the log file for "Killed" message
  212. check_for_killed_message() {
  213.     if grep -q " Killed     " "$log_file"; then
  214.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file"
  215.         return 1
  216.     fi
  217.     return 0
  218. }
  219.  
  220. # Function to process audio files
  221. process_audio() {
  222.     local audio="$1"
  223.     local audio_echo=$(echo "$audio" | sed 's|/data/data/com.termux/files/home|/home|g')
  224.     local relative_path="${audio#$video_drop_dir/}"
  225.     local dir_path=$(dirname "$relative_path")
  226.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  227.     local output_dir="$output_dir_base/$dir_path"
  228.     local output_file="$output_dir/${base_name}_converted.opus"
  229.     local temp_output_file="$output_file.tmp"
  230.  
  231.     mkdir -p "$output_dir"  # Create output directory
  232.  
  233.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $audio to $output_file" | tee -a "$log_file"
  234.  
  235.     # Construct the FFmpeg command for audio processing
  236.     local ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$audio\" -c:a libopus -f opus \"$temp_output_file\""
  237.  
  238.     # Execute the FFmpeg command
  239.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  240.  
  241.     # Check for "Killed" message in the log file
  242.     if ! check_for_killed_message; then
  243.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Exiting." | tee -a "$log_file"
  244.         exit 1
  245.     fi
  246.  
  247.     if [ $? -eq 0 ]; then
  248.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  249.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  250.         mv "$audio" "$video_processing_dir/$relative_path"
  251.         echo ""
  252.         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
  253.     else
  254.         echo ""
  255.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$audio\". Check log file for details." | tee -a "$log_file"
  256.         exit 1
  257.     fi
  258. }
  259.  
  260. # ------------------------------
  261. #      Video Encoder
  262. # ------------------------------
  263.  
  264. width=$(tput cols)
  265.  
  266. # Function to check the log file for "Killed" message
  267. check_for_killed_message() {
  268.     if grep -q " Killed     " "$log_file"; then
  269.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error: Process was killed. Check log file for details." | tee -a "$log_file" | fmt -w $width
  270.         exit 1
  271.     fi
  272. }
  273.  
  274. # Function to process videos
  275. process_video() {
  276.     local video="$1"
  277.     local video_echo=$(echo "$video" | sed 's|/data/data/com.termux/files/home|.../home|g')
  278.     local relative_path="${video#$video_drop_dir/}"
  279.     local dir_path=$(dirname "$relative_path")
  280.     local base_name=$(basename "$relative_path" | tr -cd '[:alnum:]._ -')
  281.     local output_dir="$output_dir_base/$dir_path"
  282.     local output_file="$output_dir/${base_name}_converted.mkv"
  283.     local temp_output_file="$output_file.tmp"
  284.     local scale_filter=""
  285.    
  286.     if [ -n "$resolution" ]; then
  287.         scale_filter="scale=-2:$resolution,"
  288.         echo "Resolution set to: $resolution" | tee -a "$log_file"
  289.     else
  290.         echo "Resolution set to: original" | tee -a "$log_file"
  291.     fi
  292.  
  293.     mkdir -p "$output_dir"  # Create output directory
  294.  
  295.     echo "$(date '+%Y-%m-%d %H:%M:%S') Processing $video to $output_file" | tee -a "$log_file"
  296.  
  297.     # Construct the FFmpeg command
  298.     local ffmpeg_command
  299.     if [ -n "$ffmpeg_custom_options" ]; then
  300.         ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$video\" $ffmpeg_custom_options -f matroska \"$temp_output_file\""
  301.     else
  302.         ffmpeg_command="ffmpeg -nostdin -loglevel verbose -y -i \"$video\" -c:v libx265 -c:a libopus -vf \"${scale_filter}yadif=2,mpdecimate\" -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\" -ac 2 -fps_mode passthrough -f matroska \"$temp_output_file\""
  303.     fi
  304.  
  305.     echo "FFmpeg command: $ffmpeg_command" | tee -a "$log_file"
  306.     sleep 1
  307.  
  308.     # Execute the FFmpeg command
  309.     eval $ffmpeg_command 2>&1 | tee -a "$log_file"
  310.  
  311.     # Check for "Killed" message in the log file
  312.     check_for_killed_message
  313.  
  314.     if [ $? -eq 0 ]; then
  315.         mv "$temp_output_file" "$output_file"  # Rename the temporary file to the final output file
  316.         mkdir -p "$video_processing_dir/$dir_path"  # Create processing directory
  317.         mv "$video" "$video_processing_dir/$relative_path"
  318.         echo ""
  319.         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
  320.     else
  321.         echo ""
  322.         echo "$(date '+%Y-%m-%d %H:%M:%S') Error processing \"$video\". Check log file for details." | tee -a "$log_file"
  323.         exit 1
  324.     fi
  325. }
  326.  
  327. # --------------------------------------
  328. #    Start Batch Encoding
  329. # --------------------------------------
  330.  
  331. width=$(tput cols)
  332.  
  333. # Recursively find and process videos and audio
  334. 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 '*.mts' -o -iname '*.mp3' -o -iname '*.wav' -o -iname '*.flac' -o -iname '*.aac' -o -iname '*.ogg' -o -iname '*.m4a' \) | wc -l)
  335.  
  336. # Process each audio file found
  337. 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
  338.  
  339.     stop_processing=false
  340.  
  341. # Function to handle SIGINT (Ctrl+C)
  342. handle_sigint() {
  343.     echo ""
  344.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  345.     exit 1  # Exit immediately without performing cleanup
  346. }
  347.  
  348. # Trap SIGINT and call the handle_sigint function
  349. trap handle_sigint SIGINT
  350.  
  351.     if [ "$stop_processing" = true ]; then
  352.         echo "Stopping processing due to SIGINT."
  353.         exit 1
  354.     fi
  355.     process_audio "$audio" || exit 1
  356. done
  357.  
  358. # Process each video found
  359. 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 '*.mts' \) | while read -r video; do
  360.  
  361.     stop_processing=false
  362.  
  363. # Function to handle SIGINT (Ctrl+C)
  364. handle_sigint() {
  365.     echo ""
  366.     echo "Caught SIGINT (Ctrl+C). Exiting immediately." | fmt -w $width
  367.     exit 1  # Exit immediately without performing cleanup
  368. }
  369.  
  370. # Trap SIGINT and call the handle_sigint function
  371. trap handle_sigint SIGINT
  372.  
  373.     if [ "$stop_processing" = true ]; then
  374.         echo "Stopping processing due to SIGINT."
  375.         exit 1
  376.     fi
  377.     process_video "$video" || exit 1
  378. done
  379.  
  380. # -----------------------------
  381. #     Finishing Up
  382. # -----------------------------
  383.  
  384. width=$(tput cols)
  385.  
  386. # Check for empty directories and remove them, except for the VideoDrop folder itself
  387.  
  388. # Set a maximum number of iterations to prevent hanging, this will remove up to 10 levels of subdirectories
  389. max_iterations=10
  390. iteration=0
  391.  
  392. while find "$video_drop_dir" -depth -type d -empty -not -path "$video_drop_dir" -exec rmdir "{}" \; > /dev/null 2>&1; do
  393.     iteration=$((iteration + 1))
  394.     if [ "$iteration" -ge "$max_iterations" ]; then
  395.         break
  396.     fi
  397.     : # No-op, just repeat the loop
  398. done
  399.  
  400. # final output message
  401. echo ""
  402. 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
  403. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement