From aaebaa544d14d96e866e44b3878d759c146f4424 Mon Sep 17 00:00:00 2001
From: Nicolas Pernoud <github@ninico.fr>
Date: Thu, 19 Mar 2020 16:15:41 +0100
Subject: [PATCH] feat: calc bitrate according to connection speed

---
 README.md       |  2 ++
 start_stream.sh | 29 ++++++++++++++++++++---------
 2 files changed, 22 insertions(+), 9 deletions(-)

diff --git a/README.md b/README.md
index 69ade66..a829c6e 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,8 @@ A simple script to turn an headless raspberry pi 4 (with a **good** microphone)
 
 ## Setup
 
+Install speedtest-cli : `sudo apt install speedtest-cli`.
+
 Set up the pi to boot in logged in (pi user) console mode with `sudo raspi-config`.
 Copy the **start_stream.sh** script into `/home/pi` and make it executable with `chmod +x ./start_stream.sh`.
 
diff --git a/start_stream.sh b/start_stream.sh
index 0547ebd..aac87b8 100644
--- a/start_stream.sh
+++ b/start_stream.sh
@@ -1,9 +1,18 @@
 #!/bin/sh
 KEY="***PUT YOUR YOUTUBE API KEY HERE***"
 
-sleep 30 # Allow time for the raspberry pi to boot
+# Wait for the network to be up
+while [ $(cat /sys/class/net/wlan0/operstate) != "up" ]; do
+    echo "Wifi is down. Waiting..."
+    sleep 5
+done
+# Get the upload speed
+UPLOAD_SPEED=$(speedtest --csv --no-download | cut -d ',' -f8 | cut -d '.' -f1)
+# Take half the speed for bitrate
+BITRATE="$(($UPLOAD_SPEED / 2))"
 
 echo "STREAM BOX STARTED - Press [CTRL+C] to stop..."
+echo "Bitrate is ${BITRATE}"
 
 while true; do
     #Pipe to ffmpeg
@@ -12,12 +21,14 @@ while true; do
     #Audio options
     #Video options
     #Push to youtube
-    raspivid -n -o - -t 0 -hf -fps 25 -b 6000000 | ffmpeg -re \
-        -thread_queue_size 8192 \
-        -f alsa -i plughw:1,0 \
-        -thread_queue_size 8192 \
-        -f h264 -i - -r 25 \
-        -ac 1 -acodec libmp3lame -ar 44100 -b:a 128k \
-        -vcodec copy \
-        -g 50 -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/$KEY
+    raspivid --nopreview --output - -t 0 \
+    -w 1280 -h 720 -fps 25 -b ${BITRATE} |
+        ffmpeg -re \
+    -thread_queue_size 65536 \
+    -f alsa -i plughw:1,0 \
+    -thread_queue_size 65536 \
+    -f h264 -i - -r 25 \
+    -ac 1 -acodec libmp3lame -ar 44100 -b:a 128k \
+    -vcodec copy \
+    -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/$KEY
 done
-- 
GitLab