#!/bin/bash # Script to create 4K compilation with 4 horizontal videos in a 2x2 grid # Canvas: 3840x2160 (4K) # Each horizontal video: 1920x1080 # Positioning (perfect fit): # Top-left: X=0, Y=0 # Top-right: X=1920, Y=0 # Bottom-left: X=0, Y=1080 # Bottom-right: X=1920, Y=1080 # Uses NVIDIA NVENC GPU acceleration for fast encoding # Enable strict error handling set -o pipefail # Catch failures in piped commands # Use environment variables if set (for Docker), otherwise use default paths GIFS_DIR="${GIFS_PATH:-/media/bunker-admin/Internal/plex/xxx/media/local/gifs}" OUTPUT_DIR="${INBOX_PATH:-/media/bunker-admin/Internal/plex/xxx/media/local/inbox}" # Directory exclusion (colon-separated list of directory names to exclude) EXCLUDED_DIRS="${EXCLUDED_DIRS:-}" # Filter function for excluding directories (handles newline-terminated input) filter_excluded() { if [[ -z "$EXCLUDED_DIRS" ]]; then cat # Pass through unchanged else local pattern pattern=$(echo "$EXCLUDED_DIRS" | sed 's/:/|/g') grep -Ev "/($pattern)/" fi } cd "$GIFS_DIR" || exit 1 # Check if ffmpeg is available if ! command -v ffmpeg &> /dev/null; then echo "Error: ffmpeg is not installed. Please install ffmpeg." exit 1 fi # Check if ffprobe is available if ! command -v ffprobe &> /dev/null; then echo "Error: ffprobe is not installed. Please install ffprobe." exit 1 fi # Check if NVENC is available if ! ffmpeg -hide_banner -encoders 2>/dev/null | grep -q h264_nvenc; then echo "Warning: NVENC encoder not available. Falling back to CPU encoding." ENCODER="libx264" ENCODER_OPTS="-preset medium -crf 23" else # Check if NVENC encoder is currently in use (e.g., by Steam) enc_usage=$(nvidia-smi dmon -c 1 2>/dev/null | tail -1 | awk '{print $7}') if [[ "$enc_usage" -gt 50 ]]; then if [[ "${NONINTERACTIVE:-0}" == "1" ]]; then echo "GPU encoder in use (${enc_usage}%), proceeding anyway in non-interactive mode" ENCODER="h264_nvenc" ENCODER_OPTS="-preset p4 -cq 23 -rc vbr -gpu 0 -b_ref_mode 0" else echo "" echo "⚠️ WARNING: GPU encoder is currently in use (${enc_usage}% utilization)" echo " This is likely Steam or another application using NVENC." echo "" echo " Options:" echo " 1) Close Steam/other apps and press Enter to continue with GPU" echo " 2) Type 'cpu' to use CPU encoding instead (slower)" echo " 3) Press Ctrl+C to cancel" echo "" read -p "Choice: " enc_choice if [[ "$enc_choice" == "cpu" ]]; then echo "Using CPU encoding..." ENCODER="libx264" ENCODER_OPTS="-preset medium -crf 23" else # Re-check encoder usage enc_usage=$(nvidia-smi dmon -c 1 2>/dev/null | tail -1 | awk '{print $7}') if [[ "$enc_usage" -gt 50 ]]; then echo "⚠️ Encoder still in use (${enc_usage}%). Will try GPU but may fall back to CPU." else echo "✓ GPU encoder now available" fi ENCODER="h264_nvenc" ENCODER_OPTS="-preset p4 -cq 23 -rc vbr -gpu 0 -b_ref_mode 0" fi fi else echo "✓ NVENC GPU encoder detected and available" ENCODER="h264_nvenc" ENCODER_OPTS="-preset p4 -cq 23 -rc vbr -gpu 0 -b_ref_mode 0" fi fi # Get current date for filename current_date=$(date +%d-%m-%Y) echo "" echo "=========================================" echo " Quad Horizontal 4K Compilation (2x2)" echo " Encoder: $ENCODER" echo " Date: $current_date" echo "=========================================" echo "" # Non-interactive mode: use NUM_SETS from environment or default to 100 if [[ "${NONINTERACTIVE:-0}" == "1" ]]; then NUM_SETS="${NUM_SETS:-100}" echo "Non-interactive mode: Using $NUM_SETS sets" else # Interactive menu to select number of clip sets echo "Select compilation size (sets of 4 videos):" echo " 1) 30 sets (120 clips total)" echo " 2) 60 sets (240 clips total)" echo " 3) 100 sets (400 clips total, default)" echo "" read -p "Enter choice [1-3] (default: 3): " size_choice echo "" case "$size_choice" in 1) NUM_SETS=30 ;; 2) NUM_SETS=60 ;; *) NUM_SETS=100 ;; esac fi NUM_CLIPS=$((NUM_SETS * 4)) echo "Creating compilation with $NUM_SETS sets ($NUM_CLIPS clips total)" # Log excluded directories if any if [[ -n "$EXCLUDED_DIRS" ]]; then echo "Excluding directories: $EXCLUDED_DIRS" fi echo "" start_time=$(date +%s) # Function to get video duration in seconds get_duration_seconds() { local file="$1" ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file" 2>/dev/null | cut -d. -f1 } # Function to format duration as H:MM format_duration() { local seconds="$1" local hours=$((seconds / 3600)) local minutes=$(((seconds % 3600) / 60)) printf "%d:%02d" "$hours" "$minutes" } # Function to show progress bar show_progress() { local current=$1 local total=$2 local width=40 local percentage=$((current * 100 / total)) local filled=$((width * current / total)) local empty=$((width - filled)) printf "\r → Processing set %d/%d [" "$current" "$total" printf "%${filled}s" | tr ' ' '█' printf "%${empty}s" | tr ' ' '░' printf "] %3d%%" "$percentage" } # Function to check if video has audio stream has_audio() { local file="$1" local audio_streams=$(ffprobe -v error -select_streams a -show_entries stream=index -of csv=p=0 "$file" 2>/dev/null) [[ -n "$audio_streams" ]] } # ========================================= # QUAD HORIZONTAL COMPILATION # ========================================= echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "Creating Quad Horizontal 4K Compilation" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" echo "" # Find all horizontal MP4 files and shuffle echo " → Scanning for horizontal clips..." mapfile -t h_files < <(find "$GIFS_DIR" -path "*/horizontal/*.mp4" -type f 2>/dev/null | filter_excluded | shuf) h_total=${#h_files[@]} echo " → Found $h_total horizontal clips" # We need clips in multiples of 4 clips_needed=$NUM_CLIPS if [[ $h_total -lt $clips_needed ]]; then # Round down to nearest multiple of 4 clips_needed=$((h_total / 4 * 4)) NUM_SETS=$((clips_needed / 4)) echo " → Using $clips_needed clips ($NUM_SETS sets) - not enough for requested amount" fi if [[ $NUM_SETS -gt 0 ]]; then # Create temp directory for intermediate files temp_dir=$(mktemp -d) echo "" echo " → Encoding sets of 4 videos..." for ((set=0; set&1) nvenc_exit=$? # Check if NVENC failed if [[ $nvenc_exit -ne 0 ]] || [[ "$nvenc_output" == *"No capable devices"* ]] || [[ "$nvenc_output" == *"CUDA_ERROR"* ]]; then ffmpeg -nostdin \ -i "$video1" -i "$video2" -i "$video3" -i "$video4" \ -filter_complex "$filter_complex" \ -map "[vout]" -map "[aout]" \ -c:v libx264 -preset fast -crf 23 \ -c:a aac -b:a 192k \ -t "$min_dur" \ -f mpegts \ -loglevel error \ -y "$intermediate_file" 2>&1 fi # Small delay to let GPU resources release sleep 0.1 done echo "" # Concatenate all segments echo " → Merging all segments..." concat_list_file="$temp_dir/concat_list.txt" for ts_file in "$temp_dir"/*.ts; do echo "file '$(realpath "$ts_file")'" >> "$concat_list_file" done # Temporary output for metadata extraction temp_output="$temp_dir/output.mp4" ffmpeg -f concat -safe 0 -i "$concat_list_file" \ -c copy \ -movflags +faststart \ -loglevel error \ -y "$temp_output" 2>&1 ffmpeg_exit=$? if [[ $ffmpeg_exit -eq 0 ]] && [[ -f "$temp_output" ]]; then # Get final video metadata total_duration=$(get_duration_seconds "$temp_output") duration_formatted=$(format_duration "$total_duration") # Create final filename with metadata (always 4K, always H for this format) final_filename="Quad Horizontal Comp [${current_date}] [${duration_formatted}] [4K] [E] [H].mp4" final_path="$OUTPUT_DIR/$final_filename" mv "$temp_output" "$final_path" file_size_human=$(du -h "$final_path" | cut -f1) echo " ✓ Success! Created: $final_filename ($file_size_human)" else echo " ✗ Failed to create compilation (exit code: $ffmpeg_exit)" fi # Cleanup rm -rf "$temp_dir" else echo " ⚠ Not enough horizontal clips found (need at least 4)" fi # Calculate elapsed time end_time=$(date +%s) elapsed=$((end_time - start_time)) hours=$((elapsed / 3600)) minutes=$(((elapsed % 3600) / 60)) seconds=$((elapsed % 60)) echo "" echo "" echo "=========================================" echo " Quad Horizontal Compilation Complete!" echo "=========================================" echo " Time elapsed: ${hours}h ${minutes}m ${seconds}s" echo "=========================================" echo ""