# FFmpeg NVENC

使用 NVIDIA GPU 的硬件加速视频编码。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行： [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

* 在以下位置查找连接详情： **我的订单**
* Web 界面：使用 HTTP 端口的 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 NVENC？

NVENC（NVIDIA 视频编码器）提供：

* 比 CPU 快 5-10 倍的编码速度
* 支持 H.264、H.265/HEVC、AV1
* 实时 4K/8K 编码
* 较低的 GPU 计算使用率

## 要求

| 编码器   | 最小 GPU       | 推荐           |
| ----- | ------------ | ------------ |
| H.264 | GTX 600 及以上  | RTX 3060 及以上 |
| HEVC  | GTX 900 及以上  | RTX 3070 及以上 |
| AV1   | RTX 4000 及以上 | 512x512      |

## 快速部署

**Docker 镜像：**

```
nvidia/cuda:12.1.0-devel-ubuntu22.04
```

**端口：**

```
22/tcp
```

**命令：**

```bash
apt-get update && \
apt-get install -y ffmpeg && \
echo "FFmpeg with NVENC ready"
```

## 检查 NVENC 支持

```bash

# 检查可用的编码器
ffmpeg -encoders | grep nvenc

# 应显示：

# V....D h264_nvenc

# V....D hevc_nvenc

# V....D av1_nvenc (RTX 4000+)
```

## 基本编码

### H.264 编码

```bash
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p7 -cq 23 output.mp4
```

### HEVC/H.265 编码

```bash
ffmpeg -i input.mp4 -c:v hevc_nvenc -preset p7 -cq 23 output.mp4
```

### AV1 编码（RTX 4000+）

```bash
ffmpeg -i input.mp4 -c:v av1_nvenc -preset p7 -cq 23 output.mp4
```

## 预设

| 预设    | 质量 | 性能 |
| ----- | -- | -- |
| p1    | 最低 | 最快 |
| p2-p3 | 低  | 快速 |
| p4-p5 | 中等 | 平衡 |
| p6-p7 | 高  | 慢  |

```bash

# 最快的编码
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p1 output.mp4

# 最佳质量
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p7 output.mp4
```

## 质量控制

### 恒定质量（CQ）

```bash

# 值越低 = 质量越好，文件越大
ffmpeg -i input.mp4 -c:v h264_nvenc -cq 18 output.mp4

# 推荐值：18-28
```

### 恒定比特率（CBR）

```bash
ffmpeg -i input.mp4 -c:v h264_nvenc -b:v 10M output.mp4
```

### 可变比特率（VBR）

```bash
ffmpeg -i input.mp4 -c:v h264_nvenc -b:v 10M -maxrate 15M -bufsize 20M output.mp4
```

## 分辨率与缩放

### 调整视频大小

```bash

# 缩放到 1080p
ffmpeg -i input.mp4 -vf "scale=1920:1080" -c:v h264_nvenc output.mp4

# 缩放到 4K
ffmpeg -i input.mp4 -vf "scale=3840:2160" -c:v hevc_nvenc output.mp4

# 保持纵横比
ffmpeg -i input.mp4 -vf "scale=-1:1080" -c:v h264_nvenc output.mp4
```

### GPU 缩放（更快）

```bash
ffmpeg -hwaccel cuda -hwaccel_output_format cuda \
    -i input.mp4 \
    -vf "scale_cuda=1920:1080" \
    -c:v h264_nvenc output.mp4
```

## 硬件解码 + 编码

完整的 GPU 管道：

```bash
ffmpeg \
    -hwaccel cuda \
    -hwaccel_output_format cuda \
    -i input.mp4 \
    -c:v h264_nvenc \
    -preset p4 \
    output.mp4
```

## 批量转换

### Shell 脚本

```bash
#!/bin/bash
INPUT_DIR=$1
OUTPUT_DIR=$2

mkdir -p "$OUTPUT_DIR"

for file in "$INPUT_DIR"/*.{mp4,mkv,avi,mov}; do
    if [ -f "$file" ]; then
        filename=$(basename "$file")
        name="${filename%.*}"

        ffmpeg -hwaccel cuda -i "$file" \
            -c:v h264_nvenc -preset p5 -cq 23 \
            -c:a aac -b:a 192k \
            "$OUTPUT_DIR/${name}.mp4"

        echo "Converted: $filename"
    fi
done
```

### Python 批处理

```python
import subprocess
批处理处理
from concurrent.futures import ThreadPoolExecutor

def convert_video(input_path, output_path):
    cmd = [
        'ffmpeg', '-y',
        '-hwaccel', 'cuda',
        '-i', input_path,
        '-c:v', 'h264_nvenc',
        '-preset', 'p5',
        '-cq', '23',
        '-c:a', 'aac',
        '-b:a', '192k',
        output_path
    ]
    subprocess.run(cmd, check=True)

input_dir = './videos'
output_dir = './converted'
output_dir = "./relit"

files = [f for f in os.listdir(input_dir) if f.endswith(('.mp4', '.mkv', '.avi'))]

# 并行处理（如果有多 GPU 或足够资源）
for f in files:
    input_path = os.path.join(input_dir, f)
    output_path = os.path.join(output_dir, f.rsplit('.', 1)[0] + '.mp4')
    convert_video(input_path, output_path)
    print(f"Converted: {f}")
```

## 常见任务

### 转换为 Web 优化的 MP4

```bash
ffmpeg -i input.mp4 \
    -c:v h264_nvenc -preset p5 -cq 23 \
    -c:a aac -b:a 128k \
    -movflags +faststart \
    web_video.mp4
```

### 提取音频

```bash
ffmpeg -i video.mp4 -vn -c:a copy audio.aac
ffmpeg -i video.mp4 -vn -c:a libmp3lame -b:a 320k audio.mp3
```

### 添加字幕

```bash

# 将字幕烧录进视频
ffmpeg -i input.mp4 -vf "subtitles=subs.srt" -c:v h264_nvenc output.mp4

# 作为软字幕嵌入
ffmpeg -i input.mp4 -i subs.srt -c:v copy -c:a copy -c:s mov_text output.mp4
```

### 剪辑视频

```bash

# 从 00:01:00 开始，持续 30 秒
ffmpeg -ss 00:01:00 -i input.mp4 -t 30 -c:v h264_nvenc output.mp4

# 从开始到结束时间戳
ffmpeg -i input.mp4 -ss 00:00:30 -to 00:02:00 -c:v h264_nvenc output.mp4
```

### 合并视频

```bash

# 创建文件列表
echo "file 'video1.mp4'" > list.txt
echo "file 'video2.mp4'" >> list.txt
echo "file 'video3.mp4'" >> list.txt

# 合并
ffmpeg -f concat -safe 0 -i list.txt -c:v h264_nvenc output.mp4
```

### 创建 GIF

```bash
ffmpeg -i input.mp4 -vf "fps=10,scale=480:-1:flags=lanczos" output.gif
```

### 提取帧

```bash

# 每一帧
ffmpeg -i input.mp4 frames/frame_%04d.png

# 每 1 秒
ffmpeg -i input.mp4 -vf "fps=1" frames/frame_%04d.png
```

### 帧转视频

```bash
ffmpeg -framerate 30 -i frames/frame_%04d.png -c:v h264_nvenc output.mp4
```

## 流式传输

### RTMP 流

```bash
ffmpeg -re -i input.mp4 \
    -c:v h264_nvenc -preset p4 -b:v 4M \
    -c:a aac -b:a 128k \
    -f flv rtmp://server/live/stream
```

### HLS 输出

```bash
ffmpeg -i input.mp4 \
    -c:v h264_nvenc -preset p5 \
    -c:a aac \
    -f hls -hls_time 10 -hls_list_size 0 \
    output.m3u8
```

## 性能比较

### 编码速度（4K 视频）

| 编码器         | GPU/CPU  | 性能        |
| ----------- | -------- | --------- |
| libx264     | CPU（8 核） | \~30 fps  |
| h264\_nvenc | 速度       | \~300 帧/秒 |
| h264\_nvenc | 512x512  | \~450 帧/秒 |
| hevc\_nvenc | 速度       | \~200 帧/秒 |
| hevc\_nvenc | 512x512  | \~350 帧/秒 |

## 高级选项

### 两遍编码

```bash

# 第一遍
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p7 -b:v 10M -pass 1 -f null /dev/null

# 第二遍
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p7 -b:v 10M -pass 2 output.mp4
```

### B 帧与 GOP

```bash
ffmpeg -i input.mp4 \
    -c:v h264_nvenc \
    -bf 2 \           # B 帧
    -g 60 \           # GOP 大小
    -keyint_min 30 \  # 最小关键帧间隔
    output.mp4
```

### HDR 支持（HEVC）

```bash
ffmpeg -i hdr_input.mp4 \
    -c:v hevc_nvenc \
    -preset p5 \
    -profile:v main10 \
    -pix_fmt p010le \
    hdr_output.mp4
```

## 多 GPU

```bash

# 使用特定 GPU
ffmpeg -hwaccel cuda -hwaccel_device 0 -i input.mp4 -c:v h264_nvenc output.mp4

# 在不同 GPU 上并行编码
ffmpeg -hwaccel cuda -hwaccel_device 0 -i video1.mp4 -c:v h264_nvenc out1.mp4 &
ffmpeg -hwaccel cuda -hwaccel_device 1 -i video2.mp4 -c:v h264_nvenc out2.mp4 &
wait
```

## # 使用固定种子以获得一致结果

### 未找到 NVENC

```bash

# 检查 NVIDIA 驱动
nvidia-smi

# 检查 FFmpeg 构建
ffmpeg -encoders | grep nvenc
```

### 编码失败

```bash

# 降低并发会话数（NVENC 限制）

# 消费级 GPU：3-5 个会话

# 专业级 GPU：无限制
```

### 质量差

* 使用更高的 preset（p6、p7）
* 降低 CQ 值（18-20）
* 增加比特率

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* [AI 视频生成](https://docs.clore.ai/guides/guides_v2-zh/shi-pin-sheng-cheng/ai-video-generation)
* [RIFE 插帧](https://docs.clore.ai/guides/guides_v2-zh/shi-pin-chu-li/rife-interpolation)
* [Real-ESRGAN 放大](https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-chu-li/real-esrgan-upscaling)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/shi-pin-chu-li/ffmpeg-nvenc.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
