Update tech_docs/linux/ffmpeg_guide.md

This commit is contained in:
2025-06-30 05:19:16 +00:00
parent fe5fcab388
commit 2658f299eb

View File

@@ -1,80 +1,343 @@
Creating a basic guide to `ffmpeg` involves covering some of the most common and useful tasks you can perform with this versatile tool. `ffmpeg` is a powerful command-line tool that allows for video, audio, and other multimedia file processing. Here's a beginner-friendly guide to get you started: # Comprehensive FFmpeg Guide for Beginners
### Introduction to FFmpeg ## Introduction to FFmpeg
`ffmpeg` is a comprehensive multimedia processing tool that supports a wide range of formats and tasks, including video and audio conversion, processing, streaming, and more. It's used by professionals and hobbyists alike for its flexibility and powerful capabilities. FFmpeg is a complete, cross-platform solution to record, convert, and stream audio and video. It's the Swiss Army knife of multimedia processing, powering countless applications and services you use daily, including YouTube, Netflix, VLC media player, and many others. Originally developed in 2000, FFmpeg has become the de facto standard for multimedia processing due to its incredible versatility, performance, and open-source nature.
### Installing FFmpeg ### What Makes FFmpeg Special?
Before diving into `ffmpeg` commands, ensure you have `ffmpeg` installed on your system. - **Universal Format Support**: Supports over 100 video codecs and 900+ audio codecs
- **Cross-Platform**: Runs on Windows, macOS, Linux, and various Unix systems
- **Command-Line Power**: Enables automation and batch processing
- **Professional Grade**: Used in broadcast television, streaming services, and film production
- **Free and Open Source**: No licensing fees, with full source code availability
- **On Ubuntu/Debian:** ### Key Concepts to Understand
Before diving into commands, it's important to understand these fundamental concepts:
- **Container vs Codec**: A container (like MP4, AVI, MKV) holds multiple streams, while codecs (like H.264, AAC) compress the actual data
- **Streams**: A multimedia file typically contains video streams, audio streams, and sometimes subtitle streams
- **Transcoding vs Transmuxing**: Transcoding re-encodes data (quality loss, slower), while transmuxing just changes the container (lossless, faster)
## Installing FFmpeg
### Windows
1. **Direct Download**: Visit [https://ffmpeg.org/download.html](https://ffmpeg.org/download.html) and download the Windows build
2. **Using Chocolatey**:
```cmd
choco install ffmpeg
```
3. **Using Scoop**:
```cmd
scoop install ffmpeg
```
### macOS
```bash ```bash
# Using Homebrew (recommended)
brew install ffmpeg
# For additional codec support
brew install ffmpeg --with-libvpx --with-libvorbis --with-fdk-aac
```
### Linux
```bash
# Ubuntu/Debian
sudo apt update sudo apt update
sudo apt install ffmpeg sudo apt install ffmpeg
```
- **On Fedora:** # Fedora/RHEL/CentOS
```bash
sudo dnf install ffmpeg sudo dnf install ffmpeg
# Arch Linux
sudo pacman -S ffmpeg
# For the latest version, compile from source
git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
cd ffmpeg
./configure --enable-gpl --enable-libx264 --enable-libx265
make -j$(nproc)
sudo make install
``` ```
- **On macOS (using Homebrew):**
### Verifying Installation
```bash ```bash
brew install ffmpeg ffmpeg -version
``` ```
This should display version information and supported formats.
### Basic FFmpeg Commands ## Understanding FFmpeg Command Structure
#### 1. Converting Video Formats
One of the most common tasks is converting videos from one format to another. To convert a video file, use the following command structure:
Every FFmpeg command follows this basic pattern:
```bash ```bash
ffmpeg -i input.mp4 output.avi ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url}
``` ```
Replace `input.mp4` with your source file and `output.avi` with the desired output filename and format.
#### 2. Extracting Audio from Video ### Common Global Options
- `-y`: Overwrite output files without asking
- `-n`: Never overwrite output files
- `-f`: Force input or output file format
- `-t`: Duration of output
- `-ss`: Start time offset
- `-v`: Set logging level (quiet, error, warning, info, verbose, debug)
You can extract audio tracks from a video file into a separate audio file using: ## Essential FFmpeg Commands with Context
### 1. Format Conversion and Transcoding
#### Basic Format Conversion
```bash ```bash
ffmpeg -i input.mp4 -vn output.mp3 # Simple container change (fast, no quality loss)
ffmpeg -i input.mkv -c copy output.mp4
# Full transcoding (slower, potential quality loss)
ffmpeg -i input.avi -c:v libx264 -c:a aac output.mp4
``` ```
This command takes the audio from `input.mp4` and outputs it to `output.mp3`, without the video part (`-vn` stands for "video no").
#### 3. Trimming Video Files
To trim a video file without re-encoding, specify the start time (`-ss`) and the duration (`-t`) of the clip you want to extract:
#### High-Quality Conversion with Custom Settings
```bash ```bash
ffmpeg -ss 00:00:10 -t 00:00:30 -i input.mp4 -c copy output.mp4 # H.264 with high quality settings
ffmpeg -i input.mov \
-c:v libx264 \
-preset slow \
-crf 18 \
-c:a aac \
-b:a 192k \
output.mp4
``` ```
This command extracts a 30-second clip starting at the 10-second mark from `input.mp4` to `output.mp4`, copying the streams directly without re-encoding.
#### 4. Combining Video and Audio **Context**: The `crf` (Constant Rate Factor) value controls quality. Lower values = higher quality. Range is 0-51, with 18-28 being visually lossless to good quality.
To combine a video file with an audio track, use:
#### Converting for Different Platforms
```bash ```bash
ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a aac output.mp4 # YouTube recommended settings
ffmpeg -i input.mp4 \
-c:v libx264 \
-preset slow \
-crf 20 \
-c:a aac \
-b:a 128k \
-pix_fmt yuv420p \
-movflags +faststart \
youtube_upload.mp4
# Instagram video (square format)
ffmpeg -i input.mp4 \
-vf "scale=1080:1080:force_original_aspect_ratio=decrease,pad=1080:1080:(ow-iw)/2:(oh-ih)/2" \
-c:v libx264 \
-crf 23 \
-c:a aac \
instagram.mp4
``` ```
This merges `video.mp4` and `audio.mp3` into `output.mp4`, copying the video codec and transcoding the audio to AAC.
#### 5. Reducing Video File Size ### 2. Audio Extraction and Processing
To reduce the size of a video file, you can change the bitrate or use a different codec:
#### Extract Audio in Various Formats
```bash ```bash
ffmpeg -i input.mp4 -b:v 1000k -c:a copy output.mp4 # Extract as MP3 with specific bitrate
ffmpeg -i input.mp4 -vn -c:a libmp3lame -b:a 320k output.mp3
# Extract as FLAC (lossless)
ffmpeg -i input.mp4 -vn -c:a flac output.flac
# Extract specific audio stream (if multiple exist)
ffmpeg -i input.mkv -map 0:a:1 -c:a copy audio_track_2.aac
``` ```
This command re-encodes the video to have a lower bitrate (`1000k` bits per second), potentially reducing the file size.
### Tips for Learning FFmpeg #### Audio Enhancement and Processing
```bash
# Normalize audio levels
ffmpeg -i input.mp4 -af "loudnorm=I=-16:TP=-1.5:LRA=11" normalized.mp4
- **Explore the Help Option**: `ffmpeg` comes with extensive documentation. Run `ffmpeg -h` to see an overview or `ffmpeg -h full` for detailed options. # Remove background noise
- **Experiment with Different Options**: `ffmpeg` has numerous options and filters that allow for complex processing. Experimenting is a great way to learn. ffmpeg -i noisy_audio.wav -af "highpass=f=200,lowpass=f=3000" clean_audio.wav
- **Consult the FFmpeg Documentation**: The [FFmpeg Documentation](https://ffmpeg.org/documentation.html) is a comprehensive resource for understanding all of its capabilities.
### Conclusion # Convert stereo to mono
ffmpeg -i stereo.wav -ac 1 mono.wav
```
This guide provides a starting point for using `ffmpeg`, covering some basic tasks. `ffmpeg` is incredibly powerful, and mastering it can take time. Start with these fundamental tasks, and gradually explore more complex commands and options as you become more comfortable with the tool. ### 3. Advanced Video Trimming and Editing
#### Precise Trimming (Stream Copy)
```bash
# Trim without re-encoding (fastest, but may not be frame-accurate)
ffmpeg -ss 00:01:30 -i input.mp4 -t 00:02:00 -c copy output.mp4
# Frame-accurate trimming (slower, but precise)
ffmpeg -i input.mp4 -ss 00:01:30 -t 00:02:00 -c:v libx264 -crf 18 output.mp4
```
#### Multiple Clips from One Video
```bash
# Extract multiple segments in one command
ffmpeg -i input.mp4 \
-ss 00:00:00 -t 00:00:30 -c copy clip1.mp4 \
-ss 00:01:00 -t 00:00:45 -c copy clip2.mp4 \
-ss 00:02:30 -t 00:01:00 -c copy clip3.mp4
```
### 4. Video and Audio Combination
#### Replace Audio Track
```bash
# Replace video's audio with new audio file
ffmpeg -i video.mp4 -i new_audio.mp3 \
-c:v copy \
-c:a aac \
-map 0:v:0 -map 1:a:0 \
output.mp4
# Mix original audio with new audio
ffmpeg -i video.mp4 -i music.mp3 \
-filter_complex "[0:a][1:a]amix=inputs=2:duration=first:dropout_transition=3" \
-c:v copy \
output.mp4
```
### 5. Compression and Quality Control
#### Size-Based Compression
```bash
# Target specific file size (2-pass encoding for better quality)
ffmpeg -i input.mp4 -c:v libx264 -b:v 1000k -pass 1 -f null /dev/null
ffmpeg -i input.mp4 -c:v libx264 -b:v 1000k -pass 2 output.mp4
# Quick size reduction with quality control
ffmpeg -i input.mp4 \
-vf "scale=1280:720" \
-c:v libx264 \
-crf 28 \
-preset fast \
-c:a aac \
-b:a 96k \
compressed.mp4
```
### 6. Batch Processing and Automation
#### Process Multiple Files
```bash
# Bash script for batch conversion
for file in *.mov; do
ffmpeg -i "$file" -c:v libx264 -crf 20 -c:a aac "${file%.mov}.mp4"
done
# Windows batch conversion
for %%i in (*.avi) do ffmpeg -i "%%i" -c:v libx264 -crf 20 "%%~ni.mp4"
```
### 7. Advanced Filtering and Effects
#### Video Filters
```bash
# Add watermark
ffmpeg -i input.mp4 -i watermark.png \
-filter_complex "overlay=W-w-10:H-h-10" \
watermarked.mp4
# Create thumbnail grid
ffmpeg -i input.mp4 -vf "select=not(mod(n\,1000)),scale=320:240,tile=3x3" thumbnails.png
# Stabilize shaky video
ffmpeg -i shaky.mp4 -vf "vidstabdetect=shakiness=10:accuracy=15" -f null -
ffmpeg -i shaky.mp4 -vf "vidstabtransform=smoothing=30" stabilized.mp4
```
#### Color Correction and Enhancement
```bash
# Adjust brightness, contrast, saturation
ffmpeg -i input.mp4 -vf "eq=brightness=0.1:contrast=1.2:saturation=1.3" enhanced.mp4
# Convert to black and white
ffmpeg -i input.mp4 -vf "hue=s=0" grayscale.mp4
```
## Advanced Topics
### Understanding Codecs and When to Use Them
#### Video Codecs
- **H.264 (libx264)**: Universal compatibility, good quality-to-size ratio
- **H.265 (libx265)**: Better compression than H.264, newer device support
- **VP9 (libvpx-vp9)**: Open-source, good for web streaming
- **AV1 (libaom-av1)**: Newest, best compression, limited hardware support
#### Audio Codecs
- **AAC**: Best general-purpose codec, wide compatibility
- **MP3 (libmp3lame)**: Universal compatibility, larger files
- **Opus (libopus)**: Best quality-to-size ratio, newer format
- **FLAC**: Lossless compression for archival purposes
### Performance Optimization
#### Hardware Acceleration
```bash
# NVIDIA GPU acceleration (if available)
ffmpeg -hwaccel nvdec -i input.mp4 -c:v h264_nvenc -preset fast output.mp4
# Intel Quick Sync Video
ffmpeg -hwaccel qsv -i input.mp4 -c:v h264_qsv output.mp4
# Check available hardware acceleration
ffmpeg -hwaccels
```
#### Multi-threading
```bash
# Utilize all CPU cores
ffmpeg -i input.mp4 -threads 0 -c:v libx264 output.mp4
# Limit CPU usage
ffmpeg -i input.mp4 -threads 4 -c:v libx264 output.mp4
```
## Troubleshooting Common Issues
### Error Messages and Solutions
1. **"codec not supported"**: Install FFmpeg with additional codec support
2. **"Permission denied"**: Check file permissions and output directory
3. **"Invalid data found when processing input"**: File may be corrupted or unsupported format
4. **Out of memory errors**: Use 2-pass encoding or reduce resolution
### Debugging Commands
```bash
# Analyze file information
ffprobe -v quiet -print_format json -show_format -show_streams input.mp4
# Test without output
ffmpeg -f lavfi -i testsrc=duration=10:size=320x240:rate=30 -f null -
# Verbose logging
ffmpeg -v debug -i input.mp4 output.mp4
```
## Best Practices and Pro Tips
### Quality Preservation
- Use `-c copy` when possible to avoid re-encoding
- For long-term archival, consider lossless formats
- Always keep original files as backups
- Test settings on small clips before processing large files
### Workflow Optimization
- Create preset files for common tasks
- Use batch scripts for repetitive operations
- Monitor system resources during encoding
- Consider cloud processing for large-scale operations
### Learning Resources
- **Official Documentation**: [https://ffmpeg.org/documentation.html](https://ffmpeg.org/documentation.html)
- **FFmpeg Wiki**: [https://trac.ffmpeg.org/wiki](https://trac.ffmpeg.org/wiki)
- **Command Generator**: [https://ffmpeg.guide/](https://ffmpeg.guide/)
- **Community Forums**: Stack Overflow, Reddit r/ffmpeg
## Conclusion
FFmpeg is an incredibly powerful tool that can handle virtually any multimedia processing task. This guide covers the fundamentals, but FFmpeg's capabilities extend far beyond what's presented here. The key to mastering FFmpeg is consistent practice and experimentation.
Start with simple tasks like format conversion and gradually work your way up to more complex operations like filtering and batch processing. Remember that FFmpeg's flexibility means there are often multiple ways to achieve the same result—find the approach that works best for your specific needs and workflow.
As you become more comfortable with FFmpeg, you'll discover it's not just a tool, but a foundation for building sophisticated multimedia processing workflows that can save countless hours and produce professional-quality results.