Git Product home page Git Product logo

raspberrypi_webrtc's Introduction

RaspberryPi_WebRTC

Using v4l2 dma hardware encoder with WebRTC reduces CPU usage. Both signalr and mqtt are the options for signaling in this project.

Architecture

architecture

Environment

  • RaspberryPi 3B + Raspberry Pi Camera v1.3
  • RaspberryPi OS 64bit
  • clang 12+
  • boringssl replace openssl

Summary

  • Latency is about 0.2 seconds delay.
  • Temperatures up to 60~65°C.
  • Using HW DMA sources minimizes CPU usage and latency down to ~50ms.

latency latency


How to use

Preparation

  1. Follow SETUP_ARM64_ENV to prepare an arm64 env for compilation (Optional)
  2. Follow BUILD_WEBRTC to compile libwebrtc.a
  3. Choose a signaling mechanisum
  4. Install the needed packages on pi
    sudo apt install libboost-program-options-dev libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libpulse-dev libasound2-dev libx11-dev
  5. Copy the nlohmann/json.hpp to /usr/local/include
  6. Run signaling server

Compile and run

Command line
Description Valid values
-DUSE_SIGNALR_SIGNALING Build the project by using SignalR as signaling. ON, OFF
-DUSE_MQTT_SIGNALING Build the project by using MOSQUITTO as signaling. ON, OFF
-DBUILD_TEST Build the test codes recorder, mqtt, v4l2_capture, v4l2_encoder, v4l2_decoder, v4l2_scaler
-DUSE_BUILT_IN_H264 Use the built-in openh264 software encoder ON, OFF

Build on raspberry pi and it'll output a pi_webrtc file in /build.

mkdir build
cd build
cmake .. -DCMAKE_CXX_COMPILER=/usr/bin/clang++ -DUSE_MQTT_SIGNALING=ON
make -j

Run pi_webrtc to start the service.

  • If use signalr as signaling.
    ./pi_webrtc --device=/dev/video0 --fps=30 --width=1280 --height=720 --v4l2_format=mjpeg --signaling_url=http://localhost:6080/SignalingServer --enable_v4l2_dma
  • If use mosquitto mqtt as signaling.
    ./pi_webrtc --device=/dev/video0 --fps=30 --width=1280 --height=720 --v4l2_format=mjpeg --mqtt_host=127.0.0.1 --mqtt_port=1883 --mqtt_username=<username> --mqtt_password=<password>  --enable_v4l2_dma
  • ./pi_webrtc -h to list all available args.
  • If --enable_v4l2_dma is assigned, only H264 stream is provided. The VP8, VP9 are available as well if not be assigned. But frames will be decoded/scaled by software, and the buffer will be copied to the HW encoder though.
  • If the --record_path is assigned, the background recorder will start immediately after running the program. But the performance of Pi 3B is limited, if the resolution is above 640x368@15fps the HW encoder will be unstable, stuck, or even crash.

Run as Linux Service

Set pi_webrtc to run as a daemon.

  • Create /etc/systemd/system/webrtc.service, config sample:
    [Unit]
    Description= the webrtc service need signaling server first
    After=systemd-networkd.service farmer-api.service
    
    [Service]
    Type=simple
    WorkingDirectory=/home/pi/IoT/RaspberryPi_WebRTC/build
    ExecStartPre=/bin/sleep 60
    ExecStart=/home/pi/IoT/RaspberryPi_WebRTC/build/pi_webrtc --fps=30 --width=1280 --height=720 --v4l2_format=h264 --enable_v4l2_dma --mqtt_username=hakunamatata --mqtt_password=wonderful --record_path=/home/pi/video/
    Restart=always
    RestartSec=20
      
    [Install]
    WantedBy=multi-user.target
  • Enable and run the service
    sudo systemctl enable webrtc.service
    sudo systemctl start webrtc.service

Install the coturn (Optional)

If the cellular network is used, the coturn is required because the 5G NAT setting by ISP may block p2p.

  1. Install
    sudo apt update
    sudo apt install coturn
    sudo systemctl stop coturn.service
  2. Edit config sudo nano /etc/turnserver.conf, uncomment or modify below options
    listening-port=3478
    listening-ip=192.168.x.x
    relay-ip=192.168.x.x
    external-ip=174.127.x.x/192.168.x.x
    #verbose
    lt-cred-mech
    user=webrtc:webrtc
    realm=greenhouse
    no-tls
    no-dtls
    syslog
    no-cli
  3. Set the port 3478 forwarding on the router
  4. Start the service, sudo systemctl start coturn.service

Reference

raspberrypi_webrtc's People

Contributors

tzuhuantai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

wusopp eliabruni

raspberrypi_webrtc's Issues

fix: the minimun and step of encoder bitrate are 25000

the setting bitrate should be a step of 25000

Codec Controls

             video_bitrate_mode 0x009909ce (menu)   : min=0 max=1 default=0 value=0 flags=update
                                0: Variable Bitrate
                                1: Constant Bitrate
                  video_bitrate 0x009909cf (int)    : min=25000 max=25000000 step=25000 default=10000000 value=10000000
           sequence_header_mode 0x009909d8 (menu)   : min=0 max=1 default=1 value=1
                                0: Separate Buffer
                                1: Joined With 1st Frame
         repeat_sequence_header 0x009909e2 (bool)   : default=0 value=0
                force_key_frame 0x009909e5 (button) : flags=write-only, execute-on-write
          h264_minimum_qp_value 0x00990a61 (int)    : min=0 max=51 step=1 default=20 value=20
          h264_maximum_qp_value 0x00990a62 (int)    : min=0 max=51 step=1 default=51 value=51
            h264_i_frame_period 0x00990a66 (int)    : min=0 max=2147483647 step=1 default=60 value=60
                     h264_level 0x00990a67 (menu)   : min=0 max=15 default=11 value=11
                                0: 1
                                1: 1b
                                2: 1.1
                                3: 1.2
                                4: 1.3
                                5: 2
                                6: 2.1
                                7: 2.2
                                8: 3
                                9: 3.1
                                10: 3.2
                                11: 4
                                12: 4.1
                                13: 4.2
                                14: 5
                                15: 5.1
                   h264_profile 0x00990a6b (menu)   : min=0 max=4 default=4 value=4
                                0: Baseline
                                1: Constrained Baseline
                                2: Main
                                4: High

feat: record into mp4 files

  1. from ioctl frame buffer data
  2. save segment video files

by the way, is it possible to encode the raw frame as h264 into the queue and then share encoded frames to webrtc/ffmpeg?

fix: record momery leak

Write the video file in another thread, not call async every time.
If webrtc dropped frames will come across a memory leak, maybe creating a new thread and using an queue buffer is a better way.

Synchronized Video Streaming with Raspberry PI Zero 2 W

Hello,

Great project! I would like to use this library for a specific use case, but I am not sure if it would be suitable so I'll ask here.

The use case involves using two Raspberry PI Zero 2 W devices to stream video feeds in parallel to a Linux terminal. The critical requirement is to align each video frame from one stream with the corresponding frame from the other stream, based on their timestamps.

To achieve this, the following functionalities are necessary:

Each video frame must be accompanied by a unique timestamp when sent from the Raspberry PIs.
The receiving terminal should be capable of processing the streams by fetching frames individually, retrieving their timestamps, and synchronizing them with the frames from the alternate stream.
Could you please advise whether your library supports these features, or if there is a possibility to implement such a synchronization mechanism using your library?

Thanks in advance!

typo in `Install boringssl`

sudo apt-get install libunwind-dev zip unzip tar
git clone https://github.com/google/boringssl.git
cd boringssl
mkdir build
cd build
cmake -GNinja .. -DBUILD_SHARED_LIBS=1
ninja
sudo ninja install
sudo cp -r ../install/include/* /usr/local/include/
sudo cp ../install/lib/*.a /usr/local/lib/
sudo cp ../install/lib/*.so /usr/local/lib/
cmake -GNinja .. -DBUILD_SHARED_LIBS=1

should be instead

cmake -GNinja .. 

otherwise the .a files dont get generated

perf: send encoded h264 packet to webrtc

Capturing the h264 packets directly from the camera module, written into mp4 can reduce by 80% space compared to mjpeg.

Use webrtc::VideoEncoderFactory to produce some custom "encoder"
The encoder subclass passes encoded frames (e.g. H264) to the webrtc::EncodedImage::OnEncodedImage callback.
The encoder doesn't really have to encode anything, it just delivers pre-encoded frames.

Looking for the right QEMU env for compiling the project

Since the compilation of all libraries is quite heavy, let's try to find the right QEMU setting to compile them all on an x86_64 machine. These are my cross compilation instructions that so far managed to compile libwebrtc.a. However, I encountered issues when trying to compile microsoft-signalr.so at the casablanca step (see also here).

Let me first give the specs of the system I used

# Operating System and Version:
lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.5 LTS
Release:	20.04
Codename:	focal

# kernel
uname -r
5.15.0-88-generic

# architecture
uname -m
x86_64
  1. ARM64 Root Filesystem Setup:
# Install the ARM64 cross-compilation toolchain and other necessary packages
sudo apt-get update
sudo apt-get install gcc-aarch64-linux-gnu g++-aarch64-linux-gnu binutils-aarch64-linux-gnu qemu-user-static debootstrap
sudo debootstrap --arch arm64 --foreign bullseye rootfs
sudo cp /usr/bin/qemu-aarch64-static rootfs/usr/bin/
  1. Chroot Environment Setup:
sudo mount -o bind /dev rootfs/dev
sudo mount -t devpts -o gid=5,mode=620 devpts rootfs/dev/pts
sudo chroot rootfs /bin/bash
mount -t proc /proc /proc
  1. Debootstrap Initialization:
/debootstrap/debootstrap --second-stage
  1. Basic Package Installation:
apt-get update
apt-get install -y git lsb-release sudo curl
  1. User Environment Setup:
useradd -m pi
echo "pi ALL=(ALL) NOPASSWD:ALL" | tee -a /etc/sudoers
su - pi
bash
  1. Additional Dependencies Installation:
sudo apt-get update
sudo apt-get install -y g++ libasound2-dev libpulse-dev libudev-dev libexpat1-dev libnss3-dev libgtk-3-dev python pulseaudio libpulse-dev build-essential libncurses5 libx11-dev
sudo apt remove -y libssl-dev
pulseaudio --start
  1. Depot Tools Setup:
cd /home/pi
git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git
echo "export PATH=$(pwd)/depot_tools:\$PATH" >> ~/.bashrc
source ~/.bashrc
  1. Sysroot Dependencies for ARM64:
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu binutils-aarch64-linux-gnu
  1. WebRTC Source Fetching:
mkdir -p ~/webrtc && cd ~/webrtc
fetch --nohooks webrtc
src/build/linux/sysroot_scripts/install-sysroot.py --arch=arm64
gclient sync -D
cd src
git checkout -b local-5790 branch-heads/5790
git gc --aggressive
gclient sync -D --force --reset --with_branch_heads --no-history
  1. Clang Setup:
cd /home/pi
curl -OL https://github.com/llvm/llvm-project/releases/download/llvmorg-16.0.6/clang+llvm-16.0.6-aarch64-linux-gnu.tar.xz
tar Jxvf clang+llvm-16.0.6-aarch64-linux-gnu.tar.xz
echo 'export PATH=/home/pi/clang+llvm-16.0.6-aarch64-linux-gnu/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
  1. Ninja Building and Installation:
git clone https://github.com/martine/ninja.git
cd ninja
./configure.py --bootstrap
mv /home/pi/depot_tools/ninja /home/pi/depot_tools/ninja_org
cp /home/pi/ninja/ninja /home/pi/depot_tools/ninja
  1. GN Building and Installation:
cd /home/pi
git clone https://gn.googlesource.com/gn
cd gn
sed -i -e "s/-Wl,--icf=all//" build/gen.py
python build/gen.py
ninja -C out
sudo mv /home/pi/webrtc/src/buildtools/linux64/gn /home/pi/webrtc/src/buildtools/linux64/gn_org
cp /home/pi/gn/out/gn /home/pi/webrtc/src/buildtools/linux64/gn
sudo mv /home/pi/depot_tools/gn /home/pi/depot_tools/gn_org
cp /home/pi/gn/out/gn /home/pi/depot_tools/gn
  1. Extra Dependencies for GN:
sudo apt-get update
sudo apt-get install python3-pip -y
pip3 install setuptools
  1. WebRTC Build Configuration:
gn gen out/Release64 --args='target_os="linux" target_cpu="arm64" rtc_include_tests=false rtc_use_h264=false use_rtti=true is_component_build=false is_debug=false rtc_build_examples=false use_custom_libcxx=false rtc_build_tools=false rtc_use_pipewire=false clang_base_path="/home/pi/clang+llvm-16.0.6-aarch64-linux-gnu" clang_use_chrome_plugins=false'
ninja -C out/Release64
  1. Header Files Synchronization:
sudo apt-get install rsync
rsync -amv --include=*/ --include=*.h --include=*.hpp --exclude=* ./ ./include
  1. Compiled libwebrtc.a Location:
/home/pi/webrtc/src/out/Release64/obj/libwebrtc.a

The frame is broken at 480x270

ffmpeg -i ./20230617_155615.mp4 -s 480x270 -c:v h264_v4l2m2m test.mp4
An input 1280x720 sample video is resized to 480x270 by h264_v4l2m2m fine.
Is the problem between the libyuv transform mjepg to yuv420?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.