Skip to content

Instantly share code, notes, and snippets.

@ikester
Last active June 12, 2023 18:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikester/eeb739dd65f82198241daeac097967ab to your computer and use it in GitHub Desktop.
Save ikester/eeb739dd65f82198241daeac097967ab to your computer and use it in GitHub Desktop.
Linux USB UVC gadget driver setup script.
#!/bin/bash
# set -e
cd /sys/kernel/config/usb_gadget/
mkdir -p g1
cd g1
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol
mkdir -p strings/0x409
echo "Ikestrom" > strings/0x409/manufacturer
echo "RPiZ Loopback Cam" > strings/0x409/product
echo "0123456789" > strings/0x409/serialnumber
mkdir -p configs/c.1
# echo "0x80" > configs/c.1/bmAttributes
echo "500" > configs/c.1/MaxPower
mkdir -p configs/c.1/strings/0x409
echo "UVC Config" > configs/c.1/strings/0x409/configuration
# Create UVC Functions
mkdir -p functions/uvc.usb0
create_function() {
# Example usage:
# create_function <width> <height> <format> <name>
WIDTH=$1
HEIGHT=$2
FORMAT=$3
NAME=$4
wdir=functions/uvc.usb0/streaming/$FORMAT/$NAME/${HEIGHT}p
mkdir -p $wdir
echo $WIDTH > $wdir/wWidth
echo $HEIGHT > $wdir/wHeight
echo 29491200 > $wdir/dwMinBitRate
echo 29491200 > $wdir/dwMaxBitRate
echo $(( $WIDTH * $HEIGHT * 2 )) > $wdir/dwMaxVideoFrameBufferSize
# dwFrameInterfal is in 100-ns units (fps = 1/(dwFrameInterval * 10000000))
# 333333 -> 30 fps
# 666666 -> 15 fps
# 5000000 -> 2 fps
cat <<EOF > $wdir/dwFrameInterval
333333
666666
5000000
EOF
}
# create_function 320 180 uncompressed u
# create_function 640 360 uncompressed u
create_function 1280 720 uncompressed u
# create_function 1920 1080 uncompressed u
# create_function 320 180 mjpeg m
# create_function 640 360 mjpeg m
# create_function 1280 720 mjpeg m
# create_function 1920 1080 mjpeg m
mkdir -p functions/uvc.usb0/streaming/header/h
cd functions/uvc.usb0/streaming/header/h
ln -s ../../uncompressed/u
# ln -s ../../mjpeg/m
cd ../../class/fs
ln -s ../../header/h
cd ../../class/hs
ln -s ../../header/h
cd ../../../control
mkdir -p header/h
ln -s header/h class/fs
ln -s header/h class/ss
cd ../../../
# Set the packet size: uvc gadget max size is 3k...
# echo 3072 > functions/uvc.usb0/streaming_maxpacket
echo 2048 > functions/uvc.usb0/streaming_maxpacket
# echo 1024 > functions/uvc.usb0/streaming_maxpacket
ln -s functions/uvc.usb0 configs/c.1
echo `ls /sys/class/udc` > UDC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment