Streaming to twitch.tv with ffmpeg…

April 26, 2016 | My Projects | By: Mark VandeWettering

I was trying to figure out how to screencast to twitch.tv using ffmpeg. A couple of hours of tinkering resulted in the following command line which does a bunch of stuff.

  • It captures the X desktop at 15 fps and 1920×1080 resolution.
  • It grabs frames from my webcam (a Logitech Pro 9000) at 320×240 resolution.
  • It then combines the two into a 1024×576 image, with the video overlayed at the top right and a banner at the bottom that displays a couple of lines of text.
  • It then ships it to the twitch.tv server.  If you grab this code, you need to add your own streaming URL for your own channel.
#!/bin/bash

/home/markv/bin/ffmpeg 	\
	-y -thread_queue_size 64 -f x11grab -s 1920x1080 -framerate 15 -i :0.0+0,0 \
	-thread_queue_size 64 -f v4l2 -input_format mjpeg -framerate 5 -video_size 320x240 -i /dev/video0 \
	-filter_complex \
	"[0:v] scale=1024:576, setpts=PTS-STARTPTS  [bg]; \
	 [1:v] setpts=PTS-STARTPTS [fg]; \
	 color=0x336699cc:1024x64, drawtext=textfile=twitch.txt:fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf:x=10:y=16:fontsize=16:fontcolor=white [bottom] ; \
	 [bg][fg] overlay=W-w-16:16 [out2]; \
	 [out2][bottom] overlay=0:H-64, format=yuv420p [out]" \
	-map "[out]" \
	-vsync 1 \
	-c:v libx264 -b:v 500k -maxrate 500k -bufsize 1000k -framerate 15 -g 30 -crf 30 -preset fast -pix_fmt yuv420p -tune zerolatency \
	-f flv rtmp://live.twitch.tv/app/live_XXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

A few additional notes:

  • The default DNS server for my ISP don’t serve DNS requests for the live.twitch.tv server.   I fixed this by adding the Google DNS servers to my router (8.8.8.8 and 8.8.4.4).
  • The script appears to work pretty well, but sometimes has difficulty starting up.  And, when the script crashes, the remote clients don’t time out for a considerable time.
  • I haven’t tested this extensively.

Buyer beware, but I hope it is useful.