diff --git a/.augment-guidelines b/.augment-guidelines new file mode 100644 index 0000000000000..79e2b5b32f305 --- /dev/null +++ b/.augment-guidelines @@ -0,0 +1,62 @@ +# Augment Guidelines for FFmpeg Repository + +project: + name: "FFmpeg" + description: | + A complete, cross-platform solution to record, convert and stream audio and video. + type: "media" + +architecture: + overview: | + FFmpeg is organized into several core libraries that handle different aspects of + multimedia processing. The codebase follows a modular design where each library + can be used independently or together. FFmpeg also provides command-line tools + built on top of these libraries. + + key_directories: + - path: "libavcodec" + description: | + Implements encoders and decoders for audio/video codecs and bitstream processing + - path: "libavdevice" + description: | + Provides abstraction for accessing capture and playback devices + - path: "libavfilter" + description: | + Implements media filtering framework for processing audio and video + - path: "libavformat" + description: | + Handles container formats, muxing/demuxing, and I/O protocols + - path: "libavutil" + description: | + Contains utility functions, data structures, and common components shared across + libraries + - path: "libswresample" + description: | + Implements audio mixing and resampling routines + - path: "tests" + description: | + Contains test suites and validation tools for FFmpeg functionality + +components: + - name: "WHIP" + description: | + WebRTC-HTTP Ingestion Protocol implementation for low-latency streaming. Handles + SDP exchange, ICE connectivity, DTLS handshake, SRTP encryption, and RTP + packetization for WebRTC streaming. + related_files: + - path: "libavformat/whip.c" + description: | + Core implementation of the WHIP protocol, including SDP offer/answer exchange, + ICE connectivity, DTLS handshake setup, and SRTP encryption for RTP packets + - path: "libavformat/tls.h" + description: | + Header defining the DTLS interface used by WHIP for secure communication, + including functions for certificate handling and DTLS state management + - path: "libavformat/tls.c" + description: | + Common DTLS implementation shared across different SSL backends, providing + UDP socket setup for DTLS connections + - path: "libavformat/tls_openssl.c" + description: | + OpenSSL-specific implementation of DTLS functionality, including handshake + procedures and SRTP key material export diff --git a/.augmentignore b/.augmentignore new file mode 100644 index 0000000000000..0ec86037100e4 --- /dev/null +++ b/.augmentignore @@ -0,0 +1,25 @@ + +# Build artifacts +**/objs/** +**/build/** +**/*.o +**/*.a +**/*.so +**/*.dylib +**/*.d + +# IDE files +**/.idea/** +**/.vscode/** +**/.run/** + +# Generated files +**/.tmp/** +**/fate-suite/** +**/*.flv +**/*.mp4 +**/*.ts + +# Other files. +**/tools/** +**/tests/** diff --git a/.github/docker/Dockerfile b/.github/docker/Dockerfile new file mode 100644 index 0000000000000..78e8d928afe2f --- /dev/null +++ b/.github/docker/Dockerfile @@ -0,0 +1,24 @@ +# docker build -t ossrs/srs:ffmpeg-fate +# docker push ossrs/srs:ffmpeg-fate +FROM ubuntu:22.04 + +RUN apt-get update && \ + apt-get install -y build-essential git rsync make nasm pkg-config libssl-dev &&\ + rm -rf /var/lib/apt/lists/* + +WORKDIR /opt +RUN git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg + +WORKDIR /opt/ffmpeg +RUN ./configure --enable-openssl --enable-version3 +RUN make -j$(nproc) + +RUN make fate-rsync SAMPLES=/opt/ffmpeg/fate-suite +RUN du -sh /opt/ffmpeg/fate-suite + +# Note that you should use the fate-suite.tar, then extract it out of +# docker, to avoid resync all files. +RUN tar cf fate-suite.tar fate-suite +RUN du -sh /opt/ffmpeg/fate-suite.tar + +ENV FATE_SAMPLES=/opt/ffmpeg/fate-suite diff --git a/.github/scripts/format-patch.sh b/.github/scripts/format-patch.sh new file mode 100755 index 0000000000000..3b56e701a652e --- /dev/null +++ b/.github/scripts/format-patch.sh @@ -0,0 +1,189 @@ +#!/bin/bash + +LOGPREFIX=">>" + +if [[ $(jq --version 1>/dev/null 2>&1 && echo yes) != "yes" ]]; then + echo "${LOGPREFIX} Tool jq is not installed. Please install it to parse JSON data. For example:" + echo "${LOGPREFIX} apt install jq" + echo "${LOGPREFIX} brew install jq" + echo "${LOGPREFIX} yum install jq" + echo "${LOGPREFIX} See https://github.com/jqlang/jq" + exit 1 +fi + +PR_NUMBER="$1" +PATCH_FILE="$2" +TMP_BRANCH="$3" +if [ -z "$PR_NUMBER" ]; then + echo "${LOGPREFIX} Please provide a PR link or number. For example: https://github.com/ossrs/ffmpeg-webrtc/pull/20" + exit 1 +fi + +if [[ "$1" =~ ^https://github.com/ossrs/ffmpeg-webrtc/pull/([0-9]+)$ ]]; then + PR_NUMBER="${BASH_REMATCH[1]}" +elif [[ "$1" =~ ^[0-9]+$ ]]; then + PR_NUMBER="$1" +else + echo "${LOGPREFIX} Invalid input format. Please provide a PR link or number. For example: https://github.com/ossrs/ffmpeg-webrtc/pull/20" + exit 1 +fi + +PR_URL="https://github.com/ossrs/ffmpeg-webrtc/pull/$PR_NUMBER" +echo "${LOGPREFIX} Fetching PR #$PR_NUMBER from $PR_URL" + +PR_DATA=$(curl -s "https://api.github.com/repos/ossrs/ffmpeg-webrtc/pulls/$PR_NUMBER") +REPO_NAME=$(printf '%s' "$PR_DATA" | jq -r '.head.repo.full_name') +BRANCH_NAME=$(printf '%s' "$PR_DATA" | jq -r '.head.ref') +echo "${LOGPREFIX} Repository: $REPO_NAME, Branch: $BRANCH_NAME" +if [[ -z "$REPO_NAME" || -z "$BRANCH_NAME" ]]; then + echo "${LOGPREFIX} Error: REPO_NAME or BRANCH_NAME is empty!" + exit 1 +fi + +PR_TITLE=$(printf '%s' "$PR_DATA" | jq -r '.title') +PR_DESCRIPTION=$(printf '%s' "$PR_DATA" | jq -r '.body // ""') +echo "${LOGPREFIX} PR information:" +echo "${LOGPREFIX} ===================================================================" +echo "${LOGPREFIX} $PR_TITLE" +echo "${LOGPREFIX} $PR_DESCRIPTION" +echo "${LOGPREFIX} ===================================================================" +echo "${LOGPREFIX} " +if [[ -z "$PR_TITLE" ]]; then + echo "${LOGPREFIX} Error: PR title is empty!" + exit 1 +fi + +git checkout workflows && +echo "${LOGPREFIX} Switched to workflows branch." && +git pull && +echo "${LOGPREFIX} Pulled latest changes from workflows branch." +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to switch to workflows branch or pull latest changes." + exit 1 +fi + +REMOTE_NAME=patch-tmp && +if git remote | grep -q "^$REMOTE_NAME$"; then + git remote rm "$REMOTE_NAME" +fi && +git remote add $REMOTE_NAME https://github.com/${REPO_NAME}.git && +git fetch $REMOTE_NAME $BRANCH_NAME && +echo "${LOGPREFIX} Fetch remote $REMOTE_NAME at $(git remote get-url $REMOTE_NAME)" +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to fetch remote branch $BRANCH_NAME from $REMOTE_NAME." + exit 1 +fi + +if [[ -z "$TMP_BRANCH" ]]; then + TMP_BRANCH="tmp-branch-for-patch-$PR_NUMBER" +fi && +if git branch --list "$TMP_BRANCH" | grep -q "^..$TMP_BRANCH$"; then + git branch -D "$TMP_BRANCH" +fi && +git checkout -b $TMP_BRANCH $REMOTE_NAME/$BRANCH_NAME && +echo "${LOGPREFIX} Checkout branch $TMP_BRANCH from $REMOTE_NAME/$BRANCH_NAME" +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to checkout branch $TMP_BRANCH from $REMOTE_NAME/$BRANCH_NAME." + exit 1 +fi + +FIRST_AUTHOR_NAME=$(git log workflows..HEAD --reverse --format='%an' | head -n1) +FIRST_AUTHOR_EMAIL=$(git log workflows..HEAD --reverse --format='%ae' | head -n1) +echo "${LOGPREFIX} Author: $FIRST_AUTHOR_NAME <$FIRST_AUTHOR_EMAIL>" +if [[ -z "$FIRST_AUTHOR_NAME" || -z "$FIRST_AUTHOR_EMAIL" ]]; then + echo "${LOGPREFIX} Error: Unable to determine the first author of the PR." + exit 1 +fi + +COAUTHORS=$(git log workflows..HEAD --format='Co-authored-by: %an <%ae>' |grep -v "$FIRST_AUTHOR_NAME" | sort -u) +COAUTHOR_COUNT=$(echo "$COAUTHORS" | wc -l) +if [[ "$COAUTHOR_COUNT" -gt 0 ]]; then + echo "${LOGPREFIX} $COAUTHORS" +fi + +COMMIT_MSG="$PR_TITLE" +if [[ -n "$PR_DESCRIPTION" ]]; then + COMMIT_MSG="$COMMIT_MSG\n\n$PR_DESCRIPTION" +fi + +if [[ "$COAUTHOR_COUNT" -gt 0 ]]; then + COMMIT_MSG="$COMMIT_MSG\n" + COMMIT_MSG="$COMMIT_MSG\n$COAUTHORS" +fi + +echo "${LOGPREFIX} Commit information:" +echo "${LOGPREFIX} Author: $FIRST_AUTHOR_NAME <$FIRST_AUTHOR_EMAIL>" +echo "${LOGPREFIX} ===================================================================" +echo -e "$COMMIT_MSG" +echo "${LOGPREFIX} ===================================================================" +echo "${LOGPREFIX} " + +if [[ $(git config --list --local |grep 'user.name' >/dev/null 2>&1 && echo yes) != "yes" ]]; then + git config --local user.name "$FIRST_AUTHOR_NAME" +fi && +if [[ $(git config --list --local |grep 'user.email' >/dev/null 2>&1 && echo yes) != "yes" ]]; then + git config --local user.email "$FIRST_AUTHOR_EMAIL" +fi && +git config --list && +echo "${LOGPREFIX} Set local git user configuration to: $FIRST_AUTHOR_NAME <$FIRST_AUTHOR_EMAIL>" +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to set local git user configuration." + exit 1 +fi + +git rebase workflows && +git reset --soft workflows && +echo "${LOGPREFIX} Rebased onto workflows branch and reset to soft." +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to rebase or reset changes." + exit 1 +fi + +git status && +git restore --staged .github && +git restore .github && +git status && +echo "${LOGPREFIX} Restored .github directory to the state of workflows branch." +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to restore .github directory." + exit 1 +fi + +if [[ $(git status | grep 'nothing to commit, working tree clean' >/dev/null 2>&1 && echo yes) == "yes" ]]; then + echo "${LOGPREFIX} No changes to commit. Exiting." + git checkout workflows + exit 0 +fi + +git commit --author "$FIRST_AUTHOR_NAME <$FIRST_AUTHOR_EMAIL>" -m "$(echo -e "$COMMIT_MSG")" && +echo "${LOGPREFIX} Squashed commits into a single commit." +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to rebase or commit changes." + exit 1 +fi + +git branch -vv && +git log -1 --pretty=format:"%an <%ae> %h %s" +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to display branch information or last commit." + exit 1 +fi + +if [[ -z "$PATCH_FILE" ]]; then + PATCH_FILE="whip-patch-$PR_NUMBER-$(date +%s).patch" +fi && +rm -f $PATCH_FILE && +git format-patch --add-header "X-Unsent: 1" --to ffmpeg-devel@ffmpeg.org -1 --stdout > $PATCH_FILE && +echo "${LOGPREFIX} Created patch file: $PATCH_FILE" +if [[ $? -ne 0 ]]; then + echo "${LOGPREFIX} Failed to create patch file." + exit 1 +fi + +git checkout workflows +#git br -D $TMP_BRANCH +#echo "${LOGPREFIX} Removed temporary branch $TMP_BRANCH." + +echo "${LOGPREFIX} " +echo "${LOGPREFIX} Patch file created: $PATCH_FILE" +echo "${LOGPREFIX} " diff --git a/.github/workflows/fate-cache.yml b/.github/workflows/fate-cache.yml new file mode 100644 index 0000000000000..77ea32e3f3f4e --- /dev/null +++ b/.github/workflows/fate-cache.yml @@ -0,0 +1,27 @@ +name: "FFmpeg FATE Cache" + +on: + workflow_dispatch: + +permissions: read-all + +jobs: + build: + name: "Build FFmpeg Fate Cache" + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Login to docker hub + uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a # v2.1.0 + with: + username: "${{ secrets.DOCKER_USERNAME }}" + password: "${{ secrets.DOCKER_PASSWORD }}" + - name: Build FFmpeg Fate Cache + run: | + set -euxo pipefail + docker build -t ossrs/srs:ffmpeg-fate -f .github/docker/Dockerfile . + - name: Push FFmpeg Fate Cache + run: | + set -euxo pipefail + docker push ossrs/srs:ffmpeg-fate + runs-on: ubuntu-22.04 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000000000..1a8ced2650028 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,847 @@ +name: "Test" + +on: + push: + pull_request: + +permissions: read-all + +# Results for commonly used commands: +# $HOME is /home/runner +# $(pwd) is /home/runner/work/ffmpeg-webrtc/ffmpeg-webrtc +# $(nproc) is 4 +# $(whoami) is runner +# $(id -gn) is docker +# $(which docker) is /usr/bin/docker +# $(ifconfig eth0 | grep 'inet ' | awk '{print $2}') is private IP4 address like 10.1.0.76 +jobs: + build: + name: "Build FFmpeg" + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config libssl-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + runs-on: ubuntu-22.04 + + fate: + name: "FFmpeg Fate Test" + steps: + - name: Checkout repository + uses: actions/checkout@v4 + # The cache for FFmpeg FATE samples can help decrease the resync time when executing + # "make fate-resync." The cache is stored in the Docker image "ossrs/srs:ffmpeg-fate," + # which can be refreshed by manually executing the below workflow. + # https://github.com/ossrs/ffmpeg-webrtc/actions/workflows/fate-cache.yml + - name: Download Fate Cache Samples + run: | + set -euxo pipefail + + docker run --rm -v $(pwd):/target ossrs/srs:ffmpeg-fate \ + bash -c "cp /opt/ffmpeg/fate-suite.tar /target/" + tar xf fate-suite.tar + + ls -ldh fate-suite + du -sh fate-suite + - name: Configure FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config libssl-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --extra-cflags='-fsanitize=address -g -O0' --extra-cxxflags='-fsanitize=address -g -O0' --extra-ldflags='-fsanitize=address -g -O0' + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: FFmpeg Fate rsync + run: | + set -euxo pipefail + make fate-rsync SAMPLES=$(pwd)/fate-suite + - name: Stat Fate Suite + run: | + set -euxo pipefail + du -sh fate-suite + du -sh * + - name: Run FFmpeg Fate + run: | + set -euxo pipefail + make fate -j$(nproc) SAMPLES=$(pwd)/fate-suite + runs-on: ubuntu-22.04 + + srs: + name: "FFmpeg with SRS" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libssl-dev libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + pion: + name: "FFmpeg with Pion" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libssl-dev libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: '1.22' + - name: Verify Go version + run: go version + - name: Start Pion + run: | + set -euxo pipefail + git clone https://github.com/pion/webrtc.git + cd webrtc/examples/whip-whep + go run *.go & + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip -authorization "seanTest" "http://localhost:8080/whip" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + janus: + name: "FFmpeg with Janus" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libssl-dev libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start Janus + run: | + set -euxo pipefail + git clone https://github.com/winlinvip/janus-docker.git + (cd janus-docker && + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') && + sed -i "s|\(^[[:blank:]]*nat_1_1_mapping *=\).*|\1\"$ip\"|g" janus.jcfg && + docker run --rm -d -p 8081:8080 -p 8188:8188 -p 8443:8443 -p 20000-20010:20000-20010/udp \ + -v $(pwd)/janus.jcfg:/usr/local/etc/janus/janus.jcfg \ + -v $(pwd)/janus.plugin.videoroom.jcfg:/usr/local/etc/janus/janus.plugin.videoroom.jcfg \ + -v $(pwd)/janus.transport.http.jcfg:/usr/local/etc/janus/janus.transport.http.jcfg \ + -v $(pwd)/janus.transport.websockets.jcfg:/usr/local/etc/janus/janus.transport.websockets.jcfg \ + -v $(pwd)/videoroomtest.js:/usr/local/share/janus/demos/videoroomtest.js \ + ossrs/janus:v1.0.12) + + git clone https://github.com/meetecho/simple-whip-server.git + cd simple-whip-server + git checkout bd2d98898b9842bfc329443b46bcc906aab857aa + npm install + npm run build + npm run start & + + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + curl -H 'Content-Type: application/json' -d '{"id": "abc123", "room": 2345}' \ + http://localhost:7080/whip/create + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip 'http://localhost:7080/whip/endpoint/abc123' \ + 1>ffstdout.log 2>ffstderr.log & + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + - name: Setup tmate session + if: ${{ failure() }} + uses: mxschmitt/action-tmate@v3 + runs-on: ubuntu-22.04 + + asan: + name: "FFmpeg with Asan" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libssl-dev libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus \ + --extra-cflags='-fsanitize=address -g -O0' --extra-cxxflags='-fsanitize=address -g -O0' --extra-ldflags='-fsanitize=address -g -O0' + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + # TEST: Generate a coredump. + #pkill -SIGSEGV ffmpeg && sleep 3 && exit 0 + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check Asan Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'ERROR: AddressSanitizer' && + echo "AddressSanitizer error found in ffstderr.log" && exit 1 + echo "AddressSanitizer is ok" + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + openssl-1-0-1k: + name: "With OpenSSL 1.0.1k" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build OpenSSL 1.0.1k + run: | + set -euxo pipefail + curl -s -L https://www.openssl.org/source/openssl-1.0.1k.tar.gz | tar xz + cd openssl-1.0.1k + ./config --prefix=$HOME/.release/openssl && make -j1 + sudo make install_sw + - name: Download Test File + run: | + set -euxo pipefail + curl -s -L -O https://github.com/ossrs/ffmpeg-webrtc/releases/download/pre-release/bbb-4mbps-baseline-opus.mp4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + PKG_CONFIG_PATH="$HOME/.release/openssl/lib/pkgconfig" \ + ./configure --enable-muxer=whip --enable-openssl --enable-version3 + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -i bbb-4mbps-baseline-opus.mp4 -c copy \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + openssl-1-0-2: + name: "With OpenSSL 1.0.2" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build OpenSSL 1.0.2 + run: | + set -euxo pipefail + curl -s -L https://www.openssl.org/source/openssl-1.0.2.tar.gz | tar xz + cd openssl-1.0.2 + ./config --prefix=$HOME/.release/openssl + make -j1 && sudo make install_sw + - name: Download Test File + run: | + set -euxo pipefail + curl -s -L -O https://github.com/ossrs/ffmpeg-webrtc/releases/download/pre-release/bbb-4mbps-baseline-opus.mp4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + PKG_CONFIG_PATH="$HOME/.release/openssl/lib/pkgconfig" \ + ./configure --enable-muxer=whip --enable-openssl --enable-version3 + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -i bbb-4mbps-baseline-opus.mp4 -c copy \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + openssl-1-1-0h: + name: "With OpenSSL 1.1.0h" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build OpenSSL 1.1.0h + run: | + set -euxo pipefail + curl -s -L https://www.openssl.org/source/openssl-1.1.0h.tar.gz | tar xz + cd openssl-1.1.0h + ./config --prefix=$HOME/.release/openssl + make -j$(nproc) && sudo make install_sw + - name: Download Test File + run: | + set -euxo pipefail + curl -s -L -O https://github.com/ossrs/ffmpeg-webrtc/releases/download/pre-release/bbb-4mbps-baseline-opus.mp4 + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + PKG_CONFIG_PATH="$HOME/.release/openssl/lib/pkgconfig" \ + ./configure --enable-muxer=whip --enable-openssl --enable-version3 + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -i bbb-4mbps-baseline-opus.mp4 -c copy \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + openssl-3-0: + name: "With OpenSSL 3.0" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build OpenSSL 3.0 + run: | + set -euxo pipefail + curl -s -L https://www.openssl.org/source/openssl-3.0.0.tar.gz | tar xz + cd openssl-3.0.0 + ./config --prefix=$HOME/.release/openssl + make -j$(nproc) && sudo make install_sw + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + PKG_CONFIG_PATH="$HOME/.release/openssl/lib/pkgconfig" \ + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + openssl-latest: + name: "With OpenSSL latest" + needs: build + steps: + - name: Checkout repository + uses: actions/checkout@v4 + - name: Build OpenSSL latest + run: | + set -euxo pipefail + curl -s -L https://www.openssl.org/source/openssl-3.5.0.tar.gz | tar xz + cd openssl-3.5.0 + ./config --prefix=$HOME/.release/openssl + make -j$(nproc) && sudo make install_sw + - name: Build FFmpeg + run: | + set -euxo pipefail + + # Install dependencies + sudo apt-get update + sudo apt-get install -y nasm pkg-config jq libopus-dev libx264-dev + + # Build FFmpeg with WebRTC support + PKG_CONFIG_PATH="$HOME/.release/openssl/lib/pkgconfig" \ + ./configure --enable-muxer=whip --enable-openssl --enable-version3 \ + --enable-libx264 --enable-gpl --enable-libopus + make -j$(nproc) + ./ffmpeg -version && ./ffmpeg -muxers 2>/dev/null |grep whip + - name: Start SRS Docker container + run: | + set -euxo pipefail + ip=$(ifconfig eth0 | grep 'inet ' | awk '{print $2}') + docker run --rm -d -p 1935:1935 -p 1985:1985 -p 8080:8080 \ + --env CANDIDATE=$ip -p 8000:8000/udp \ + ossrs/srs:5 ./objs/srs -c conf/rtc2rtmp.conf + - name: Streaming with FFmpeg + run: | + set -euxo pipefail + nohup ./ffmpeg -t 30 -re -f lavfi -i testsrc=size=1280x720 -f lavfi -i sine=frequency=440 -pix_fmt yuv420p \ + -vcodec libx264 -profile:v baseline -r 25 -g 50 -acodec libopus -ar 48000 -ac 2 \ + -f whip "http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream" \ + 1>ffstdout.log 2>ffstderr.log & + - name: Check SRS Streaming + id: streaming + run: | + set -euxo pipefail + + # Check streams in SRS. + for ((i=0; i<10; i++)); do + STREAM=$(curl -s http://localhost:1985/api/v1/streams/ | jq -r '.streams[].name') + if [[ "$STREAM" == "livestream" ]]; then + echo 'Test OK'; + echo "has_stream=true" >> $GITHUB_OUTPUT + break; + fi + sleep 3 + done + + if [[ "$STREAM" != "livestream" ]]; then + echo "Stream not found: $STREAM" + echo "has_stream=false" >> $GITHUB_OUTPUT + fi + - name: Stop FFmpeg normally + run: | + pkill -SIGINT ffmpeg && sleep 3 || + echo "FFmpeg process not found or already stopped." + - name: Show FFmpeg Stdout Log + run: cat ffstdout.log + - name: Show FFmpeg Stderr Log + run: cat ffstderr.log + - name: Check FFmpeg Exit Log + run: | + set -euxo pipefail + cat ffstderr.log |grep 'Exiting normally' && exit 0 + echo "Exiting normally not found in ffstderr.log" && exit 1 + - name: Check Stream Existence + if: ${{ steps.streaming.outputs.has_stream == 'false' }} + run: exit 1 + runs-on: ubuntu-22.04 + + generate-patch: + name: "Generate Patch" + if: ${{ github.event_name == 'pull_request' }} + steps: + # Checkout to workflows branch, make sure the base branch is available. + - name: Checkout repository with workflows branch + uses: actions/checkout@v4 + with: + ref: workflows + fetch-depth: 0 + - name: Try to checkout to workflows branch + run: | + set -euxo pipefail + git checkout workflows + git branch -vv + # Checkout to PR commit, use the lastest script. + - name: Checkout repository to PR commit + uses: actions/checkout@v4 + - name: Show Git Info + run: | + set -euxo pipefail + git branch -vv + echo "Repository: ${{ github.repository }}" + echo "Ref: ${{ github.ref }}" + echo "Event Name: ${{ github.event_name }}" + echo "Pull Request Number: ${{ github.event.pull_request.number }}" + - name: Install Dependencies + run: | + set -euxo pipefail + sudo apt-get update + sudo apt-get install -y jq + - name: Run Script + id: format_patch + run: | + set -euxo pipefail + + PR_NUMBER=${{ github.event.pull_request.number }} + PATCH_FILENAME="whip-patch-$PR_NUMBER-$(date +%s)" + TMP_BRANCH="tmp-branch-for-patch-$PR_NUMBER" + echo "PR ID is ${{ github.event.pull_request.number }}" + echo "Patch file is $PATCH_FILENAME.patch" + echo "Temporary branch is $TMP_BRANCH" + + bash .github/scripts/format-patch.sh $PR_NUMBER "$PATCH_FILENAME.patch" + echo "patch_file=$PATCH_FILENAME" >> $GITHUB_OUTPUT + echo "temporary_branch=$TMP_BRANCH" >> $GITHUB_OUTPUT + + if [[ -f "$PATCH_FILENAME.patch" ]]; then + echo "has_patch=true" >> $GITHUB_OUTPUT + else + echo "has_patch=false" >> $GITHUB_OUTPUT + fi + - name: Show Branch Info + if: ${{ steps.format_patch.outputs.has_patch == 'true' }} + run: git show ${{ steps.format_patch.outputs.temporary_branch }} + - name: Show Patch File + if: ${{ steps.format_patch.outputs.has_patch == 'true' }} + run: cat ${{ steps.format_patch.outputs.patch_file }}.patch + - name: Upload all patch files + if: ${{ steps.format_patch.outputs.has_patch == 'true' }} + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.format_patch.outputs.patch_file }} + path: | + whip-*.patch + retention-days: 90 + runs-on: ubuntu-22.04 + + test-done: + needs: + - fate + - srs + - pion + - janus + - asan + - openssl-1-0-1k + - openssl-1-0-2 + - openssl-1-1-0h + - openssl-3-0 + - openssl-latest + - generate-patch + steps: + - run: echo 'All done' + runs-on: ubuntu-22.04 + diff --git a/.gitignore b/.gitignore index 59c89da5e03b5..9e56f800f8c67 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,7 @@ *.ptx *.ptx.c *.ptx.gz +*.patch *_g \#* .\#* @@ -45,3 +46,4 @@ /libavcodec/vulkan/*.c /libavfilter/vulkan/*.c /.*/ +/fate-suite diff --git a/libavformat/whip.c b/libavformat/whip.c index 5fdbd6949d541..1fcbbf98b300d 100644 --- a/libavformat/whip.c +++ b/libavformat/whip.c @@ -114,6 +114,7 @@ /* Referring to Chrome's definition of RTP payload types. */ #define WHIP_RTP_PAYLOAD_TYPE_H264 106 #define WHIP_RTP_PAYLOAD_TYPE_OPUS 111 +#define WHIP_RTP_PAYLOAD_TYPE_RTX 105 /** * The STUN message header, which is 20 bytes long, comprises the @@ -150,6 +151,11 @@ #define WHIP_SDP_SESSION_ID "4489045141692799359" #define WHIP_SDP_CREATOR_IP "127.0.0.1" +/** + * Retransmission / NACK support +*/ +#define HISTORY_SIZE_DEFAULT 512 + /* Calculate the elapsed time from starttime to endtime in milliseconds. */ #define ELAPSED(starttime, endtime) ((int)(endtime - starttime) / 1000) @@ -193,6 +199,15 @@ enum WHIPState { WHIP_STATE_FAILED, }; +typedef struct RtpHistoryItem { + /* original RTP seq */ + uint16_t seq; + /* length in bytes */ + int size; + /* malloc-ed copy */ + uint8_t* pkt; +} RtpHistoryItem; + typedef struct WHIPContext { AVClass *av_class; @@ -279,6 +294,7 @@ typedef struct WHIPContext { /* The SRTP send context, to encrypt outgoing packets. */ SRTPContext srtp_audio_send; SRTPContext srtp_video_send; + SRTPContext srtp_video_rtx_send; SRTPContext srtp_rtcp_send; /* The SRTP receive context, to decrypt incoming packets. */ SRTPContext srtp_recv; @@ -303,6 +319,15 @@ typedef struct WHIPContext { /* The certificate and private key used for DTLS handshake. */ char* cert_file; char* key_file; + + /* RTX / NACK */ + uint8_t rtx_payload_type; + uint32_t video_rtx_ssrc; + uint16_t rtx_seq; + int history_size; + RtpHistoryItem * history; /* ring buffer */ + int hist_head; + int enable_nack_rtx; /* TODO: using whip_flags */ } WHIPContext; /** @@ -615,6 +640,17 @@ static int generate_sdp_offer(AVFormatContext *s) whip->audio_payload_type = WHIP_RTP_PAYLOAD_TYPE_OPUS; whip->video_payload_type = WHIP_RTP_PAYLOAD_TYPE_H264; + /* RTX / NACK init */ + whip->rtx_payload_type = WHIP_RTP_PAYLOAD_TYPE_RTX; + whip->video_rtx_ssrc = av_lfg_get(&whip->rnd); + whip->rtx_seq = 0; + whip->hist_head = 0; + whip->history_size = FFMAX(64, whip->history_size); + whip->history = av_calloc(whip->history_size, sizeof(*whip->history)); + if (!whip->history) + return AVERROR(ENOMEM); + whip->enable_nack_rtx = 1; + av_bprintf(&bp, "" "v=0\r\n" "o=FFmpeg %s 2 IN IP4 %s\r\n" @@ -666,7 +702,7 @@ static int generate_sdp_offer(AVFormatContext *s) } av_bprintf(&bp, "" - "m=video 9 UDP/TLS/RTP/SAVPF %u\r\n" + "m=video 9 UDP/TLS/RTP/SAVPF %u %u\r\n" "c=IN IP4 0.0.0.0\r\n" "a=ice-ufrag:%s\r\n" "a=ice-pwd:%s\r\n" @@ -679,9 +715,16 @@ static int generate_sdp_offer(AVFormatContext *s) "a=rtcp-rsize\r\n" "a=rtpmap:%u %s/90000\r\n" "a=fmtp:%u level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=%02x%02x%02x\r\n" + "a=rtcp-fb:%u nack\r\n" + "a=rtpmap:%u rtx/90000\r\n" + "a=fmtp:%u apt=%u\r\n" + "a=ssrc-group:FID %u %u\r\n" + "a=ssrc:%u cname:FFmpeg\r\n" + "a=ssrc:%u msid:FFmpeg video\r\n" "a=ssrc:%u cname:FFmpeg\r\n" "a=ssrc:%u msid:FFmpeg video\r\n", whip->video_payload_type, + whip->rtx_payload_type, whip->ice_ufrag_local, whip->ice_pwd_local, whip->dtls_fingerprint, @@ -691,8 +734,16 @@ static int generate_sdp_offer(AVFormatContext *s) profile, profile_iop, level, + whip->video_payload_type, + whip->rtx_payload_type, + whip->rtx_payload_type, + whip->video_payload_type, + whip->video_ssrc, + whip->video_rtx_ssrc, + whip->video_ssrc, whip->video_ssrc, - whip->video_ssrc); + whip->video_rtx_ssrc, + whip->video_rtx_ssrc); } if (!av_bprint_is_complete(&bp)) { @@ -1400,6 +1451,12 @@ static int setup_srtp(AVFormatContext *s) goto end; } + ret = ff_srtp_set_crypto(&whip->srtp_video_rtx_send, suite, buf); + if (ret < 0) { + av_log(whip, AV_LOG_ERROR, "WHIP: Failed to set crypto for video rtx send\n"); + goto end; + } + ret = ff_srtp_set_crypto(&whip->srtp_rtcp_send, suite, buf); if (ret < 0) { av_log(whip, AV_LOG_ERROR, "Failed to set crypto for rtcp send\n"); @@ -1429,6 +1486,37 @@ static int setup_srtp(AVFormatContext *s) return ret; } + +/** + * RTX history helpers + */ + static void rtp_history_store(WHIPContext *whip, const uint8_t *pkt, int size) +{ + int pos = whip->hist_head % whip->history_size; + RtpHistoryItem * it = &whip->history[pos]; + /* free older entry */ + av_free(it->pkt); + it->pkt = av_malloc(size); + if (!it->pkt) + return; + + memcpy(it->pkt, pkt, size); + it->size = size; + it->seq = AV_RB16(pkt + 2); + + whip->hist_head = ++pos; +} + +static const RtpHistoryItem* rtp_history_find(const WHIPContext *whip, uint16_t seq) +{ + for (int i = 0; i < whip->history_size; i++) { + const RtpHistoryItem * it = &whip->history[i]; + if (it->pkt && it->seq == seq) + return it; + } + return NULL; +} + /** * Callback triggered by the RTP muxer when it creates and sends out an RTP packet. * @@ -1465,6 +1553,10 @@ static int on_rtp_write_packet(void *opaque, const uint8_t *buf, int buf_size) return 0; } + /* Store only ORIGINAL video packets (non-RTX, non-RTCP) */ + if (!is_rtcp && is_video) + rtp_history_store(whip, buf, buf_size); + ret = ffurl_write(whip->udp, whip->buf, cipher_size); if (ret < 0) { av_log(whip, AV_LOG_ERROR, "WHIP: Failed to write packet=%dB, ret=%d\n", cipher_size, ret); @@ -1473,6 +1565,46 @@ static int on_rtp_write_packet(void *opaque, const uint8_t *buf, int buf_size) return ret; } +/** + * See https://datatracker.ietf.org/doc/html/rfc4588 + * Build and send a single RTX packet + */ +static int send_rtx_packet(AVFormatContext *s, const uint8_t * orig_pkt, int orig_size) +{ + WHIPContext * whip = s->priv_data; + int new_size, cipher_size; + /* skip if no RTX PT configured */ + if (!whip->enable_nack_rtx) + return 0; + + /* allocate new buffer: header + 2 + payload */ + if (orig_size + 2 > sizeof(whip->buf)) + return 0; + + memcpy(whip->buf, orig_pkt, orig_size); + + uint8_t * hdr = whip->buf; + uint16_t orig_seq = AV_RB16(hdr + 2); + + /* rewrite header */ + hdr[1] = (hdr[1] & 0x80) | whip->rtx_payload_type; /* keep M bit */ + AV_WB16(hdr + 2, whip->rtx_seq++); + AV_WB32(hdr + 8, whip->video_rtx_ssrc); + + /* shift payload 2 bytes */ + memmove(hdr + 12 + 2, hdr + 12, orig_size - 12); + AV_WB16(hdr + 12, orig_seq); + + new_size = orig_size + 2; + + /* Encrypt by SRTP and send out. */ + cipher_size = ff_srtp_encrypt(&whip->srtp_video_rtx_send, whip->buf, new_size, whip->buf, sizeof(whip->buf)); + if (cipher_size <= 0 || cipher_size < new_size) { + av_log(whip, AV_LOG_WARNING, "WHIP: Failed to encrypt packet=%dB, cipher=%dB\n", new_size, cipher_size); + return 0; + } + return ffurl_write(whip->udp, whip->buf, cipher_size); +} /** * Creates dedicated RTP muxers for each stream in the AVFormatContext to build RTP @@ -1795,6 +1927,64 @@ static int whip_write_packet(AVFormatContext *s, AVPacket *pkt) goto end; } } + /** + * Handle RTCP NACK + * Refer to RFC 4585, Section 6.2.1 + * The Generic NACK message is identified by PT=RTPFB and FMT=1. + * TODO: disable retransmisstion when "-tune zerolatency" + */ + if (media_is_rtcp(whip->buf, ret)) { + int ptr = 0; + uint8_t pt = whip->buf[ptr + 1]; + uint8_t fmt = (whip->buf[ptr] & 0x1f); + if (ptr + 4 <= ret && pt == 205 && fmt == 1 ) { + /** + * Refer to RFC 3550, Section 6.4.1. + * The length of this RTCP packet in 32-bit words minus one, + * including the header and any padding. + */ + int rtcp_len = (AV_RB16(&whip->buf[ptr + 2]) + 1) * 4; + /* SRTCP index(4 bytes) + HMAC (SRTP_AES128_CM_SHA1_80 10bytes) */ + int srtcp_len = rtcp_len + 4 + 10; + if (srtcp_len == ret && rtcp_len >= 12) { + int i = 0; + uint8_t *pkt = av_malloc(srtcp_len); + memcpy(pkt, whip->buf, srtcp_len); + int ret = ff_srtp_decrypt(&whip->srtp_recv, pkt, &srtcp_len); + if (ret < 0) + av_log(whip, AV_LOG_ERROR, "WHIP: SRTCP decrypt failed: %d\n", ret); + while (12 + i < rtcp_len && ret == 0) { + /** + * See https://datatracker.ietf.org/doc/html/rfc4585#section-6.1 + * Handle multi NACKs in bundled packet. + */ + uint16_t pid = AV_RB16(&pkt[ptr + 12 + i]); + uint16_t blp = AV_RB16(&pkt[ptr + 14 + i]); + + /* retransmit pid + any bit set in blp */ + for (int bit = -1; bit < 16; bit++) { + uint16_t seq = (bit < 0) ? pid : pid + bit + 1; + if (bit >= 0 && !(blp & (1 << bit))) + continue; + + const RtpHistoryItem * it = rtp_history_find(whip, seq); + if (it) { + ret = send_rtx_packet(s, it->pkt, it->size); + av_log(whip, AV_LOG_VERBOSE, + "WHIP: NACK, packet found: size: %d, seq=%d, rtx size=%d, lateset stored packet seq:%d\n", + it->size, seq, ret, whip->history[whip->hist_head-1].seq); + } else { + av_log(whip, AV_LOG_VERBOSE, + "WHIP: NACK, packet not found, seq=%d, latest stored packet seq: %d, latest rtx seq: %d\n", + seq, whip->history[whip->hist_head-1].seq, whip->rtx_seq); + } + } + i = i + 4; + } + av_free(pkt); + } + } + } } else if (ret != AVERROR(EAGAIN)) { av_log(whip, AV_LOG_ERROR, "WHIP: Failed to read from UDP socket\n"); goto end; @@ -1898,6 +2088,7 @@ static const AVOption options[] = { { "authorization", "The optional Bearer token for WHIP Authorization", OFFSET(authorization), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, ENC }, { "cert_file", "The optional certificate file path for DTLS", OFFSET(cert_file), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, ENC }, { "key_file", "The optional private key file path for DTLS", OFFSET(key_file), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, ENC }, + { "rtx_history", "Packet history size", OFFSET(history_size), AV_OPT_TYPE_INT, { .i64 = HISTORY_SIZE_DEFAULT }, 64, 2048, ENC }, { NULL }, };