Generated banner for Video To Gif
Generated logo for Video To Gif

Video To Gif

MicrosoftOfficialPublished by Microsoft

  • Skill
  • Tool integration
  • Automation and integrations
  • MIT
  • Low risk
  • Has scripts

From the author

Video-to-GIF conversion with FFmpeg two-pass optimization
— the description by Microsoft

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides bash and PowerShell scripts to convert video files into GIF animations. It utilizes FFmpeg to perform a two-pass conversion process, where the first pass generates an optimized color palette and the second pass applies it to the output. The tool includes automatic HDR detection and tonemapping, as well as configurable parameters for frame rate, resolution, dithering, and time-range extraction.

What it does

  • Converts video files to GIF format using two-pass palette optimization.
  • Automatically detects HDR content and applies tonemapping for SDR output.
  • Supports custom frame rates, output widths, and loop counts.
  • Allows extraction of specific video segments using start time and duration parameters.
  • Provides multiple dithering algorithms to manage color approximation.
  • Includes cross-platform support via bash and PowerShell scripts.

When to use it

  • When you need to convert video clips into GIF animations for documentation or presentations.
  • When you require specific control over GIF resolution, frame rate, or color dithering.
  • When processing HDR video content that requires tonemapping for standard GIF output.
  • When you need to extract and convert only a specific portion of a longer video file.

Advantages

  • Two-pass conversion process for palette optimization.
  • Automatic HDR detection and tonemapping support.
  • Flexible configuration for file size and visual output settings.
  • Supports both bash and PowerShell environments.
  • Includes built-in search logic for locating input files.

Usage examples

“Convert my video file demo.mp4 into a GIF.”
The script processes the video using default settings (10 FPS, 1280px width) and saves the result as demo.gif.
“Create a GIF from the first 10 seconds of my video starting at the 5-second mark.”
The script extracts the specified segment and generates a GIF based on the provided start and duration parameters.
“Convert this HDR video to a GIF using the reinhard tonemapping algorithm.”
The script detects the HDR content and applies the reinhard tonemapping algorithm to ensure proper color conversion.
“Generate a thumbnail-sized GIF from my video.”
The script uses the width parameter to scale the output to 320 pixels while maintaining the aspect ratio.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/microsoft/video-to-gif/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip video-to-gif.zip -d .agents/skills

Documentation by Microsoft

Video-to-GIF Conversion Skill

This skill converts video files to optimized GIF animations using FFmpeg two-pass palette optimization.

Overview

The two-pass conversion process generates superior quality GIFs compared to single-pass approaches. Pass one analyzes the video and creates an optimized color palette. Pass two applies that palette to produce the final GIF with better color fidelity and smaller file sizes.

Response Format

After successful conversion, include a file link to the GIF in the response with the absolute file path:

/absolute/path/to/filename.gif

This allows the user to open the file and review it.

Prerequisites

FFmpeg is required and must be available in your system PATH.

macOS
brew install ffmpeg
Linux (Debian/Ubuntu)
sudo apt update && sudo apt install ffmpeg
Windows

Using Chocolatey:

choco install ffmpeg

Using winget:

winget install FFmpeg.FFmpeg

Verify installation:

ffmpeg -version

Quick Start

Convert a video using default settings (10 FPS, 1280px width, sierra2_4a dithering):

scripts/convert.sh input.mp4
scripts/convert.ps1 -InputPath input.mp4

Output saves to input.gif by default.

File Search Behavior

When a filename is provided without a full path, the script searches in this order:

  1. Current working directory

  2. Workspace root (if inside a project)

  3. ~/Movies/ (macOS) or ~/Videos/ (Linux)

  4. ~/Downloads/

  5. ~/Desktop/

This allows natural commands like convert.sh demo.mov without specifying full paths.

HDR Handling

The script automatically detects HDR video content via ffprobe by checking for BT.2020 color primaries or SMPTE 2084 transfer characteristics. When HDR is detected, tonemapping is applied automatically to produce SDR-compatible GIF output with proper color preservation.

Use --tonemap to select the tonemapping algorithm:

AlgorithmCharacteristics
hableFilmic curve, good highlight rolloff (default)
reinhardPreserves more color saturation
mobiusSimilar to reinhard with better highlights
bt2390ITU standard, more conservative

Parameters Reference

ParameterFlag (bash)Flag (PowerShell)DefaultDescription
Input file--input-InputPath(required)Source video file path
Output file--output-OutputPathinput.gifDestination GIF file path
Frame rate--fps-Fps10Frames per second
Width--width-Width1280Output width in pixels
Dithering--dither-Dithersierra2_4aDithering algorithm
Tonemapping--tonemap-TonemaphableHDR tonemapping algorithm
Skip palette--skip-palette-SkipPalettefalseUse single-pass mode
Start time--start-Start0Start time in seconds
Duration--duration-Duration(full video)Duration to convert in seconds
Loop count--loop-Loop0GIF loop count (0 = infinite)
TimeoutVIDEO_TO_GIF_TIMEOUT (env)-TimeoutSeconds600Seconds allowed for each ffprobe/ffmpeg run

The output path must differ from the input path. Both scripts refuse to run when the output resolves to the input, which includes the default output for a .gif input, so pass an explicit output path in that case. An existing file at a different output path is overwritten.

Each ffprobe and ffmpeg invocation is stopped when it exceeds the timeout. When the HDR probe fails or times out, the input is treated as SDR and conversion continues.

Frame Rate (FPS)

FPS controls animation smoothness and file size. Lower values reduce file size but create choppier motion.

FPSUse Case
5Simple animations, icons
10General use (default)
15Smooth motion, UI demos
24Near-video quality
Width

Width sets the output horizontal resolution in pixels. Height scales proportionally to maintain aspect ratio.

WidthUse Case
320Thumbnails, previews
640Documentation
800Presentations
1280High detail (default)
Dithering Algorithms

Dithering determines how the 256-color GIF palette approximates the original colors.

AlgorithmQualitySpeedBest For
sierra2_4aHighMediumGeneral use (default)
floyd_steinbergHighSlowPhotographic content
bayerMediumFastGraphics with solid colors
noneLowFastestStylized/posterized look
Time Range Selection

Use --start and --duration to convert a specific portion of the video:

# Start at 5 seconds, convert 10 seconds
scripts/convert.sh --input video.mp4 --start 5 --duration 10
Loop Control

Use --loop to control GIF repeat behavior:

ValueBehavior
0Loop forever
1Play once
NPlay N times

Two-Pass vs Single-Pass

Two-Pass (Default)

Two-pass conversion creates a custom palette from the source video, then applies it:

# Pass 1: Generate palette
ffmpeg -i input.mp4 \
  -vf "fps=10,scale=1280:-1:flags=lanczos,palettegen=stats_mode=diff" \
  -y /tmp/palette.png

# Pass 2: Create GIF
ffmpeg -i input.mp4 -i /tmp/palette.png \
  -filter_complex "fps=10,scale=1280:-1:flags=lanczos[x];[x][1:v]paletteuse=dither=sierra2_4a:diff_mode=rectangle" \
  -loop 0 -y output.gif

Two-pass produces better color accuracy and typically smaller files.

Single-Pass

Single-pass skips palette generation and uses FFmpeg's default 256-color palette:

ffmpeg -i input.mp4 \
  -vf "fps=10,scale=1280:-1:flags=lanczos" \
  -loop 0 -y output.gif

Single-pass processes faster but produces lower quality output with potential color banding.

Use single-pass via --skip-palette (bash) or -SkipPalette (PowerShell).

Script Reference

convert.sh (Bash)
# Basic usage
scripts/convert.sh video.mp4

# Custom output path
scripts/convert.sh --input video.mp4 --output demo.gif

# Adjust quality parameters
scripts/convert.sh --input video.mp4 --fps 15 --width 640 --dither floyd_steinberg

# HDR video with custom tonemapping
scripts/convert.sh --input hdr-video.mov --tonemap reinhard

# Extract a 10-second clip starting at 5 seconds
scripts/convert.sh --input video.mp4 --start 5 --duration 10

# Create a GIF that plays only once
scripts/convert.sh --input video.mp4 --loop 1

# Fast single-pass mode
scripts/convert.sh --input video.mp4 --skip-palette
convert.ps1 (PowerShell)
# Basic usage
scripts/convert.ps1 -InputPath video.mp4

# Custom output path
scripts/convert.ps1 -InputPath video.mp4 -OutputPath demo.gif

# Adjust quality parameters
scripts/convert.ps1 -InputPath video.mp4 -Fps 15 -Width 640 -Dither floyd_steinberg

# HDR video with custom tonemapping
scripts/convert.ps1 -InputPath hdr-video.mov -Tonemap reinhard

# Extract a 10-second clip starting at 5 seconds
scripts/convert.ps1 -InputPath video.mp4 -Start 5 -Duration 10

# Create a GIF that plays only once
scripts/convert.ps1 -InputPath video.mp4 -Loop 1

# Fast single-pass mode
scripts/convert.ps1 -InputPath video.mp4 -SkipPalette

Examples

HDR Video Conversion

HDR content is detected automatically. No special flags are needed:

scripts/convert.sh hdr-footage.mov

The script applies hable tonemapping by default. Use --tonemap to try different algorithms:

# Use reinhard for more saturated colors
scripts/convert.sh --input hdr-footage.mov --tonemap reinhard
Time Range Extraction

Extract a specific segment from a longer video:

# Convert seconds 30-45 of a screencast
scripts/convert.sh --input screencast.mp4 --start 30 --duration 15 --fps 15
Documentation Thumbnails

Create compact thumbnails for documentation:

scripts/convert.sh --input demo.mp4 --width 320 --fps 8

Troubleshooting

FFmpeg not found

Verify FFmpeg is in your PATH:

which ffmpeg  # macOS/Linux
where.exe ffmpeg  # Windows

If FFmpeg is installed but not found, add its directory to your PATH environment variable.

File not found

Ensure the file exists at the specified path. If providing only a filename, the script searches the workspace first, then common directories (~/Movies/, ~/Downloads/, ~/Desktop/). Use an absolute path if the file is in a different location.

Output file is too large

Reduce file size with these adjustments:

  • Lower FPS (try 8 or 5)

  • Reduce width (try 640 or 320)

  • Use bayer dithering for faster processing

  • Use --duration to convert only a portion of the video

Colors appear washed out

Switch to floyd_steinberg dithering for photographic content. Avoid none dithering unless a stylized look is intended.

HDR content looks wrong

Ensure FFmpeg 4.0+ is installed with zscale filter support. The script requires libzimg for HDR tonemapping. Install via:

# macOS
brew install zimg
brew reinstall ffmpeg

# Ubuntu
sudo apt install libzimg-dev

If colors still appear off, try a different tonemapping algorithm with --tonemap. The reinhard algorithm preserves more saturation, while bt2390 provides more conservative results.

Conversion fails with filter error

Ensure FFmpeg version 4.0 or later is installed. The palettegen and paletteuse filters require this version.

ffmpeg -version
Temporary palette file remains

The scripts clean up /tmp/palette.png (or $env:TEMP\palette.png on Windows) automatically. If conversion fails mid-process, remove this file manually.

Files

scripts/convert.ps1

#!/usr/bin/env pwsh
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT

<#
.SYNOPSIS
    Convert video files to optimized GIF animations using FFmpeg.

.DESCRIPTION
    This script converts video files to GIF animations using FFmpeg two-pass
    palette optimization. The two-pass approach generates a custom color palette
    from the source video, producing better color accuracy and smaller file sizes
    compared to single-pass conversion.

    Features HDR auto-detection with Hable tonemapping and workspace-first file search.

.PARAMETER InputPath
    Path to the input video file. Searches workspace, ~/Movies, ~/Downloads, ~/Desktop if not found.

.PARAMETER OutputPath
    Path for the output GIF file. Defaults to the input filename with .gif extension.

.PARAMETER Fps
    Frame rate for the output GIF. Valid range: 1-30. Default: 10.

.PARAMETER Width
    Output width in pixels. Height scales proportionally. Valid range: 100-3840. Default: 1280.

.PARAMETER Dither
    Dithering algorithm for color approximation.
    Options: sierra2_4a (default), floyd_steinberg, bayer, none.

.PARAMETER Loop
    GIF loop count. 0 means infinite loop. Default: 0.

.PARAMETER Start
    Start time in seconds for time range extraction.

.PARAMETER Duration
    Duration in seconds for time range extraction.

.PARAMETER SkipPalette
    Use single-pass mode instead of two-pass palette optimization.
    Faster processing but lower quality output.

.PARAMETER TimeoutSeconds
    Maximum wall-clock seconds for each ffprobe or ffmpeg invocation. Valid range: 1-86400. Default: 600.
    The output path must differ from the input path; a .gif input therefore needs an explicit -OutputPath.

.EXAMPLE
    ./convert.ps1 -InputPath video.mp4
    Converts video.mp4 to video.gif using default settings.

.EXAMPLE
    ./convert.ps1 -InputPath video.mp4 -OutputPath demo.gif -Fps 15 -Width 640
    Converts with custom frame rate and width.

.EXAMPLE
    ./convert.ps1 -InputPath video.mp4 -Start 5 -Duration 10
    Converts a 10-second clip starting at 5 seconds.

.EXAMPLE
    ./convert.ps1 -InputPath video.mp4 -Dither floyd_steinberg
    Converts using Floyd-Steinberg dithering for photographic content.

.EXAMPLE
    ./convert.ps1 -InputPath video.mp4 -SkipPalette
    Converts using faster single-pass mode.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true, Position = 0)]
    [string]$InputPath,

    [Parameter(Mandatory = $false)]
    [string]$OutputPath,

    [Parameter(Mandatory = $false)]
    [ValidateRange(1, 30)]
    [int]$Fps = 10,

    [Parameter(Mandatory = $false)]
    [ValidateRange(100, 3840)]
    [int]$Width = 1280,

    [Parameter(Mandatory = $false)]
    [ValidateSet('sierra2_4a', 'floyd_steinberg', 'bayer', 'none')]
    [string]$Dither = 'sierra2_4a',

    [Parameter(Mandatory = $false)]
    [ValidateSet('hable', 'reinhard', 'mobius', 'bt2390')]
    [string]$Tonemap = 'hable',

    [Parameter(Mandatory = $false)]
    [ValidateRange(0, [int]::MaxValue)]
    [int]$Loop = 0,

    [Parameter(Mandatory = $false)]
    [ValidateRange(0, [double]::MaxValue)]
    [double]$Start,

    [Parameter(Mandatory = $false)]
    [ValidateRange(0.1, [double]::MaxValue)]
    [double]$Duration,

    [Parameter(Mandatory = $false)]
    [ValidateRange(1, 86400)]
    [int]$TimeoutSeconds = 600,

    [Parameter(Mandatory = $false)]
    [switch]$SkipPalette
)

#region Functions

function Test-FFmpegAvailable {
    $ffmpegPath = Get-Command -Name 'ffmpeg' -ErrorAction SilentlyContinue
    if (-not $ffmpegPath) {
        Write-Error "FFmpeg is required but not installed."
        Write-Host ""
        Write-Host "Install FFmpeg:" -ForegroundColor Yellow
        Write-Host "  Chocolatey: choco install ffmpeg"
        Write-Host "  winget:     winget install FFmpeg.FFmpeg"
        Write-Host "  Manual:     https://ffmpeg.org/download.html"
        return $false
    }
    return $true
}

function Find-VideoFile {
    <#
    .SYNOPSIS
        Search for a video file in workspace and common directories.
    #>
    param(
        [Parameter(Mandatory = $true)]
        [string]$Filename
    )

    # If absolute path or file exists at given path, return as-is
    if (Test-Path -Path $Filename -PathType Leaf) {
        return (Resolve-Path -Path $Filename).Path
    }

    # Build search locations in priority order
    $searchDirs = @(
        $PWD.Path
    )

    # Add git repository root if available
    try {
        $gitRoot = git rev-parse --show-toplevel 2>$null
        if ($LASTEXITCODE -eq 0 -and $gitRoot) {
            $searchDirs += $gitRoot
        }
    }
    catch {
        Write-Verbose "Git not available or not in a repository: $_"
    }

    # Add common video directories
    if ($IsMacOS) {
        $searchDirs += @(
            (Join-Path -Path $HOME -ChildPath 'Movies')
            (Join-Path -Path $HOME -ChildPath 'Downloads')
            (Join-Path -Path $HOME -ChildPath 'Desktop')
        )
    }
    elseif ($IsWindows) {
        $searchDirs += @(
            (Join-Path -Path $HOME -ChildPath 'Videos')
            (Join-Path -Path $HOME -ChildPath 'Downloads')
            (Join-Path -Path $HOME -ChildPath 'Desktop')
        )
    }
    else {
        # Linux
        $searchDirs += @(
            (Join-Path -Path $HOME -ChildPath 'Videos')
            (Join-Path -Path $HOME -ChildPath 'Downloads')
            (Join-Path -Path $HOME -ChildPath 'Desktop')
        )
    }

    foreach ($dir in $searchDirs) {
        $candidatePath = Join-Path -Path $dir -ChildPath $Filename
        if (Test-Path -Path $candidatePath -PathType Leaf) {
            return $candidatePath
        }
    }

    # File not found
    return $null
}

function Resolve-PhysicalPath {
    <#
    .SYNOPSIS
        Resolve existing path segments through symbolic links and junctions.
    .DESCRIPTION
        Returns an absolute filesystem path while preserving any nonexistent
        trailing segments, such as a new output filename.
    #>
    [CmdletBinding()]
    [OutputType([string])]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Path
    )

    $fullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
    $pathRoot = [System.IO.Path]::GetPathRoot($fullPath)
    $current = $pathRoot
    $segments = $fullPath.Substring($pathRoot.Length).Split(
        [System.IO.Path]::DirectorySeparatorChar,
        [System.StringSplitOptions]::RemoveEmptyEntries
    )

    for ($index = 0; $index -lt $segments.Length; $index++) {
        $candidate = Join-Path -Path $current -ChildPath $segments[$index]
        if (-not (Test-Path -LiteralPath $candidate -ErrorAction Stop)) {
            for ($tailIndex = $index; $tailIndex -lt $segments.Length; $tailIndex++) {
                $current = Join-Path -Path $current -ChildPath $segments[$tailIndex]
            }
            break
        }

        $item = Get-Item -LiteralPath $candidate -Force -ErrorAction Stop
        if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
            $target = $item.ResolveLinkTarget($true)
            if (-not $target) {
                throw "Unable to resolve symbolic link or junction: $candidate"
            }
            $current = $target.FullName
        }
        else {
            $current = $item.FullName
        }
    }

    return [System.IO.Path]::GetFullPath($current)
}

function Test-HDRContent {
    <#
    .SYNOPSIS
        Detect if video contains HDR content using ffprobe.
    .DESCRIPTION
        Runs ffprobe under the same wall-clock bound as the conversion. A probe that
        times out, fails, or cannot start is treated as SDR content.
    #>
    param(
        [Parameter(Mandatory = $true)]
        [string]$FilePath,

        [Parameter(Mandatory = $false)]
        [int]$TimeoutSeconds = 600
    )

    $ffprobePath = Get-Command -Name 'ffprobe' -ErrorAction SilentlyContinue
    if (-not $ffprobePath) {
        return $false
    }

    $probeArguments = @(
        '-v', 'error'
        '-select_streams', 'v:0'
        '-show_entries', 'stream=color_primaries,color_transfer'
        '-of', 'csv=p=0'
        $FilePath
    )

    try {
        $probe = Invoke-BoundedProcess -FilePath 'ffprobe' -Arguments $probeArguments -TimeoutSeconds $TimeoutSeconds -CaptureOutput

        # Check for HDR indicators: bt2020 primaries or smpte2084 transfer
        if ($probe.ExitCode -eq 0 -and $probe.StdOut -match 'bt2020|smpte2084') {
            return $true
        }
    }
    catch {
        Write-Warning "HDR detection failed; treating input as SDR: $($_.Exception.Message)"
    }

    return $false
}

function Format-FileSize {
    param([long]$Bytes)

    if ($Bytes -ge 1MB) {
        return "{0:N2} MB" -f ($Bytes / 1MB)
    }
    elseif ($Bytes -ge 1KB) {
        return "{0:N2} KB" -f ($Bytes / 1KB)
    }
    else {
        return "$Bytes bytes"
    }
}

function Invoke-BoundedProcess {
    <#
    .SYNOPSIS
        Runs an executable with the given argument list under a wall-clock timeout.
    .DESCRIPTION
        Uses the .NET process API so each argument (including the filtergraph) is
        passed verbatim and is never re-parsed by a shell, and so the process tree can
        be terminated if it exceeds TimeoutSeconds, preventing a hostile or
        pathological input from hanging the conversion indefinitely.
    #>
    param(
        [Parameter(Mandatory = $true)]
        [string]$FilePath,

        [Parameter(Mandatory = $false)]
        [object[]]$Arguments = @(),

        [Parameter(Mandatory = $false)]
        [int]$TimeoutSeconds = 600,

        [Parameter(Mandatory = $false)]
        [switch]$CaptureOutput
    )

    $psi = [System.Diagnostics.ProcessStartInfo]::new()
    $psi.FileName = $FilePath
    foreach ($arg in $Arguments) { [void]$psi.ArgumentList.Add([string]$arg) }
    $psi.UseShellExecute = $false
    if ($CaptureOutput) {
        $psi.RedirectStandardOutput = $true
        $psi.RedirectStandardError = $true
    }

    $process = [System.Diagnostics.Process]::Start($psi)
    try {
        $stdoutTask = $null
        if ($CaptureOutput) {
            $stdoutTask = $process.StandardOutput.ReadToEndAsync()
            $null = $process.StandardError.ReadToEndAsync()
        }

        if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
            try {
                $process.Kill($true)
                $process.WaitForExit()
            }
            catch {
                Write-Verbose "Failed to terminate timed-out process: $_"
            }
            throw "$FilePath timed out after $TimeoutSeconds seconds."
        }

        # The parameterless overload waits for redirected streams to drain.
        $process.WaitForExit()

        return [pscustomobject]@{
            ExitCode = $process.ExitCode
            StdOut   = if ($stdoutTask) { $stdoutTask.Result } else { $null }
        }
    }
    finally {
        $process.Dispose()
    }
}

function Invoke-FFmpegProcess {
    <#
    .SYNOPSIS
        Runs ffmpeg with the given argument list under a wall-clock timeout.
    #>
    param(
        [Parameter(Mandatory = $true)]
        [object[]]$Arguments,

        [Parameter(Mandatory = $false)]
        [int]$TimeoutSeconds = 600
    )

    $result = Invoke-BoundedProcess -FilePath 'ffmpeg' -Arguments $Arguments -TimeoutSeconds $TimeoutSeconds
    return $result.ExitCode -eq 0
}

function Invoke-SinglePassConversion {
    param(
        [string]$SourcePath,
        [string]$DestinationPath,
        [int]$LoopCount,
        [string]$BaseFilter,
        [double[]]$TimeArgs,
        [int]$TimeoutSeconds = 600
    )

    Write-Verbose "Running single-pass conversion..."

    $arguments = @()

    # Add time range arguments before input
    if ($TimeArgs -and $TimeArgs.Count -gt 0) {
        if ($PSBoundParameters.ContainsKey('Start') -or $TimeArgs[0] -ge 0) {
            $arguments += @('-ss', $TimeArgs[0])
        }
        if ($TimeArgs.Count -gt 1 -and $TimeArgs[1] -gt 0) {
            $arguments += @('-t', $TimeArgs[1])
        }
    }

    $arguments += @(
        '-i', $SourcePath
        '-vf', $BaseFilter
        '-loop', $LoopCount
        '-y', $DestinationPath
    )

    return (Invoke-FFmpegProcess -Arguments $arguments -TimeoutSeconds $TimeoutSeconds)
}

function Invoke-TwoPassConversion {
    param(
        [string]$SourcePath,
        [string]$DestinationPath,
        [string]$DitherAlgorithm,
        [int]$LoopCount,
        [string]$BaseFilter,
        [double[]]$TimeArgs,
        [int]$TimeoutSeconds = 600
    )

    # Create the palette inside a private, unpredictable temp directory rather than
    # a predictable palette_$PID.png, which is exposed to a symlink or pre-creation
    # race on a shared temp location. The finally block removes it even on failure.
    $paletteDir = New-Item -ItemType Directory -Force -Path (
        Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ("video-to-gif-" + [System.IO.Path]::GetRandomFileName())
    )
    $paletteFile = Join-Path -Path $paletteDir.FullName -ChildPath 'palette.png'

    try {
        # Build time arguments array
        $timeArguments = @()
        if ($TimeArgs -and $TimeArgs.Count -gt 0) {
            if ($TimeArgs[0] -ge 0) {
                $timeArguments += @('-ss', $TimeArgs[0])
            }
            if ($TimeArgs.Count -gt 1 -and $TimeArgs[1] -gt 0) {
                $timeArguments += @('-t', $TimeArgs[1])
            }
        }

        # Pass 1: Generate palette
        Write-Host "Pass 1: Generating optimized palette..."
        $paletteFilter = "$BaseFilter,palettegen=stats_mode=diff"

        $pass1Args = $timeArguments + @(
            '-i', $SourcePath
            '-vf', $paletteFilter
            '-y', $paletteFile
        )

        if (-not (Invoke-FFmpegProcess -Arguments $pass1Args -TimeoutSeconds $TimeoutSeconds)) {
            Write-Error "Palette generation failed."
            return $false
        }

        # Pass 2: Create GIF
        Write-Host "Pass 2: Creating GIF with palette..."
        $filterComplex = "${BaseFilter}[x];[x][1:v]paletteuse=dither=${DitherAlgorithm}:diff_mode=rectangle"

        $pass2Args = $timeArguments + @(
            '-i', $SourcePath
            '-i', $paletteFile
            '-filter_complex', $filterComplex
            '-loop', $LoopCount
            '-y', $DestinationPath
        )

        return (Invoke-FFmpegProcess -Arguments $pass2Args -TimeoutSeconds $TimeoutSeconds)
    }
    finally {
        # Remove the private palette directory (and its contents) even on failure.
        if ($paletteDir -and (Test-Path -Path $paletteDir.FullName)) {
            Remove-Item -Path $paletteDir.FullName -Recurse -Force -ErrorAction SilentlyContinue
        }
    }
}

function Invoke-VideoConversion {
    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$InputPath,

        [Parameter(Mandatory = $false)]
        [string]$OutputPath,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 30)]
        [int]$Fps = 10,

        [Parameter(Mandatory = $false)]
        [ValidateRange(100, 3840)]
        [int]$Width = 1280,

        [Parameter(Mandatory = $false)]
        [ValidateSet('sierra2_4a', 'floyd_steinberg', 'bayer', 'none')]
        [string]$Dither = 'sierra2_4a',

        [Parameter(Mandatory = $false)]
        [ValidateSet('hable', 'reinhard', 'mobius', 'bt2390')]
        [string]$Tonemap = 'hable',

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, [int]::MaxValue)]
        [int]$Loop = 0,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, [double]::MaxValue)]
        [double]$Start,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0.1, [double]::MaxValue)]
        [double]$Duration,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 86400)]
        [int]$TimeoutSeconds = 600,

        [Parameter(Mandatory = $false)]
        [switch]$SkipPalette
    )

    if (-not (Test-FFmpegAvailable)) {
        throw "FFmpeg is not available"
    }

    # Search for input file
    $resolvedInput = $null
    if (Test-Path -Path $InputPath -PathType Leaf) {
        $resolvedInput = (Resolve-Path -Path $InputPath).Path
    }
    else {
        $resolvedInput = Find-VideoFile -Filename $InputPath
        if ($resolvedInput) {
            Write-Host "Found: $resolvedInput"
        }
        else {
            $searchLocations = @(
                "current directory"
                "workspace root"
            )
            if ($IsMacOS) {
                $searchLocations += @("~/Movies", "~/Downloads", "~/Desktop")
            }
            else {
                $searchLocations += @("~/Videos", "~/Downloads", "~/Desktop")
            }
            throw "Input file not found: $InputPath`nSearched: $($searchLocations -join ', ')"
        }
    }

    # Set default output path if not specified
    if ([string]::IsNullOrEmpty($OutputPath)) {
        $inputItem = Get-Item -Path $resolvedInput
        $OutputPath = Join-Path -Path $inputItem.DirectoryName -ChildPath "$($inputItem.BaseName).gif"
    }

    # Refuse to overwrite the source, for example the default output of a .gif input.
    $pathComparison = if ($IsLinux) { [System.StringComparison]::Ordinal } else { [System.StringComparison]::OrdinalIgnoreCase }
    if ([string]::Equals((Resolve-PhysicalPath -Path $OutputPath), (Resolve-PhysicalPath -Path $resolvedInput), $pathComparison)) {
        throw "Output path is the same as the input path: $resolvedInput. Specify a different -OutputPath."
    }

    # Detect HDR content
    $isHDR = Test-HDRContent -FilePath $resolvedInput -TimeoutSeconds $TimeoutSeconds

    # Build base filter chain
    $baseFilter = "fps=$Fps,scale=${Width}:-1:flags=lanczos"

    # Add HDR tonemapping if detected
    if ($isHDR) {
        $hdrFilter = "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=${Tonemap}:desat=0,zscale=t=iec61966-2-1:m=bt709:r=full,format=rgb24"
        $baseFilter = "$hdrFilter,$baseFilter"
    }

    # Build time arguments
    $timeArgs = @()
    if ($PSBoundParameters.ContainsKey('Start')) {
        $timeArgs += $Start
    }
    else {
        $timeArgs += -1  # Sentinel value indicating no start time
    }
    if ($PSBoundParameters.ContainsKey('Duration')) {
        $timeArgs += $Duration
    }

    Write-Host "Converting: $resolvedInput"
    Write-Host "Output:     $OutputPath"
    Write-Host "Settings:   $Fps FPS, ${Width}px width, $Dither dithering, loop=$Loop"

    if ($PSBoundParameters.ContainsKey('Start') -or $PSBoundParameters.ContainsKey('Duration')) {
        $startDisplay = if ($PSBoundParameters.ContainsKey('Start')) { "${Start}s" } else { "0s" }
        $durationDisplay = if ($PSBoundParameters.ContainsKey('Duration')) { "${Duration}s" } else { "full" }
        Write-Host "Time range: start=$startDisplay, duration=$durationDisplay"
    }

    if ($isHDR) {
        Write-Host "HDR:        Detected, applying $Tonemap tonemapping"
    }

    if ($SkipPalette) {
        Write-Host "Mode:       Single-pass (faster, lower quality)"
        Write-Host ""

        $success = Invoke-SinglePassConversion `
            -SourcePath $resolvedInput `
            -DestinationPath $OutputPath `
            -LoopCount $Loop `
            -BaseFilter $baseFilter `
            -TimeArgs $timeArgs `
            -TimeoutSeconds $TimeoutSeconds
    }
    else {
        Write-Host "Mode:       Two-pass palette optimization"
        Write-Host ""

        $success = Invoke-TwoPassConversion `
            -SourcePath $resolvedInput `
            -DestinationPath $OutputPath `
            -DitherAlgorithm $Dither `
            -LoopCount $Loop `
            -BaseFilter $baseFilter `
            -TimeArgs $timeArgs `
            -TimeoutSeconds $TimeoutSeconds
    }

    if ($success -and (Test-Path -Path $OutputPath)) {
        $outputFile = Get-Item -Path $OutputPath
        $formattedSize = Format-FileSize -Bytes $outputFile.Length
        Write-Host ""
        Write-Host "Conversion complete: $OutputPath ($formattedSize)" -ForegroundColor Green
    }
    else {
        throw "Conversion failed. Output file was not created."
    }
}

#endregion Functions

#region Main Execution

if ($MyInvocation.InvocationName -ne '.') {
    try {
        Invoke-VideoConversion @PSBoundParameters
        exit 0
    }
    catch {
        Write-Error -ErrorAction Continue "Video conversion failed: $($_.Exception.Message)"
        exit 1
    }
}

#endregion Main Execution

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs a command-line tool

The author says: Requires FFmpeg on PATH

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Microsoft
Publisher
Microsoft (Official)
Source
microsoft/hve-core · .github/skills/experimental/video-to-gif · commit f425e94
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Microsoft.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download video-to-gif.zip