#!/bin/sh

# build_ffmpeg_deb_nvidia.sh
# 2023-06-14
# by Gernot Walzl

# This shell script builds deb packages of ffmpeg with enabled
# NVIDIA hardware acceleration for video encoding.

# https://trac.ffmpeg.org/wiki/HWAccelIntro
# https://developer.nvidia.com/blog/nvidia-ffmpeg-transcoding-guide/
# https://docs.nvidia.com/video-technologies/video-codec-sdk/ffmpeg-with-nvidia-gpu/index.html

set -e  # exit on error

# nv-codec-headers (/usr/include/ffnvcodec) are required to be installed.
# This is a build dependency.
# https://packages.debian.org/source/nv-codec-headers
sudo apt-get install libffmpeg-nvenc-dev

# The NVENC video encoding library is required to be installed.
# This is a runtime dependency.
sudo apt-get install libnvidia-encode1

# nvidia-cuda-toolkit is required for --enable-cuda-nvcc
sudo apt-get install nvidia-cuda-toolkit

# libfdk-aac-dev is required for --enable-libfdk-aac
sudo apt-get install libfdk-aac-dev

# Install all build dependencies for the default configuration:
sudo apt-get build-dep ffmpeg

# Get the source of the ffmpeg deb package:
apt-get source ffmpeg
cd ffmpeg-*

# The following command shows all NVIDIA related configure options:
# ./configure --help | grep -i nv

# The file ./configure contains:
#     nvccflags_default="-gencode arch=compute_30,code=sm_30 -O2"
# Support for old GPU architectures has been removed in recent CUDA compilers.
# The following CUDA compiler flags generate code for recent GPU architectures:
#     --nvccflags="-gencode arch=compute_60,code=sm_60"

patch -p0 <<'EOF'
--- debian/rules.orig
+++ debian/rules
@@ -78,5 +78,15 @@
 	--enable-openal \
 	--enable-opencl \
 	--enable-opengl \
-	--enable-sdl2
+	--enable-sdl2 \
+	--enable-nonfree \
+	--enable-libfdk-aac \
+	--enable-cuda-nvcc \
+	--enable-cuvid \
+	--enable-ffnvcodec \
+	--enable-libnpp \
+	--enable-nvdec \
+	--enable-nvenc \
+	--enable-vdpau \
+	--nvccflags="-gencode arch=compute_60,code=sm_60"

EOF
dpkg-buildpackage --no-sign

# To use ffmpeg, you probably do not need the following packages:
# *-dbgsym_*
# *-dev_*
# *-extra*

# To show a list of supported decoders and encoders:
# ffmpeg -hide_banner -codecs | grep -i nv

# To see a list of encoding options:
# ffmpeg -hide_banner -h encoder=hevc_nvenc

# To encode a video using hardware acceleration:
# ffmpeg -hwaccel cuda -hwaccel_output_format cuda -i input.mp4 -c:v hevc_nvenc -preset hq output.mp4