# FFmpeg NVENC

Codificación de vídeo acelerada por hardware con GPU NVIDIA.

{% hint style="success" %}
Todos los ejemplos se pueden ejecutar en servidores GPU alquilados a través de [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Alquilar en CLORE.AI

1. Visita [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrar por tipo de GPU, VRAM y precio
3. Elegir **Bajo demanda** (tarifa fija) o **Spot** (precio de puja)
4. Configura tu pedido:
   * Selecciona imagen Docker
   * Establece puertos (TCP para SSH, HTTP para interfaces web)
   * Agrega variables de entorno si es necesario
   * Introduce el comando de inicio
5. Selecciona pago: **CLORE**, **BTC**, o **USDT/USDC**
6. Crea el pedido y espera el despliegue

### Accede a tu servidor

* Encuentra los detalles de conexión en **Mis Pedidos**
* Interfaces web: Usa la URL del puerto HTTP
* SSH: `ssh -p <port> root@<proxy-address>`

## ¿Qué es NVENC?

NVENC (NVIDIA Video Encoder) proporciona:

* Codificación 5-10x más rápida que la CPU
* Soporte para H.264, H.265/HEVC, AV1
* Codificación 4K/8K en tiempo real
* Bajo uso de cómputo de GPU

## Requisitos

| Códec | GPU mínima | Recomendado |
| ----- | ---------- | ----------- |
| H.264 | GTX 600+   | RTX 3060+   |
| HEVC  | GTX 900+   | RTX 3070+   |
| AV1   | RTX 4000+  | RTX 4090    |

## Despliegue rápido

**Imagen Docker:**

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

**Puertos:**

```
22/tcp
```

**Comando:**

```bash
apt-get update && \
apt-get install -y ffmpeg && \
echo "FFmpeg con NVENC listo"
```

## Comprobar soporte NVENC

```bash

# Comprobar codificadores disponibles
ffmpeg -encoders | grep nvenc

# Debería mostrar:

# V....D h264_nvenc

# V....D hevc_nvenc

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

## Codificación básica

### Codificación H.264

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

### Codificación HEVC/H.265

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

### Codificación AV1 (RTX 4000+)

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

## Preajustes

| Preajuste | Calidad  | Velocidad     |
| --------- | -------- | ------------- |
| p1        | Más bajo | El más rápido |
| p2-p3     | Baja     | Rápido        |
| p4-p5     | Medio    | Equilibrado   |
| p6-p7     | Alto     | Lento         |

```bash

# Codificación más rápida
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p1 output.mp4

# Mejor calidad
ffmpeg -i input.mp4 -c:v h264_nvenc -preset p7 output.mp4
```

## Control de calidad

### Calidad constante (CQ)

```bash

# Menor = mejor calidad, archivo más grande
ffmpeg -i input.mp4 -c:v h264_nvenc -cq 18 output.mp4

# Valores recomendados: 18-28
```

### Tasa de bits constante (CBR)

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

### Tasa de bits variable (VBR)

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

## Resolución y escalado

### Redimensionar vídeo

```bash

# Escalar a 1080p
ffmpeg -i input.mp4 -vf "scale=1920:1080" -c:v h264_nvenc output.mp4

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

# Mantener relación de aspecto
ffmpeg -i input.mp4 -vf "scale=-1:1080" -c:v h264_nvenc output.mp4
```

### Escalado por GPU (más rápido)

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

## Decodificación + codificación por hardware

Pipeline completo de GPU:

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

## Conversión por lotes

### Script de 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 "Convertido: $filename"
    fi
done
```

### Lote en Python

```python
import subprocess
import os
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'
os.makedirs(output_dir, exist_ok=True)

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

# Procesar en paralelo (si hay múltiples GPUs o suficientes recursos)
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"Convertido: {f}")
```

## Tareas comunes

### Convertir a MP4 optimizado para web

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

### Extraer audio

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

### Añadir subtítulos

```bash

# Quemar subtítulos en el vídeo
ffmpeg -i input.mp4 -vf "subtitles=subs.srt" -c:v h264_nvenc output.mp4

# Insertar como subtítulos blandos
ffmpeg -i input.mp4 -i subs.srt -c:v copy -c:a copy -c:s mov_text output.mp4
```

### Recortar vídeo

```bash

# Desde 00:01:00 durante 30 segundos
ffmpeg -ss 00:01:00 -i input.mp4 -t 30 -c:v h264_nvenc output.mp4

# Desde la marca de inicio hasta la de fin
ffmpeg -i input.mp4 -ss 00:00:30 -to 00:02:00 -c:v h264_nvenc output.mp4
```

### Concatenar vídeos

```bash

# Crear lista de archivos
echo "file 'video1.mp4'" > list.txt
echo "file 'video2.mp4'" >> list.txt
echo "file 'video3.mp4'" >> list.txt

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

### Crear GIF

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

### Extraer cuadros

```bash

# Cada cuadro
ffmpeg -i input.mp4 frames/frame_%04d.png

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

### De cuadros a vídeo

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

## Streaming

### Flujo 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
```

### Salida 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
```

## Comparación de rendimiento

### Velocidad de codificación (vídeo 4K)

| Codificador | GPU/CPU         | Velocidad |
| ----------- | --------------- | --------- |
| libx264     | CPU (8 núcleos) | \~30 fps  |
| h264\_nvenc | RTX 3090        | \~300 fps |
| h264\_nvenc | RTX 4090        | \~450 fps |
| hevc\_nvenc | RTX 3090        | \~200 fps |
| hevc\_nvenc | RTX 4090        | \~350 fps |

## Opciones avanzadas

### Codificación en dos pasadas

```bash

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

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

### B-Frames y GOP

```bash
ffmpeg -i input.mp4 \
    -c:v h264_nvenc \
    -bf 2 \           # B-frames
    -g 60 \           # Tamaño GOP
    -keyint_min 30 \  # Intervalo mínimo de fotograma clave
    output.mp4
```

### Soporte HDR (HEVC)

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

## Multi-GPU

```bash

# Usar GPU específica
ffmpeg -hwaccel cuda -hwaccel_device 0 -i input.mp4 -c:v h264_nvenc output.mp4

# Codificación paralela en diferentes GPUs
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
```

## Solución de problemas

### NVENC no encontrado

```bash

# Comprobar controlador NVIDIA
nvidia-smi

# Comprobar compilación de FFmpeg
ffmpeg -encoders | grep nvenc
```

### Codificación fallida

```bash

# Reducir sesiones concurrentes (límite NVENC)

# GPUs de consumo: 3-5 sesiones

# GPUs profesionales: ilimitadas
```

### Calidad pobre

* Usar preset más alto (p6, p7)
* Valor CQ más bajo (18-20)
* Aumentar la tasa de bits

## Estimación de costos

Tarifas típicas del marketplace de CLORE.AI (a fecha de 2024):

| GPU       | Tarifa por hora | Tarifa diaria | Sesión de 4 horas |
| --------- | --------------- | ------------- | ----------------- |
| RTX 3060  | \~$0.03         | \~$0.70       | \~$0.12           |
| RTX 3090  | \~$0.06         | \~$1.50       | \~$0.25           |
| RTX 4090  | \~$0.10         | \~$2.30       | \~$0.40           |
| A100 40GB | \~$0.17         | \~$4.00       | \~$0.70           |
| A100 80GB | \~$0.25         | \~$6.00       | \~$1.00           |

*Los precios varían según el proveedor y la demanda. Consulta* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *para las tarifas actuales.*

**Ahorra dinero:**

* Usa **Spot** market para cargas de trabajo flexibles (a menudo 30-50% más barato)
* Paga con **CLORE** tokens
* Compara precios entre diferentes proveedores

## Próximos pasos

* [Generación de video AI](/guides/guides_v2-es/generacion-de-video/ai-video-generation.md)
* [Interpolación RIFE](/guides/guides_v2-es/procesamiento-de-video/rife-interpolation.md)
* [Escalado Real-ESRGAN](/guides/guides_v2-es/procesamiento-de-imagenes/real-esrgan-upscaling.md)


---

# 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-es/procesamiento-de-video/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.
