Friday, November 16, 2012

Streaming to Twitch.TV with Linux

Windows users have a few options open to them in order to stream their game play to Twitch.TV.  X-Split, OBS and FFsplit to name a few, interesting the latter are based of ffmpeg! Linux users can use WebcamStudio, but I've not had a lot of success in getting that setup. Although that was quite some time ago since I last tried.

Here I'm going to show you my setup that I use for Minecraft streaming to Twitch.TV

Missing applications that I use you can grab from the Ubuntu repository with apt-get or whatever your comfortable using.

First lets get the stream key sorted.  Login to Twitch.TV, click your name and head to the Dashboard, top right corner is a link to first time streaming. It will take you to a page with various Windows options, in the top right is a Show button if you click it you'll get your stream key.  Select it and Copy it .

Create a file in your $HOME called .twitch_key:

cd 
vi .twitch_key

...and paste in the contents, (this isn't my key, but an example)

live_1827739123_wt7we7twe7rt7we78twr

Save and open another file called audio.sh This is where we are going to create our loopback devices for mixing gameplay audio and microphone sounds.

vi audio.sh

and the contents will be:


#!/bin/bash pactl
load-module module-null-sink sink_name=mix 
pactl load-module module-loopback sink=mix
pactl load-module module-loopback sink=mix

Save and create another file called twitch.sh and paste in these contents:

#! /bin/bash 
TOPXY="$1,$2" 
INRES="1280x720" 
OUTRES="852x480" 
FPS="30" 
QUAL="medium" 
STREAM_KEY=$(cat ~/.twitch_key) 
avconv \ 
    -f x11grab -s $INRES  -r "$FPS" -i :0.0+$TOPXY \ 
    -f alsa -ac 2 -i pulse \ 
    -vcodec libx264 -s $OUTRES -preset $QUAL \ 
    -acodec libmp3lame -ar 44100 -threads 4 -qscale 3 -b 712000  -bufsize 512k \ 
    -f flv "rtmp://live.justin.tv/app/$STREAM_KEY"

And save it. Lets look at those variables TOPXY is the top left corner of the window you want to stream, INRES is the width and height of that window. I set mine to 720p. OUTRES is what your going to broadcast, unless your partnered with Twitch there isn't any point in going higher. Just make sure its a 16:9 aspect ratio. FPS you can guess.

So now its time to get ready to broadcast.....

Load your game, in my case I'm going to use Minecraft. Also you'll need a terminal open and pavucontrol. Anything ontop of the Minecraft window will get send to the stream, so move terminal and pavucontrol out of the way.  You can find Minecraft window dimensions with:

xwininfo -name Minecraft

Just replace Minecraft with your windows title.  You'll see upper-left X, upper-right Y those are your top left corner, Width and Height you need to make 1280 and 720 easy way to do that is with wmctrl

wmctrl -r Minecraft -e 0,50,50,1280,720

That command breaks down to -r is the name of the window, -e as 0,<Top Left>, <Top Right> , <Width>, <Height>. So here we move the top left corner of the window to 50,50 and then resize it to 720p

Next step, setup the audio, by running

sh audio.sh

Now look at the Recording tab on pavucontrol. At the bottom choose All Streams.  The Top Loopback lets make that our gameplay audio, so click the button and choose your Internal Audio or whereever your gameplay audio will come from.

The second Loopback will be our Microphone, in this case I'm going to leave it as Webcam.

You might find you need to visit the Playback tab and make both the Loopbacks play on a unused port, for example my HDMI socket on my Nvidia card.  You'll know you'll need to try this if the next step results in no outputted audio.

Finally we can jump back to the terminal window and launch the stream. You'll need to pass twitch two parameters that being the top corner X and Y position.

sh twitch.sh 50 50 

The first time you launch you'll need to jump back to pavucontrol and the recording tab another option will appear that will be avconv, you'll need to set it to listen to Monitor of Null Output.  You should now be live and streaming with game audio and microphone.  To end the broadcast Ctrl+C in the ffmpeg window.

Unless you restart your login session you'll only need to find the window co-ordinates if they have changed and run the twitch.sh again, the audio settings will last as long as your logged in.

If you made it this far come say Hi on my stream: http://twitch.tv/CreativeTux, drop me a Follow and I'll follow you right back.

To stream from a video device i.e. Xbox or PlayStation game play you would change -f x11grab to -f video4linux2 -r 30 -s 1280x720 -i /dev/video0

12 comments:

  1. I keep getting the following error when trying to stream my desktop.
    Could not open 'rtmp://live.justin.tv/MYLIVEKEY'
    I am not sure if my ffmpeg is even capable of streaming to rtmp, here's the compile options
    http://pastebin.com/ygMRgcxF

    ReplyDelete
    Replies
    1. Are you sure your streaming tothe right location and key? Your comment URL doesn't have the necessary /app/LIVEKEYHERE. Check the format and url location of the ffmpeg/avconv line with the one in my script and make sure your key is correct and without any leading/trailing spaces maybe?

      Delete
  2. Can you comment what version of avconv you are running? the version i just got from apt chokes at the "-preset" part.

    ReplyDelete
    Replies
    1. Do you have the h264 installed? libavformat53 or the -extra, I forget which one and I'm not on my system to double check till this evening. ffmpeg/avconv straight out of apt on Ubuntu, nothing patched or updated.

      Delete
  3. Good how-to, a template for my attempts, thank you:)

    I can get a/v streaming to work, but my approach threw a humongous issue, after 3 minutes or so the latency becomes very noticeable, and by the end of 30 minutes or an hour unbearable.

    I suspected the encoder first(libmp3lame), so I switched it up a bit and employed libfaac. This did not seem to help, it worked! but appeared to use more bandwidth. And like libmp3lame, still produced the latency horror.

    Some googling hinted that jack was the cure for latency and it seemed to work a treat, dont know how I had it working in the first place but after a reboot jack did not want to play, any more, at all.

    Another problem was minecraft. It just straight up refuses to switch sinks.
    One work-around was to disable my hardware sound device[OFF] before running minecraft.

    Besides all that, thanks again for your post, its been fun gaining access to the twitch.tv universe.

    ReplyDelete
  4. Nice tutorial, thanks! Btw I am streaming live 24/7 at (http://www.sscaitournament.com/) using this ;-)

    ReplyDelete
  5. thanks for this. It worked straight up for me. I am wondering though, is there a way to gracefully undo the loopback setup, so that i can remove it and have the system back to a normal state? Also, does this work with skype for both the speaker and the listener, or do i have to add another loopback?

    Cheers,

    ReplyDelete
  6. hi!
    I'm not really good at english, but I understand nearly everything in your post, so thanks!
    But I've got few problems
    the first is after the command "sh audio.sh", I received something like : "audio.sh: 21: audio.sh: load-module: not found
    Failure: Module initialization failed
    Failure: Module initialization failed"
    And the second is with pavucontrol, where there's nothing in the compartiment "recording".
    I'm not sure you're going to see this, but I'm still trying,
    thanks.

    ReplyDelete
  7. I think there's a typo in the first script. I think it should look more like this:

    #!/bin/bash
    pactl load-module module-null-sink sink_name=mix
    pactl load-module module-loopback sink=mix
    pactl load-module module-loopback sink=mix

    ReplyDelete
  8. i am using this method to stream my game AND my webcam microphone but there is serious lag between the game video/audio and my microphone. For example, i will shoot my gun and say into the mic that I am shooting my gun and t on the livestream the visual of shooting my gun occurs and then not for around another 25 seconds does the audio of me saying i am shooting my gun happens. How to fix this mic audio sync issue please? Also, I am trying to ensure that I am streaming around 2,500kb/ps for the video to twitch BUT it's very weird in that whatever bitrate I choose for the acodec is what's used for both. So you have "acodec libmp3lame -ar 44100 -threads 4 -qscale 3 -b 712000" which will result in audio and video being streamed at 712 kb/ps only. How do I set the video bitrate to be CBR versus VBR since twitch hates VBR I have read online in many places. All the windows tutorials I have seen for using xsplit or obs state to set the CBR (constant bit rate).

    ReplyDelete
  9. avconv seems to constantly give me this error:
    avconv version 0.8.9-6:0.8.9-0ubuntu0.13.04.1, Copyright (c) 2000-2013 the Libav developers
    built on Nov 9 2013 19:09:48 with gcc 4.7.3
    Hyper fast Audio and Video encoder
    usage: avconv [options] [[infile options] -i infile]... {[outfile options] outfile}...

    Use -h to get full help or, even better, run 'man avconv'
    twitch.sh: 17: twitch.sh: -f: not found
    twitch.sh: 19: twitch.sh: -f: not found
    twitch.sh: 21: twitch.sh: -vcodec: not found
    twitch.sh: 23: twitch.sh: -acodec: not found
    twitch.sh: 25: twitch.sh: -f: not found

    ReplyDelete
  10. i keep getting this error but atleast it is not like the old on i was getting
    ffmpeg version 1.2.6-7:1.2.6-1~trusty1 Copyright (c) 2000-2014 the FFmpeg developers
    built on Apr 26 2014 18:52:58 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
    configuration: --arch=amd64 --disable-stripping --enable-avresample --enable-pthreads --enable-runtime-cpudetect --extra-version='7:1.2.6-1~trusty1' --libdir=/usr/lib/x86_64-linux-gnu --prefix=/usr --enable-bzlib --enable-libdc1394 --enable-libfreetype --enable-frei0r --enable-gnutls --enable-libgsm --enable-libmp3lame --enable-librtmp --enable-libopencv --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-vaapi --enable-vdpau --enable-libvorbis --enable-libvpx --enable-zlib --enable-gpl --enable-postproc --enable-libcdio --enable-x11grab --enable-libx264 --shlibdir=/usr/lib/x86_64-linux-gnu --enable-shared --disable-static
    avcodec configuration: --arch=amd64 --disable-stripping --enable-avresample --enable-pthreads --enable-runtime-cpudetect --extra-version='7:1.2.6-1~trusty1' --libdir=/usr/lib/x86_64-linux-gnu --prefix=/usr --enable-bzlib --enable-libdc1394 --enable-libfreetype --enable-frei0r --enable-gnutls --enable-libgsm --enable-libmp3lame --enable-librtmp --enable-libopencv --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-vaapi --enable-vdpau --enable-libvorbis --enable-libvpx --enable-zlib --enable-gpl --enable-postproc --enable-libcdio --enable-x11grab --enable-libx264 --shlibdir=/usr/lib/x86_64-linux-gnu --enable-shared --disable-static --enable-version3 --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvo-aacenc --enable-libvo-amrwbenc
    libavutil 52. 18.100 / 52. 18.100
    libavcodec 54. 92.100 / 54. 92.100
    libavformat 54. 63.104 / 54. 63.104
    libavdevice 53. 5.103 / 53. 5.103
    libavfilter 3. 42.103 / 3. 42.103
    libswscale 2. 2.100 / 2. 2.100
    libswresample 0. 17.102 / 0. 17.102
    libpostproc 52. 2.100 / 52. 2.100
    [NULL @ 0x698d00] Unable to find a suitable output format for ' '
    : Invalid argument
    twitch.sh: 9: twitch.sh: -f: not found
    twitch.sh: 10: twitch.sh: -f: not found
    twitch.sh: 11: twitch.sh: -vcodec: not found
    twitch.sh: 12: twitch.sh: -acodec: not found
    twitch.sh: 13: twitch.sh: -f: not found

    ReplyDelete