Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Untitled conversation

  1. User
    # Ensure console output uses UTF-8 encoding
    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
    
    # Check if ffmpeg and ffprobe are installed and available in the PATH
    if (!(Get-Command ffmpeg -ErrorAction SilentlyContinue) -or !(Get-Command ffprobe -ErrorAction SilentlyContinue)) {
        Write-Host "Error: ffmpeg or ffprobe not found. Please install them and add to PATH." -ForegroundColor Red
        exit
    }
    
    # Default CRF (Constant Rate Factor) value
    $crf = 20.0
    # Flag to determine if the original files should be saved
    $saveOriginals = $false
    # Files to process, initially empty
    $files = @()
    
    # Parse command line arguments
    foreach ($arg in $args) {
        if ($arg -match '^-S$') {
            $saveOriginals = $true
        } elseif ($arg -match '^-crf=(\d+(\.\d+)?)$') {
            $crf = [double]$matches[1]
        } else {
            $files += $arg
        }
    }
    
    $sao = "sao=1"
    if ($crf -le 16) {
        $sao = "no-sao=1"
    } elseif ($crf -le 20) {
        $sao = "limit-sao=1"
    }
    
    # Encoder settings for high-quality HEVC conversion
    $encoder = @("-x265-params", "aq-mode=3:crf=$($crf):ref=4:bframes=8:deblock=-1,-1:$sao")
    $encoder
    
    # Initialize variables for tracking space savings and processed file count
    $totalSpaceSavedMB = 0
    $processedFilesCount = 0
    
    # List of file extensions to exclude from processing
    $excludedExtensions = @(
        '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp',          # Image files
        '.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a', '.mka',    # Audio files
        '.txt', '.doc', '.docx', '.pdf', '.rtf', '.odt',                    # Text files
        '.srt', '.sub', '.ass', '.vtt'                                      # Subtitle files
    )
    
    # Determine files to process
    $filesToProcess = if ($files.Count -eq 0) {
        # If no files specified, process all video files in the current directory
        Get-ChildItem -File | Where-Object { $excludedExtensions -notcontains $_.Extension.ToLower() }
    } else {
        # Validate specified files and exclude non-existent ones
        $files | ForEach-Object {
            try {
                Get-Item -Path $_
            } catch {
                Write-Host "Error: File '$_' does not exist or cannot be accessed." -ForegroundColor Red
                $null
            }
        } | Where-Object { $_ -and ($excludedExtensions -notcontains $_.Extension.ToLower()) }
    }
    
    foreach ($file in $filesToProcess) {
        # Use ffprobe to check if the file contains a video stream
        $videoStreamCheck = ffprobe -v quiet -select_streams v -show_entries stream=codec_type -of csv=p=0 $file.FullName
        if (-not $videoStreamCheck -or $videoStreamCheck -notmatch "video") {
            Write-Host "Skipping non-video file: $($file.Name)" -ForegroundColor Yellow
            continue
        }
    
        # Check the number of video streams in the file
        $videoStreamIndexes = ffprobe -v quiet -select_streams v -show_entries stream=index -of csv=p=0 $file.FullName
        if (-not $videoStreamIndexes) {
            Write-Host "Skipping file: $($file.Name) due to no video streams found." -ForegroundColor Yellow
            continue
        }
    
        $videoStreamIndexesArray = $videoStreamIndexes.TrimEnd(',').Split(",")
        if ($videoStreamIndexesArray.Count -gt 1) {
            Write-Host "Skipping file: $($file.Name) because it has more than one video stream." -ForegroundColor Yellow
            continue
        }
    
        # Retrieve the codec information for the video stream using ffprobe
        $codecInfo = ffprobe -v quiet -select_streams v:0 -show_entries stream=codec_name -of default=noprint_wrappers=1:nokey=1 $file.FullName
    
        # Check if the video codec is not HEVC, VP9, AV1
        if ($codecInfo -match "hevc|vp9|av01") {
            Write-Host "Skipping file (already HEVC, VP9, or AV1): $($file.Name)" -ForegroundColor Yellow
            continue
        }
    
        Write-Host "Converting file: $($file.Name)" -ForegroundColor Green
    
        # Define the temporary output file path
        $outputFile = "$($file.DirectoryName)\$($file.BaseName)_HEVC$($file.Extension)"
    
        # Perform the video conversion using ffmpeg
        ffmpeg -y -i $file.FullName -c:v libx265 -preset slow $encoder -pix_fmt yuv420p10le -c:a libopus -b:a 192k -vbr on -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    
        # Check if the conversion was successful by comparing durations
        $originalDuration = ffprobe -v quiet -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $file.FullName
        $outputDuration = ffprobe -v quiet -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $outputFile
        if ([math]::Abs($originalDuration - $outputDuration) -gt 1) {
            Write-Host "Error: Output file duration mismatch, keeping the original file: $($file.Name)" -ForegroundColor Red
            Remove-Item $outputFile -Force
            continue
        }
    
        Write-Host "Conversion completed: $outputFile" -ForegroundColor Green
    
        # Calculate the space savings
        $originalSizeMB = [math]::Round(($file.Length / 1MB), 2)
        $outputFileInfo = Get-Item -LiteralPath $outputFile
        $outputSizeMB = [math]::Round(($outputFileInfo.Length / 1MB), 2)
        $spaceSavedMB = [math]::Round(($originalSizeMB - $outputSizeMB), 2)
    
        Write-Host "Original Size: $originalSizeMB MB, Converted Size: $outputSizeMB MB, Space Saved: $spaceSavedMB MB" -ForegroundColor Cyan
        $totalSpaceSavedMB += $spaceSavedMB
        $processedFilesCount++
    
        # Report total space saved and processed files count
        $roundedTotalSpaceSavedMB = [math]::Round($totalSpaceSavedMB, 2)
        Write-Host "Total space saved: $roundedTotalSpaceSavedMB MB (Processed files: $processedFilesCount)" -ForegroundColor Cyan
    
        # Remove the original file unless the -Save switch is specified
        if (-not $saveOriginals) {
            Remove-Item -LiteralPath $file.FullName -Force
            Rename-Item -LiteralPath $outputFile -NewName $file.Name
        }
    }
    
    Write-Host "All files processed." -ForegroundColor Green
    

    Проанализируй данный скрипт. Можно ли его улучшить. Улучшить качество и скорость libx265, общее качество и скорость.

  2. Assistant

    Analysis and Improvement Suggestions for the Provided PowerShell Script

    The script is designed to convert video files to HEVC (H.265) using ffmpeg and ffprobe, while checking for existing HEVC, VP9, or AV1 encodings to avoid unnecessary conversions. It also replaces original files unless the -S option is specified and provides information on space savings.

    Below, we'll analyze the script and suggest improvements to both the script itself and the ffmpeg encoding parameters to enhance quality and speed.


    1. Script Improvements

    a. Command-Line Argument Parsing

    Issue: The script accepts -S and -crf= options, but lacks help documentation and robust error handling for invalid arguments.

    Improvement:

    • Add Help Documentation: Implement a -Help or -h switch to display usage instructions.
    • Validate Arguments: Check for invalid or misspelled arguments and provide user-friendly error messages.

    Example Modification:

    # Add help function
    function Show-Help {
        Write-Host "Usage: script.ps1 [-S] [-crf=<value>] [files]"
        Write-Host "-S             Save original files after conversion."
        Write-Host "-crf=<value>    Set the CRF (Constant Rate Factor) value (e.g., -crf=20)."
        Write-Host "files           Optional list of files to process. If omitted, all video files in the current directory will be processed."
        exit
    }
    
    # Check for help argument
    if ($args -contains "-h" -or $args -contains "-help" -or $args -contains "--help") {
        Show-Help
    }
    
    # Rest of the argument parsing remains similar
    

    b. File Extension Filtering

    Issue: The script excludes files based on a hardcoded list of extensions, which might miss uncommon video file extensions.

    Improvement:

    • Use MIME Types: Instead of excluding by extensions, identify video files using MIME types or by checking for video streams with ffprobe.
    • Include Common Video Extensions: Ensure common video extensions like .mkv, .mp4, .avi, .mov, etc., are considered.

    Example Modification:

    # Get all files and filter only those with video streams
    $filesToProcess = Get-ChildItem -File | Where-Object {
        # Use ffprobe to check if the file has a video stream
        $hasVideo = ffprobe -v quiet -select_streams v -show_entries stream=index -of csv=p=0 $_.FullName
        return $hasVideo
    }
    

    c. Duration Comparison

    Issue: Comparing durations in seconds may not be precise due to rounding or timebase differences.

    Improvement:

    • Compare Frame Counts: Use frame counts to compare the original and converted videos.
    • Allow a Small Tolerance: Set a minimal acceptable difference (e.g., less than 0.1 seconds).

    Example Modification:

    # Get frame counts
    $originalFrames = ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of csv=p=0 $file.FullName
    $outputFrames = ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of csv=p=0 $outputFile
    
    # Compare frame counts
    if ([int]$originalFrames -ne [int]$outputFrames) {
        Write-Host "Error: Frame count mismatch, keeping the original file: $($file.Name)" -ForegroundColor Red
        Remove-Item $outputFile -Force
        continue
    }
    

    d. Modularization and Code Reuse

    Issue: The script is linear and can be segmented for better readability and maintenance.

    Improvement:

    • Create Functions: Encapsulate repetitive or logical sections into functions (e.g., Get-FilesToProcess, Convert-File, Calculate-SpaceSaved).
    • Error Handling in Functions: Implement try-catch blocks within functions for precise error handling.

    e. User Configurability

    Issue: Some encoding parameters are hardcoded, reducing flexibility.

    Improvement:

    • Expose Parameters: Allow users to specify presets, audio codecs, and other encoding parameters via command-line options.
    • Provide Defaults: While allowing customization, provide sensible defaults.

    Example Modification:

    # Add parameters
    $audioCodec = "libopus"
    $audioBitrate = "192k"
    $videoPreset = "slow"
    
    # Parse new arguments
    if ($arg -match '^-preset=(\w+)$') {
        $videoPreset = $matches[1]
    } elseif ($arg -match '^-acodec=(\w+)$') {
        $audioCodec = $matches[1]
    }
    
    # Use variables in the ffmpeg command
    ffmpeg -y -i $file.FullName -c:v libx265 -preset $videoPreset $encoder -pix_fmt yuv420p10le -c:a $audioCodec -b:a $audioBitrate -vbr on -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    

    2. Enhancing Encoding Quality and Speed

    Balancing quality and encoding speed often involves trade-offs. Below are suggestions to optimize both:

    a. Adjusting Preset Levels

    Issue: The -preset slow option provides better compression but increases encoding time.

    Improvement:

    • Use -preset medium: Offers a better balance between speed and quality.
    • Allow User Selection: Let users choose the preset level via command-line options.

    Example:

    # Expose preset as a parameter (as shown above)
    $videoPreset = "medium"  # Default to medium
    

    b. Re-evaluating 10-bit Encoding

    Issue: Encoding to 10-bit (-pix_fmt yuv420p10le) increases encoding time and may not be necessary for 8-bit source videos.

    Improvement:

    • Check Source Bit Depth: Only encode to 10-bit if the source is 10-bit.
    • Default to 8-bit: Use -pix_fmt yuv420p for 8-bit sources for faster encoding and broader compatibility.

    Example Modification:

    # Check source bit depth
    $bitDepth = ffprobe -v error -select_streams v:0 -show_entries stream=bits_per_raw_sample -of default=noprint_wrappers=1:nokey=1 $file.FullName
    
    if ($bitDepth -ge 10) {
        $pixFmt = "yuv420p10le"
    } else {
        $pixFmt = "yuv420p"
    }
    
    # Use $pixFmt in the ffmpeg command
    ffmpeg -y -i $file.FullName -c:v libx265 -preset $videoPreset $encoder -pix_fmt $pixFmt -c:a $audioCodec -b:a $audioBitrate -vbr on -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    

    c. Adjusting x265 Parameters

    Issue: Some x265 parameters may unnecessarily slow down encoding without significant quality gain.

    Improvements:

    • Reduce ref Frames: Set ref=3 (x265 default) for faster encoding.
    • Reduce bframes: Use the default bframes=4.
    • Adjust aq-mode: Use aq-mode=1 for faster encoding; aq-mode=3 is slower and may not provide noticeable quality improvements for all content.
    • Modify Deblocking Filter Only If Necessary: Default deblock=0:0 may suffice unless blocking artifacts are observed.
    • Simplify SAO Settings: Consider whether adjusting SAO based on CRF is beneficial.

    Example Modification:

    # Adjust x265 parameters
    $encoderParams = "aq-mode=1:crf=$crf"
    
    # Optional: Adjust 'ref' and 'bframes' if not default
    #$encoderParams += ":ref=3:bframes=4"
    
    # Include SAO if necessary
    #if ($includeSAO) { $encoderParams += ":sao=1" }
    
    $encoder = @("-x265-params", $encoderParams)
    

    d. Audio Codec and Compatibility

    Issue: Using libopus may not be compatible with all devices.

    Improvements:

    • Default to AAC: Use aac codec for wider compatibility.
    • Expose Audio Codec as an Option: Allow users to choose between aac, libopus, or other codecs.

    Example Modification:

    # Set default audio codec to AAC for compatibility
    $audioCodec = "aac"
    $audioBitrate = "192k"
    
    # Use variables in the ffmpeg command
    ffmpeg -y -i $file.FullName -c:v libx265 -preset $videoPreset $encoder -pix_fmt $pixFmt -c:a $audioCodec -b:a $audioBitrate -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    

    e. Utilizing Hardware Acceleration

    Issue: Software encoding with libx265 is CPU-intensive and slow.

    Improvement:

    • Use Hardware Encoders: If compatible hardware is available, use hevc_nvenc (NVIDIA), hevc_amf (AMD), or hevc_qsv (Intel) for faster encoding.
    • Note on Quality: Hardware encoders are faster but may produce lower quality compared to software encoding at the same bitrate.

    Example Modification:

    # Check for hardware encoder flag
    $useHardwareEncoder = $false  # Default to false
    if ($args -contains "-hw") {
        $useHardwareEncoder = $true
    }
    
    # Update ffmpeg command based on hardware encoder availability
    if ($useHardwareEncoder) {
        # Assuming NVIDIA hardware is available
        ffmpeg -y -i $file.FullName -c:v hevc_nvenc -preset slow -b:v 5000k -c:a $audioCodec -b:a $audioBitrate -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    } else {
        # Original software encoding command
        ffmpeg -y -i $file.FullName -c:v libx265 -preset $videoPreset $encoder -pix_fmt $pixFmt -c:a $audioCodec -b:a $audioBitrate -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    }
    

    Note: When using hardware encoders, -crf is typically not supported. Instead, you specify a target bitrate with -b:v.

    f. Multithreading and Resource Management

    Issue: Encoding may not fully utilize available CPU cores.

    Improvement:

    • Ensure Multithreading: x265 uses multithreading by default. Verify that ffmpeg is not limited by any thread parameters.
    • Limit CPU Usage: If necessary, allow users to limit CPU usage to keep the system responsive.

    Example:

    # Explicitly set threads if required
    $threads = [Environment]::ProcessorCount  # Use all available cores
    
    # Update ffmpeg command
    ffmpeg -threads $threads -y -i $file.FullName -c:v libx265 -preset $videoPreset $encoder -pix_fmt $pixFmt -c:a $audioCodec -b:a $audioBitrate -c:s copy -c:d copy -map 0 -hide_banner $outputFile
    

    3. Summary of Recommendations

    • Script Enhancements:

      • Add help documentation and improve argument parsing.
      • Use MIME types or check for video streams to identify files to process.
      • Modularize code into functions for better maintainability.
      • Improve duration comparison by using frame counts.
      • Expose more encoding options to the user for flexibility.
    • Encoding Optimizations:

      • Use -preset medium for a balance between speed and quality.
      • Default to 8-bit encoding unless the source is 10-bit.
      • Adjust x265 parameters (aq-mode, ref, bframes) to default values for faster encoding.
      • Switch to AAC audio codec for broader compatibility.
      • Consider hardware acceleration if compatible hardware is available, acknowledging potential quality trade-offs.

    By implementing these recommendations, the script will be more robust, user-friendly, and capable of faster encoding without significantly compromising quality.