
Video To Gif
- 29 installs
- 1.3k repo stars
- Updated July 27, 2026
- microsoft/hve-core
video-to-gif converts videos to optimized GIFs with FFmpeg.
About
The video-to-gif skill converts video files to optimized GIF animations with FFmpeg two-pass palette optimization for better color fidelity and smaller sizes. Scripts convert.sh and convert.ps1 support fps, width, dithering, HDR tonemapping, trim start and duration, and loop count. Automatic HDR detection via ffprobe applies tonemapping algorithms hable, reinhard, mobius, or bt2390. File search checks cwd, workspace root, Movies or Videos, Downloads, and Desktop when paths are partial. Requires FFmpeg on PATH with install instructions for macOS, Linux, and Windows. Output includes absolute path link to the generated GIF.
- Two-pass FFmpeg palette optimization for quality GIFs.
- Bash and PowerShell scripts with HDR auto-detection.
- Configurable fps, width, dither, trim, and loop options.
- Smart file search across common video folders.
- Returns absolute path to output GIF for review.
Video To Gif by the numbers
- 29 all-time installs (skills.sh)
- Ranked #978 of 1,340 Generative Media skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
video-to-gif capabilities & compatibility
- Capabilities
- two pass palette optimization workflow
- Use cases
- video generation
What video-to-gif says it does
converts video files to optimized GIF animations using FFmpeg two-pass palette optimization
npx skills add https://github.com/microsoft/hve-core --skill video-to-gifAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 29 |
|---|---|
| repo stars | ★ 1.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 27, 2026 |
| Repository | microsoft/hve-core ↗ |
How do I convert a video to a high-quality GIF?
Convert videos to optimized GIFs using FFmpeg two-pass palette generation.
Who is it for?
Creators making demo GIFs from screen recordings or videos.
Skip if: Skip for video encoding to MP4 or streaming formats.
When should I use this skill?
User wants video converted to GIF with FFmpeg.
What you get
Optimized GIF file path from two-pass FFmpeg conversion.
Files
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.gifThis 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 ffmpegLinux (Debian/Ubuntu)
sudo apt update && sudo apt install ffmpegWindows
Using Chocolatey:
choco install ffmpegUsing winget:
winget install FFmpeg.FFmpegVerify installation:
ffmpeg -versionQuick Start
Convert a video using default settings (10 FPS, 1280px width, sierra2_4a dithering):
scripts/convert.sh input.mp4scripts/convert.ps1 -InputPath input.mp4Output 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:
| Algorithm | Characteristics |
|---|---|
| hable | Filmic curve, good highlight rolloff (default) |
| reinhard | Preserves more color saturation |
| mobius | Similar to reinhard with better highlights |
| bt2390 | ITU standard, more conservative |
Parameters Reference
| Parameter | Flag (bash) | Flag (PowerShell) | Default | Description |
|---|---|---|---|---|
| Input file | --input | -InputPath | (required) | Source video file path |
| Output file | --output | -OutputPath | input.gif | Destination GIF file path |
| Frame rate | --fps | -Fps | 10 | Frames per second |
| Width | --width | -Width | 1280 | Output width in pixels |
| Dithering | --dither | -Dither | sierra2_4a | Dithering algorithm |
| Tonemapping | --tonemap | -Tonemap | hable | HDR tonemapping algorithm |
| Skip palette | --skip-palette | -SkipPalette | false | Use single-pass mode |
| Start time | --start | -Start | 0 | Start time in seconds |
| Duration | --duration | -Duration | (full video) | Duration to convert in seconds |
| Loop count | --loop | -Loop | 0 | GIF loop count (0 = infinite) |
Frame Rate (FPS)
FPS controls animation smoothness and file size. Lower values reduce file size but create choppier motion.
| FPS | Use Case |
|---|---|
| 5 | Simple animations, icons |
| 10 | General use (default) |
| 15 | Smooth motion, UI demos |
| 24 | Near-video quality |
Width
Width sets the output horizontal resolution in pixels. Height scales proportionally to maintain aspect ratio.
| Width | Use Case |
|---|---|
| 320 | Thumbnails, previews |
| 640 | Documentation |
| 800 | Presentations |
| 1280 | High detail (default) |
Dithering Algorithms
Dithering determines how the 256-color GIF palette approximates the original colors.
| Algorithm | Quality | Speed | Best For |
|---|---|---|---|
| sierra2_4a | High | Medium | General use (default) |
| floyd_steinberg | High | Slow | Photographic content |
| bayer | Medium | Fast | Graphics with solid colors |
| none | Low | Fastest | Stylized/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 10Loop Control
Use --loop to control GIF repeat behavior:
| Value | Behavior |
|---|---|
| 0 | Loop forever |
| 1 | Play once |
| N | Play 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.gifTwo-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.gifSingle-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-paletteconvert.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 -SkipPaletteExamples
HDR Video Conversion
HDR content is detected automatically. No special flags are needed:
scripts/convert.sh hdr-footage.movThe 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 reinhardTime 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 15Documentation Thumbnails
Create compact thumbnails for documentation:
scripts/convert.sh --input demo.mp4 --width 320 --fps 8Troubleshooting
FFmpeg not found
Verify FFmpeg is in your PATH:
which ffmpeg # macOS/Linux
where.exe ffmpeg # WindowsIf 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
bayerdithering for faster processing - Use
--durationto 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-devIf 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 -versionTemporary 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.
Quick Usage Examples
Basic Conversion
# Convert with defaults (10 FPS, 480px, sierra2_4a dithering)
../convert.sh video.mp4
# Specify output filename
../convert.sh --input video.mp4 --output demo.gif# Convert with defaults
../convert.ps1 -InputPath video.mp4
# Specify output filename
../convert.ps1 -InputPath video.mp4 -OutputPath demo.gifHigh Quality Demo
../convert.sh --input presentation.mp4 --fps 15 --width 800 --dither floyd_steinberg../convert.ps1 -InputPath presentation.mp4 -Fps 15 -Width 800 -Dither floyd_steinbergSmall File Size
../convert.sh --input video.mp4 --fps 5 --width 320 --dither bayer../convert.ps1 -InputPath video.mp4 -Fps 5 -Width 320 -Dither bayerTest Video Generation
Create a test video using FFmpeg's test source filter. This generates a 5-second video with color bars and a timer.
ffmpeg -f lavfi -i "testsrc=duration=5:size=640x480:rate=30" \
-c:v libx264 -pix_fmt yuv420p test-video.mp4Alternative test patterns:
# Color bars with audio
ffmpeg -f lavfi -i "smptebars=duration=5:size=640x480:rate=30" \
-f lavfi -i "sine=frequency=1000:duration=5" \
-c:v libx264 -c:a aac -pix_fmt yuv420p test-bars.mp4
# Mandelbrot fractal zoom
ffmpeg -f lavfi -i "mandelbrot=size=640x480:rate=30" \
-t 5 -c:v libx264 -pix_fmt yuv420p test-fractal.mp4
# Random noise
ffmpeg -f lavfi -i "nullsrc=size=640x480:rate=30,geq=random(1)*255:128:128" \
-t 3 -c:v libx264 -pix_fmt yuv420p test-noise.mp4Quality Comparison
Compare dithering algorithms by converting the same source with different settings:
# Generate all variants
for dither in sierra2_4a floyd_steinberg bayer none; do
../convert.sh --input test-video.mp4 --output "test-${dither}.gif" --dither "${dither}"
done# Generate all variants
@('sierra2_4a', 'floyd_steinberg', 'bayer', 'none') | ForEach-Object {
../convert.ps1 -InputPath test-video.mp4 -OutputPath "test-$_.gif" -Dither $_
}Expected results:
| Algorithm | File Size | Visual Quality | Processing Time |
|---|---|---|---|
| sierra2_4a | Medium | High | Medium |
| floyd_steinberg | Medium | Highest | Slow |
| bayer | Smaller | Medium | Fast |
| none | Smallest | Low | Fastest |
File Size Optimization
Strategies for reducing GIF file size:
Reduce Frame Rate
Lower frame rates significantly reduce file size. For simple animations, 5-8 FPS is often sufficient.
../convert.sh --input video.mp4 --fps 5Reduce Dimensions
Smaller dimensions dramatically reduce file size. 320px width works well for thumbnails.
../convert.sh --input video.mp4 --width 320Trim Source Duration
Shorter videos produce smaller GIFs. Trim before conversion:
# Extract 3 seconds starting at 00:05
ffmpeg -i video.mp4 -ss 00:00:05 -t 3 -c copy trimmed.mp4
../convert.sh trimmed.mp4Combine Optimizations
Stack multiple optimizations for maximum compression:
../convert.sh --input video.mp4 --fps 8 --width 320 --dither bayerBatch Conversion
Convert multiple videos in a directory:
for video in *.mp4; do
../convert.sh --input "${video}"
doneGet-ChildItem -Filter "*.mp4" | ForEach-Object {
../convert.ps1 -InputPath $_.FullName
}Convert with consistent settings:
for video in *.mp4; do
../convert.sh --input "${video}" --fps 12 --width 640 --dither sierra2_4a
doneGet-ChildItem -Filter "*.mp4" | ForEach-Object {
../convert.ps1 -InputPath $_.FullName -Fps 12 -Width 640 -Dither sierra2_4a
}🤖 Crafted with precision by ✨Copilot following brilliant human instruction, then carefully refined by our team of discerning human reviewers.
#!/usr/bin/env pwsh
# Copyright (c) Microsoft Corporation.
# 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.
.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)]
[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 Test-HDRContent {
<#
.SYNOPSIS
Detect if video contains HDR content using ffprobe.
#>
param(
[Parameter(Mandatory = $true)]
[string]$FilePath
)
$ffprobePath = Get-Command -Name 'ffprobe' -ErrorAction SilentlyContinue
if (-not $ffprobePath) {
return $false
}
try {
$colorInfo = & ffprobe -v error -select_streams v:0 `
-show_entries stream=color_primaries,color_transfer `
-of csv=p=0 $FilePath 2>$null
# Check for HDR indicators: bt2020 primaries or smpte2084 transfer
if ($colorInfo -match 'bt2020|smpte2084') {
return $true
}
}
catch {
Write-Verbose "ffprobe failed, assuming SDR content: $_"
}
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-SinglePassConversion {
param(
[string]$SourcePath,
[string]$DestinationPath,
[int]$LoopCount,
[string]$BaseFilter,
[double[]]$TimeArgs
)
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
)
& ffmpeg @arguments
return $LASTEXITCODE -eq 0
}
function Invoke-TwoPassConversion {
param(
[string]$SourcePath,
[string]$DestinationPath,
[string]$DitherAlgorithm,
[int]$LoopCount,
[string]$BaseFilter,
[double[]]$TimeArgs
)
$paletteFile = Join-Path -Path $env:TEMP -ChildPath "palette_$PID.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
)
& ffmpeg @pass1Args
if ($LASTEXITCODE -ne 0) {
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
)
& ffmpeg @pass2Args
return $LASTEXITCODE -eq 0
}
finally {
# Cleanup palette file
if (Test-Path -Path $paletteFile) {
Remove-Item -Path $paletteFile -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)]
[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"
}
# Detect HDR content
$isHDR = Test-HDRContent -FilePath $resolvedInput
# 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
}
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
}
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
#!/usr/bin/env bash
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: MIT
#
# convert.sh
# Convert video files to optimized GIF animations using FFmpeg two-pass palette optimization
# Features: HDR auto-detection with tonemapping, workspace-first file search, time range selection
set -euo pipefail
# Default values
DEFAULT_FPS=10
DEFAULT_WIDTH=1280
DEFAULT_DITHER="sierra2_4a"
DEFAULT_TONEMAP="hable"
DEFAULT_LOOP=0
usage() {
echo "Usage: ${0##*/} [OPTIONS] [INPUT_FILE]"
echo ""
echo "Convert video files to optimized GIF animations."
echo ""
echo "Options:"
echo " --input FILE Input video file (required if not positional)"
echo " --output FILE Output GIF file (defaults to input with .gif extension)"
echo " --fps N Frame rate (default: ${DEFAULT_FPS})"
echo " --width N Output width in pixels (default: ${DEFAULT_WIDTH})"
echo " --dither ALG Dithering algorithm (default: ${DEFAULT_DITHER})"
echo " Options: sierra2_4a, floyd_steinberg, bayer, none"
echo " --tonemap ALG HDR tonemapping algorithm (default: ${DEFAULT_TONEMAP})"
echo " Options: hable, reinhard, mobius, bt2390"
echo " --start N Start time in seconds (default: 0)"
echo " --duration N Duration to convert in seconds (default: full video)"
echo " --loop N GIF loop count, 0=infinite (default: ${DEFAULT_LOOP})"
echo " --skip-palette Use single-pass mode (faster, lower quality)"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " ${0##*/} video.mp4"
echo " ${0##*/} --input video.mp4 --output demo.gif --fps 15"
echo " ${0##*/} --input video.mp4 --start 5 --duration 10"
exit 1
}
err() {
printf "ERROR: %s\n" "$1" >&2
exit 1
}
get_file_size() {
local file="$1"
if [[ "$(uname)" == "Darwin" ]]; then
stat -f%z "${file}"
else
stat -c%s "${file}"
fi
}
format_size() {
local bytes="$1"
if (( bytes >= 1048576 )); then
printf "%.2f MB" "$(echo "scale=2; ${bytes} / 1048576" | bc)"
elif (( bytes >= 1024 )); then
printf "%.2f KB" "$(echo "scale=2; ${bytes} / 1024" | bc)"
else
printf "%d bytes" "${bytes}"
fi
}
# Find file using prefix matching to handle Unicode whitespace mismatches
# macOS screen recordings use non-breaking spaces (U+00A0) that look like ASCII spaces
find_by_prefix() {
local dir="$1"
local basename="$2"
[[ -d "${dir}" ]] || return 1
local base_no_ext="${basename%.*}"
local ext="${basename##*.}"
local prefix="${base_no_ext:0:15}"
local found_file
while IFS= read -r -d '' found_file; do
echo "${found_file}"
return 0
done < <(find "${dir}" -maxdepth 1 -type f -name "${prefix}*.${ext}" -print0 2>/dev/null)
return 1
}
# Search for file in workspace and common directories
find_video_file() {
local filename="$1"
# Direct path lookup
if [[ -f "${filename}" ]]; then
echo "${filename}"
return 0
fi
# Extract directory and basename for prefix matching
local dir_part base_part
if [[ "${filename}" == */* ]]; then
dir_part="${filename%/*}"
base_part="${filename##*/}"
else
dir_part=""
base_part="${filename}"
fi
# For absolute paths, try prefix matching in the specified directory
if [[ "${filename}" == /* ]]; then
if find_by_prefix "${dir_part}" "${base_part}"; then
return 0
fi
return 1
fi
# Build search locations for relative paths
local search_dirs=("." "${PWD}")
local git_root
if git_root=$(git rev-parse --show-toplevel 2>/dev/null); then
search_dirs+=("${git_root}")
fi
if [[ "$(uname)" == "Darwin" ]]; then
search_dirs+=("${HOME}/Movies" "${HOME}/Downloads" "${HOME}/Desktop")
else
search_dirs+=("${HOME}/Videos" "${HOME}/Downloads" "${HOME}/Desktop")
fi
for dir in "${search_dirs[@]}"; do
# Try exact match first
if [[ -f "${dir}/${filename}" ]]; then
echo "${dir}/${filename}"
return 0
fi
# Fall back to prefix matching for Unicode whitespace issues
if find_by_prefix "${dir}" "${base_part}"; then
return 0
fi
done
return 1
}
# Detect if video is HDR using ffprobe
detect_hdr() {
local file="$1"
if ! command -v ffprobe &>/dev/null; then
echo "false"
return
fi
local color_info
color_info=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=color_primaries,color_transfer \
-of csv=p=0 "${file}" 2>/dev/null || echo "")
# Check for HDR indicators: bt2020 primaries or smpte2084 transfer
if [[ "${color_info}" == *"bt2020"* ]] || [[ "${color_info}" == *"smpte2084"* ]]; then
echo "true"
else
echo "false"
fi
}
main() {
local input_file=""
local output_file=""
local fps="${DEFAULT_FPS}"
local width="${DEFAULT_WIDTH}"
local dither="${DEFAULT_DITHER}"
local tonemap="${DEFAULT_TONEMAP}"
local loop="${DEFAULT_LOOP}"
local start_time=""
local duration=""
local skip_palette=false
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--input)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--input requires a file path"
fi
input_file="$2"
shift 2
;;
--output)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--output requires a file path"
fi
output_file="$2"
shift 2
;;
--fps)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--fps requires a number"
fi
fps="$2"
shift 2
;;
--width)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--width requires a number"
fi
width="$2"
shift 2
;;
--dither)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--dither requires an algorithm name"
fi
dither="$2"
shift 2
;;
--tonemap)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--tonemap requires an algorithm name"
fi
tonemap="$2"
shift 2
;;
--start)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--start requires a number"
fi
start_time="$2"
shift 2
;;
--duration)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--duration requires a number"
fi
duration="$2"
shift 2
;;
--loop)
if [[ -z "${2:-}" || "$2" == --* ]]; then
err "--loop requires a number"
fi
loop="$2"
shift 2
;;
--skip-palette)
skip_palette=true
shift
;;
--help|-h)
usage
;;
-*)
err "Unknown option: $1"
;;
*)
if [[ -z "${input_file}" ]]; then
input_file="$1"
else
err "Unexpected argument: $1"
fi
shift
;;
esac
done
# Validate input file
if [[ -z "${input_file}" ]]; then
err "Input file is required. Use --input FILE or provide as positional argument."
fi
# Search for file if not found at given path
if [[ ! -f "${input_file}" ]]; then
local found_file
if found_file=$(find_video_file "${input_file}") && [[ -n "${found_file}" ]]; then
echo "Found: ${found_file}"
input_file="${found_file}"
else
err "Input file not found: ${input_file}
Searched: current directory, workspace root, ~/Movies (or ~/Videos), ~/Downloads, ~/Desktop"
fi
fi
# Set default output file if not specified
if [[ -z "${output_file}" ]]; then
output_file="${input_file%.*}.gif"
fi
# Validate dithering algorithm
case "${dither}" in
sierra2_4a|floyd_steinberg|bayer|none) ;;
*)
err "Invalid dithering algorithm: ${dither}. Options: sierra2_4a, floyd_steinberg, bayer, none"
;;
esac
# Validate tonemapping algorithm
case "${tonemap}" in
hable|reinhard|mobius|bt2390) ;;
*)
err "Invalid tonemapping algorithm: ${tonemap}. Options: hable, reinhard, mobius, bt2390"
;;
esac
# Check for FFmpeg
if ! command -v ffmpeg &>/dev/null; then
echo "ERROR: FFmpeg is required but not installed." >&2
echo "" >&2
echo "Install FFmpeg:" >&2
echo " macOS: brew install ffmpeg" >&2
echo " Ubuntu: sudo apt install ffmpeg" >&2
echo " Windows: choco install ffmpeg" >&2
exit 1
fi
# Detect HDR content
local is_hdr
is_hdr=$(detect_hdr "${input_file}")
# Build time range arguments
local time_args=()
if [[ -n "${start_time}" ]]; then
time_args+=(-ss "${start_time}")
fi
if [[ -n "${duration}" ]]; then
time_args+=(-t "${duration}")
fi
echo "Converting: ${input_file}"
echo "Output: ${output_file}"
echo "Settings: ${fps} FPS, ${width}px width, ${dither} dithering, loop=${loop}"
if [[ -n "${start_time}" ]] || [[ -n "${duration}" ]]; then
echo "Time range: start=${start_time:-0}s, duration=${duration:-full}"
fi
if [[ "${is_hdr}" == "true" ]]; then
echo "HDR: Detected, applying ${tonemap} tonemapping"
fi
# Build video filter chain
local base_filter="fps=${fps},scale=${width}:-1:flags=lanczos"
# Add HDR tonemapping if detected
# Convert HDR to SDR using selected tonemapping algorithm, then explicitly convert to sRGB for accurate GIF colors
if [[ "${is_hdr}" == "true" ]]; then
base_filter="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,${base_filter}"
fi
if [[ "${skip_palette}" == true ]]; then
echo "Mode: Single-pass (faster, lower quality)"
echo ""
ffmpeg "${time_args[@]}" -i "${input_file}" \
-vf "${base_filter}" \
-loop "${loop}" -y "${output_file}"
else
echo "Mode: Two-pass palette optimization"
echo ""
local palette_file="/tmp/palette_$$.png"
# Pass 1: Generate palette
echo "Pass 1: Generating optimized palette..."
ffmpeg "${time_args[@]}" -i "${input_file}" \
-vf "${base_filter},palettegen=stats_mode=diff" \
-y "${palette_file}"
# Pass 2: Create GIF
echo "Pass 2: Creating GIF with palette..."
ffmpeg "${time_args[@]}" -i "${input_file}" -i "${palette_file}" \
-filter_complex "${base_filter}[x];[x][1:v]paletteuse=dither=${dither}:diff_mode=rectangle" \
-loop "${loop}" -y "${output_file}"
# Cleanup palette file
rm -f "${palette_file}"
fi
if [[ -f "${output_file}" ]]; then
local file_size
file_size=$(get_file_size "${output_file}")
echo ""
echo "Conversion complete: ${output_file} ($(format_size "${file_size}"))"
else
err "Conversion failed. Output file was not created."
fi
}
main "$@"
Related skills
FAQ
What does video-to-gif do?
video-to-gif converts videos to optimized GIFs with FFmpeg.
When should I use video-to-gif?
User wants video converted to GIF with FFmpeg.
Is this skill safe to install?
Review the Security Audits panel on this page before installing in production.