diff --git a/.gitignore b/.gitignore index 6f6f5e6..b1b5a14 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,9 @@ # Go workspace file go.work go.work.sum + +bin/** +build/** +config/config.yaml + + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3fb1b48 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +# builds service executable +.PHONY: build +build: + go build -x -v -o ./bin/gowebrtc pkg/main.go + +clean: + rm -rvf bin build + +debian: build + mkdir -p build/debian/gowebrtc/DEBIAN \ + build/debian/gowebrtc/usr/local/bin \ + build/debian/gowebrtc/etc/gowebrtc/ \ + build/debian/gowebrtc/lib/systemd/system \ + build/debian/gowebrtc/usr/share/gowebrtc + cp -v config/config.yaml.sample build/debian/gowebrtc/etc/gowebrtc + cp -v bin/gowebrtc build/debian/gowebrtc/usr/local/bin + cp -v gowebrtc.service build/debian/gowebrtc/lib/systemd/system + cp -av html build/debian/gowebrtc/usr/share/gowebrtc + cp -v debian.control build/debian/gowebrtc/DEBIAN/control + dpkg-deb --build build/debian/gowebrtc + +debian-install: debian + sudo dpkg -i build/debian/gowebrtc.deb + +debian-uninstall: + sudo dpkg -r gowebrtc + +.PHONY: test +test: build + @./bin/gowebrtc server diff --git a/config/config.yaml.sample b/config/config.yaml.sample new file mode 100644 index 0000000..32ffed3 --- /dev/null +++ b/config/config.yaml.sample @@ -0,0 +1,8 @@ +port: 8080 +url: /stream +image_width: 640 +image_height: 480 +framerate: 30 +log_file: /var/log/gowebrtc.log +audio_device: alsasrc device=plughw:CARD=I930,DEV=0 +video_device: autovideosrc diff --git a/debian.control b/debian.control new file mode 100644 index 0000000..da648f5 --- /dev/null +++ b/debian.control @@ -0,0 +1,6 @@ +Package: gowebrtc +Version: 0.1.0 +Maintainer: Neeraj Jakhar +Architecture: all +Description: Service to setup webrtc streaming +Depends: libgstreamer1.0-dev, libgstreamer-plugins-base1.0-dev, gstreamer1.0-plugins-good, gstreamer1.0-alsa diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..1bd1711 --- /dev/null +++ b/go.mod @@ -0,0 +1,63 @@ +module github.com/homebackend/go-webrtc + +go 1.22.5 + +require ( + github.com/akamensky/argparse v1.4.0 + github.com/gin-gonic/gin v1.10.0 + github.com/go-gst/go-gst v1.1.0 + github.com/homebackend/go-homebackend-common v0.0.0-20231117105846-e72d04db4335 + github.com/pion/webrtc/v3 v3.2.49 +) + +require ( + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-gst/go-glib v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/google/uuid v1.3.1 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-pointer v0.0.1 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pion/datachannel v1.5.8 // indirect + github.com/pion/dtls/v2 v2.2.12 // indirect + github.com/pion/ice/v2 v2.3.29 // indirect + github.com/pion/interceptor v0.1.29 // indirect + github.com/pion/logging v0.2.2 // indirect + github.com/pion/mdns v0.0.12 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/rtcp v1.2.14 // indirect + github.com/pion/rtp v1.8.7 // indirect + github.com/pion/sctp v1.8.19 // indirect + github.com/pion/sdp/v3 v3.0.9 // indirect + github.com/pion/srtp/v2 v2.0.20 // indirect + github.com/pion/stun v0.6.1 // indirect + github.com/pion/transport/v2 v2.2.4 // indirect + github.com/pion/turn/v2 v2.1.6 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.23.0 // indirect + golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6c53d1f --- /dev/null +++ b/go.sum @@ -0,0 +1,206 @@ +github.com/akamensky/argparse v1.4.0 h1:YGzvsTqCvbEZhL8zZu2AiA5nq805NZh75JNj4ajn1xc= +github.com/akamensky/argparse v1.4.0/go.mod h1:S5kwC7IuDcEr5VeXtGPRVZ5o/FdhcMlQz4IZQuw64xA= +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-gst/go-glib v1.1.0 h1:XTGhwk2BWYjW/UZ08y7ojf3iPPRiYtXL0W6vJkXNKFc= +github.com/go-gst/go-glib v1.1.0/go.mod h1:JybIYeoHNwCkHGaBf1fHNIaM4sQTrJPkPLsi7dmPNOU= +github.com/go-gst/go-gst v1.1.0 h1:HSQyvJld2kNgiyVC8CJ0N1PEvR/b0Ld6nkkzZLljuzk= +github.com/go-gst/go-gst v1.1.0/go.mod h1:izJ4GCBNWAv5W4mudSvvmDZhm98xvbCxH0GeK5A5VE8= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/homebackend/go-homebackend-common v0.0.0-20231117105846-e72d04db4335 h1:GfL9jFuSpEjklpjfOVnTGQyD3Nd2VbF4ecik0biaFG4= +github.com/homebackend/go-homebackend-common v0.0.0-20231117105846-e72d04db4335/go.mod h1:URcU1vebZS3laMHyd63rbCFKaqSypeLSy7elh4v9qMk= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b h1:FQ7+9fxhyp82ks9vAuyPzG0/vVbWwMwLJ+P6yJI5FN8= +github.com/juju/fslock v0.0.0-20160525022230-4d5c94c67b4b/go.mod h1:HMcgvsgd0Fjj4XXDkbjdmlbI505rUPBs6WBMYg2pXks= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0= +github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pion/datachannel v1.5.8 h1:ph1P1NsGkazkjrvyMfhRBUAWMxugJjq2HfQifaOoSNo= +github.com/pion/datachannel v1.5.8/go.mod h1:PgmdpoaNBLX9HNzNClmdki4DYW5JtI7Yibu8QzbL3tI= +github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= +github.com/pion/dtls/v2 v2.2.12 h1:KP7H5/c1EiVAAKUmXyCzPiQe5+bCJrpOeKg/L05dunk= +github.com/pion/dtls/v2 v2.2.12/go.mod h1:d9SYc9fch0CqK90mRk1dC7AkzzpwJj6u2GU3u+9pqFE= +github.com/pion/ice/v2 v2.3.29 h1:nKSU0Kb7F0Idfaz15EwGB1GbOxBlONXnWma5p1lOFcE= +github.com/pion/ice/v2 v2.3.29/go.mod h1:KXJJcZK7E8WzrBEYnV4UtqEZsGeWfHxsNqhVcVvgjxw= +github.com/pion/interceptor v0.1.29 h1:39fsnlP1U8gw2JzOFWdfCU82vHvhW9o0rZnZF56wF+M= +github.com/pion/interceptor v0.1.29/go.mod h1:ri+LGNjRUc5xUNtDEPzfdkmSqISixVTBF/z/Zms/6T4= +github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= +github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= +github.com/pion/mdns v0.0.12 h1:CiMYlY+O0azojWDmxdNr7ADGrnZ+V6Ilfner+6mSVK8= +github.com/pion/mdns v0.0.12/go.mod h1:VExJjv8to/6Wqm1FXK+Ii/Z9tsVk/F5sD/N70cnYFbk= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/rtcp v1.2.12/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4= +github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE= +github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4= +github.com/pion/rtp v1.8.3/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= +github.com/pion/rtp v1.8.7 h1:qslKkG8qxvQ7hqaxkmL7Pl0XcUm+/Er7nMnu6Vq+ZxM= +github.com/pion/rtp v1.8.7/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= +github.com/pion/sctp v1.8.19 h1:2CYuw+SQ5vkQ9t0HdOPccsCz1GQMDuVy5PglLgKVBW8= +github.com/pion/sctp v1.8.19/go.mod h1:P6PbDVA++OJMrVNg2AL3XtYHV4uD6dvfyOovCgMs0PE= +github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY= +github.com/pion/sdp/v3 v3.0.9/go.mod h1:B5xmvENq5IXJimIO4zfp6LAe1fD9N+kFv+V/1lOdz8M= +github.com/pion/srtp/v2 v2.0.20 h1:HNNny4s+OUmG280ETrCdgFndp4ufx3/uy85EawYEhTk= +github.com/pion/srtp/v2 v2.0.20/go.mod h1:0KJQjA99A6/a0DOVTu1PhDSw0CXF2jTkqOoMg3ODqdA= +github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4= +github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8= +github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= +github.com/pion/transport/v2 v2.2.2/go.mod h1:OJg3ojoBJopjEeECq2yJdXH9YVrUJ1uQ++NjXLOUorc= +github.com/pion/transport/v2 v2.2.3/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= +github.com/pion/transport/v2 v2.2.4 h1:41JJK6DZQYSeVLxILA2+F4ZkKb4Xd/tFJZRFZQ9QAlo= +github.com/pion/transport/v2 v2.2.4/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0= +github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= +github.com/pion/transport/v3 v3.0.2 h1:r+40RJR25S9w3jbA6/5uEPTzcdn7ncyU44RWCbHkLg4= +github.com/pion/transport/v3 v3.0.2/go.mod h1:nIToODoOlb5If2jF9y2Igfx3PFYWfuXi37m0IlWa/D0= +github.com/pion/turn/v2 v2.1.3/go.mod h1:huEpByKKHix2/b9kmTAM3YoX6MKP+/D//0ClgUYR2fY= +github.com/pion/turn/v2 v2.1.6 h1:Xr2niVsiPTB0FPtt+yAWKFUkU1eotQbGgpTIld4x1Gc= +github.com/pion/turn/v2 v2.1.6/go.mod h1:huEpByKKHix2/b9kmTAM3YoX6MKP+/D//0ClgUYR2fY= +github.com/pion/webrtc/v3 v3.2.49 h1:G0DfKWeA++CBH7RcwB7M4msg9t/euEnFz638PYB6Ipg= +github.com/pion/webrtc/v3 v3.2.49/go.mod h1:s+tiQ44KWdJJkEw/oOoW24fW0ZEHlgOd3QyT90bqHeM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY= +golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/gowebrtc.service b/gowebrtc.service new file mode 100644 index 0000000..445301d --- /dev/null +++ b/gowebrtc.service @@ -0,0 +1,12 @@ +[Unit] +Description=Service to setup webrtc streaming +Wants=network-online.target +After=network-online.target + +[Service] +ExecStart=/usr/local/bin/gowebrtc server +Restart=always +RestartSec=5s + +[Install] +WantedBy=multi-user.target diff --git a/html/index.html b/html/index.html new file mode 100644 index 0000000..a631f70 --- /dev/null +++ b/html/index.html @@ -0,0 +1,30 @@ + + + + + + WebRTC + + + + + + + + +
+ +
+ + Video
+
+ +

+ + Logs
+
+ + + + + diff --git a/html/main.css b/html/main.css new file mode 100644 index 0000000..9e43d34 --- /dev/null +++ b/html/main.css @@ -0,0 +1,4 @@ +textarea { + width: 500px; + min-height: 75px; +} \ No newline at end of file diff --git a/html/main.js b/html/main.js new file mode 100644 index 0000000..3d023c5 --- /dev/null +++ b/html/main.js @@ -0,0 +1,77 @@ +remoteStream = new MediaStream() +document.getElementById('video-player').srcObject = remoteStream + +let pc = new RTCPeerConnection({ + iceServers: [{ + urls: 'stun:stun.l.google.com:19302' + }] +}) +let log = msg => { + document.getElementById('div').innerHTML += msg + '
' +} + +pc.ontrack = function(event) { + event.streams[0].getTracks().forEach((track) => { + remoteStream.addTrack(track) + }) +} + +pc.oniceconnectionstatechange = e => log(pc.iceConnectionState) +pc.onicecandidate = event => { + if (event.candidate) { + console.log('Updated candidate: ' + btoa(JSON.stringify(pc.localDescription))); + } +} + +// Offer to receive 1 audio, and 1 video track +pc.addTransceiver('video', { + 'direction': 'sendrecv' +}) +pc.addTransceiver('audio', { + 'direction': 'sendrecv' +}) + +pc.createOffer().then(d => pc.setLocalDescription(d)).catch(log) + +window.startSession = () => { + document.getElementById('start-session').disabled = true; + let localSessionDescription = btoa(JSON.stringify(pc.localDescription)); + console.log('Local: ' + localSessionDescription); + + fetch('/stream', { + method: 'POST', + body: JSON.stringify({"sdp": localSessionDescription}), + headers: { + 'Content-Type': 'application/json' + } + }).then(response => { + if (!response.ok) { + alert('Failed to call /stream api'); + throw new Error('Error calling api'); + } + + return response.json(); + }).then(data => { + console.log('Remote: ' + data); + pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(data.sdp)))); + document.getElementById('stop-session').disabled = false; + }).catch(error => { + alert('Error' + error); + }); +} + +window.stopSession = () => { + document.getElementById('stop-session').disabled = true; + document.getElementById('reload-session').disabled = false; + fetch('/stream', { + method: 'DELETE', + }).then(response => { + if (!response.ok) { + alert('Failed to call /stream api'); + throw new Error('Error calling api'); + } + }).catch(error => { + alert('Error' + error); + }); +} + diff --git a/pkg/main.go b/pkg/main.go new file mode 100644 index 0000000..3bee6d6 --- /dev/null +++ b/pkg/main.go @@ -0,0 +1,448 @@ +/* + Copyright (c) 2024 Neeraj Jakhar + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +package main + +import ( + "bufio" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "strings" + "syscall" + "time" + + "github.com/akamensky/argparse" + "github.com/gin-gonic/gin" + "github.com/go-gst/go-gst/gst" + "github.com/go-gst/go-gst/gst/app" + homecommon "github.com/homebackend/go-homebackend-common/pkg" + "github.com/pion/webrtc/v3" + "github.com/pion/webrtc/v3/pkg/media" +) + +const ( + CONF_FILE = "/etc/gowebrtc/config.yaml" + ANSWER = "Answer: " +) + +type Request struct { + SDP string `json:"sdp"` +} + +type Response struct { + SDP string `json:"sdp"` +} + +type Configuration struct { + Port int `yaml:"port" validate:"number,gte=1,lte=65535" default:"8080"` + Url string `yaml:"url" default:"/stream"` + ImageWidth uint `yaml:"image_width" default:"640"` + ImageHeight uint `yaml:"image_height" default:"480"` + FrameRate uint `yaml:"framerate" default:"30"` + LogFile string `yaml:"log_file" default:"none"` + AudioDevice string `yaml:"audio_device" validate:"required"` + VideoDevice string `yaml:"video_device" validate:"required"` +} + +// Encode encodes the input in base64 +func encode(obj interface{}) string { + b, err := json.Marshal(obj) + if err != nil { + log.Fatalln(err) + } + + return base64.StdEncoding.EncodeToString(b) +} + +func decode(in string, obj interface{}) { + b, err := base64.StdEncoding.DecodeString(in) + if err != nil { + log.Fatalln(err) + } + + err = json.Unmarshal(b, obj) + if err != nil { + log.Fatalln(err) + } +} + +func mustReadStdin() string { + r := bufio.NewReader(os.Stdin) + + var in string + for { + var err error + in, err = r.ReadString('\n') + if err != io.EOF { + if err != nil { + log.Fatalln(err) + } + } + in = strings.TrimSpace(in) + if len(in) > 0 { + break + } + } + + fmt.Printf("Stdin: %s\n", in) + return in +} + +func main() { + parser := argparse.NewParser(os.Args[0], "Setup Webrtc for video streaming from local camera") + + serverCommand := parser.NewCommand("server", "Start webrtc service") + executeCommand := parser.NewCommand("execute", "Execute webrtc streaming") + + c := serverCommand.String("c", "configuration-file", &argparse.Options{ + Required: false, + Default: CONF_FILE, + Help: "Configuration File", + }) + + a := executeCommand.String("a", "audio-pipeline", &argparse.Options{ + Required: true, + Help: "GStreamer audio pipeline to use", + }) + + v := executeCommand.String("v", "video-pipeline", &argparse.Options{ + Required: true, + Help: "GStreamer video pipeline to use", + }) + + s := executeCommand.String("s", "sdp-file", &argparse.Options{ + Required: true, + Help: "File containing SDP data", + }) + + err := parser.Parse(os.Args) + if err != nil { + fmt.Print(parser.Usage(err)) + os.Exit(1) + } + + if serverCommand.Happened() { + config := homecommon.GetConf[Configuration](*c) + streaming := false + pid := 0 + + f := setupLogging(config.LogFile) + if f != nil { + defer f.Close() + } + + var htmldir string + if _, err := os.Stat("./html"); err == nil { + htmldir = "./html" + } else { + htmldir = "/usr/share/gowebrtc/html" + } + + gin.DisableConsoleColor() + gin.DefaultWriter = log.Writer() + + router := gin.Default() + router.Static("/", htmldir) + router.POST("/stream", createStream(config, &streaming, &pid)) + router.DELETE("/stream", deleteStream(&streaming, &pid)) + router.Run(fmt.Sprintf("0.0.0.0:%d", config.Port)) + } else if executeCommand.Happened() { + startExecuting(*v, *a, *s) + } +} + +func deleteStream(streaming *bool, pid *int) gin.HandlerFunc { + fn := func(c *gin.Context) { + if *streaming { + syscall.Kill(*pid, syscall.SIGINT) + *streaming = false + } + + c.Writer.WriteHeader(http.StatusNoContent) + } + + return fn +} + +func executeSelfAsExecutor(videoSrc, audioSrc, sdpFileName string, pid chan int, answer chan string) int { + cmd := exec.Command(os.Args[0], "execute", "-v", videoSrc, "-a", audioSrc, "-s", sdpFileName) + + stdout, err := cmd.StdoutPipe() + if err != nil { + log.Fatalln(err) + } + stderr, err := cmd.StderrPipe() + if err != nil { + log.Fatalln(err) + } + + cmd.Start() + pid <- cmd.Process.Pid + + scanner := bufio.NewScanner(stdout) + for scanner.Scan() { + m := scanner.Text() + if strings.HasPrefix(m, "Answer: ") { + answerText := m[len(ANSWER):] + log.Printf("Answer found to be %s", answerText) + answer <- answerText + } else { + log.Println(m) + } + } + + scanerr := bufio.NewScanner(stderr) + for scanerr.Scan() { + m := scanner.Text() + log.Println(m) + } + + if err := cmd.Wait(); err != nil { + if exiterr, ok := err.(*exec.ExitError); ok { + return exiterr.ExitCode() + } else { + log.Fatalf("cmd.Wait: %v", err) + } + } + + return 0 +} + +func createStream(config *Configuration, streaming *bool, child *int) gin.HandlerFunc { + fn := func(c *gin.Context) { + if *streaming { + c.AbortWithStatusJSON(http.StatusInternalServerError, map[string]string{"message": "Service unavailable as streaming is in progress"}) + return + } + + *streaming = true + + var request Request + if err := c.BindJSON(&request); err != nil { + log.Println(err) + return + } + + videoSrc := fmt.Sprintf("%s ! video/x-raw, width=%d, height=%d, framerate=%d/1 ! videoconvert ! queue", config.VideoDevice, config.ImageWidth, config.ImageHeight, config.FrameRate) + audioSrc := fmt.Sprintf("%s ! audioconvert ! queue", config.AudioDevice) + + log.Println(videoSrc) + log.Println(audioSrc) + + file, err := os.CreateTemp("/tmp", "gowebrtc") + if err != nil { + log.Println(err) + c.IndentedJSON(http.StatusInternalServerError, map[string]string{"message": "Unable to create sdp file"}) + } + sdpFileName := file.Name() + defer os.Remove(sdpFileName) + + file.WriteString(request.SDP) + file.Close() + + var response Response + answer := make(chan string) + pid := make(chan int) + failure := make(chan int) + + go func() { + log.Println("About to execute streaming process") + code := executeSelfAsExecutor(videoSrc, audioSrc, sdpFileName, pid, answer) + log.Printf("Child process with PID: %d exited with code: %d", *child, code) + *streaming = false + *child = 0 + failure <- code + }() + + for { + select { + case s := <-answer: + log.Println("Got result") + response.SDP = s + c.IndentedJSON(http.StatusOK, response) + log.Println("Sent response") + return + case code := <-failure: + log.Println("Got error while starting streaming") + c.IndentedJSON(http.StatusInternalServerError, map[string]string{"message": fmt.Sprintf("Error while creating stream: %d", code)}) + return + case p := <-pid: + log.Printf("Started process with pid: %d", p) + *child = p + break + default: + time.Sleep(100 * time.Millisecond) + } + } + } + + return fn +} + +func setupLogging(logFile string) *os.File { + if logFile != "none" { + f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + log.Fatalf("Error opening file: %v", err) + } + + log.SetOutput(f) + + return f + } + + return nil +} + +func startExecuting(videoSrc, audioSrc, sdpFile string) { + gst.Init(nil) + config := webrtc.Configuration{} + + peerConnection, err := webrtc.NewPeerConnection(config) + if err != nil { + panic(err) + } + + peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) { + fmt.Printf("Connection State has changed %s \n", connectionState.String()) + if connectionState == webrtc.ICEConnectionStateFailed { + panic("Exiting as connection could not be established") + } + }) + + audioTrack, err := webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{MimeType: "audio/opus"}, "audio", "pion1") + if err != nil { + panic(err) + } + _, err = peerConnection.AddTrack(audioTrack) + if err != nil { + panic(err) + } + + // Create a video track + firstVideoTrack, err := webrtc.NewTrackLocalStaticSample(webrtc.RTPCodecCapability{MimeType: "video/vp8"}, "video", "pion2") + if err != nil { + panic(err) + } + _, err = peerConnection.AddTrack(firstVideoTrack) + if err != nil { + panic(err) + } + + buf, err := os.ReadFile(sdpFile) + if err != nil { + panic(err) + } + + offer := webrtc.SessionDescription{} + decode(string(buf), &offer) + + err = peerConnection.SetRemoteDescription(offer) + if err != nil { + panic(err) + } + + answer, err := peerConnection.CreateAnswer(nil) + if err != nil { + panic(err) + } + + gatherComplete := webrtc.GatheringCompletePromise(peerConnection) + + err = peerConnection.SetLocalDescription(answer) + if err != nil { + panic(err) + } + + fmt.Println("Gathering candidates") + <-gatherComplete + + localDescription := encode(*peerConnection.LocalDescription()) + fmt.Println(ANSWER + localDescription) + + pipelineForCodec("opus", []*webrtc.TrackLocalStaticSample{audioTrack}, audioSrc) + pipelineForCodec("vp8", []*webrtc.TrackLocalStaticSample{firstVideoTrack}, videoSrc) + + select {} +} + +// Create the appropriate GStreamer pipeline depending on what codec we are working with +func pipelineForCodec(codecName string, tracks []*webrtc.TrackLocalStaticSample, pipelineSrc string) { + pipelineStr := "appsink name=appsink" + switch codecName { + case "vp8": + pipelineStr = pipelineSrc + " ! vp8enc error-resilient=partitions keyframe-max-dist=10 auto-alt-ref=true cpu-used=5 deadline=1 ! " + pipelineStr + case "vp9": + pipelineStr = pipelineSrc + " ! vp9enc ! " + pipelineStr + case "h264": + pipelineStr = pipelineSrc + " ! video/x-raw,format=I420 ! x264enc speed-preset=ultrafast tune=zerolatency key-int-max=20 ! video/x-h264,stream-format=byte-stream ! " + pipelineStr + case "opus": + pipelineStr = pipelineSrc + " ! opusenc ! " + pipelineStr + case "pcmu": + pipelineStr = pipelineSrc + " ! audio/x-raw, rate=8000 ! mulawenc ! " + pipelineStr + case "pcma": + pipelineStr = pipelineSrc + " ! audio/x-raw, rate=8000 ! alawenc ! " + pipelineStr + default: + log.Fatalln("Unhandled codec " + codecName) //nolint + } + + log.Println(pipelineStr) + pipeline, err := gst.NewPipelineFromString(pipelineStr) + if err != nil { + log.Fatalln(err) + } + + if err = pipeline.SetState(gst.StatePlaying); err != nil { + log.Fatalln(err) + } + + appSink, err := pipeline.GetElementByName("appsink") + if err != nil { + log.Fatalln(err) + } + + app.SinkFromElement(appSink).SetCallbacks(&app.SinkCallbacks{ + NewSampleFunc: func(sink *app.Sink) gst.FlowReturn { + sample := sink.PullSample() + if sample == nil { + return gst.FlowEOS + } + + buffer := sample.GetBuffer() + if buffer == nil { + return gst.FlowError + } + + samples := buffer.Map(gst.MapRead).Bytes() + defer buffer.Unmap() + + for _, t := range tracks { + if err := t.WriteSample(media.Sample{Data: samples, Duration: *buffer.Duration().AsDuration()}); err != nil { + log.Fatalln(err) //nolint + } + } + + return gst.FlowOK + }, + }) +}