Advertisement
v1ral_ITS

twitch_ffmpeg

Jun 27th, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 14.07 KB | None | 0 0
  1. #! /bin/bash
  2.  
  3. # ================================================ OPTIONS =====================================================
  4. # Add the FFMPEG ABSOLUTE PATH "/path/to/ffmpeg"
  5. FFMPEG_PATH="ffmpeg"
  6.  
  7. # Streaming Options
  8. OUTRES="1280x720"     # Twitch Output Resolution
  9. FPS="24"              # Frame per Seconds (Suggested 24, 25, 30 or 60)
  10. THREADS="4"           # Change this if you have a good CPU (Suggested 4 threads, Max 6 threads)
  11. QUALITY="ultrafast"   # ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo
  12. CBR="1000k"           # Constant bitrate (CBR) Increase this to get a better pixel quality (1000k - 3000k for twitch)
  13.  
  14. # Webcam Options
  15. WEBCAM="/dev/video0" # WebCam device
  16. WEBCAM_WH="320:240"  # WebCam Width end Height
  17. WEBCAM_XY=""         # WebCam Position (in pixel) example: "10:10", if "" (empty) then it will set the standard position
  18.  
  19. # File to save if you do not want to stream
  20. FILE_VIDEO="my.flv"  # File name
  21.  
  22. # STREAM KEY
  23. # You can find YOUR key here: http://www.twitch.tv/broadcast/ (Show Key button)
  24. # Save your key inside the twitch_key file
  25. # Or make a global file named ".twitch_key" in your home directory (~/.twitch_key)
  26.  
  27. # Twitch Server list http://bashtech.net/twitch/ingest.php
  28. SERVER="live-fra"    # EU server
  29.  
  30. # These will be used only if the -coords option is called.
  31. SET_XY="1030:10"        # Position of the Window on the screen (X,Y)
  32. SET_INRES="45x30"       # Window size (WxH)
  33.  
  34. # Change this to 'true' if you want to go always on FULLSCREEN, this will disable the output.
  35. ALWAYS_FULLSCREEN=false
  36.  
  37. # Change this to 'true' if you want to hide your STREAM_KEY, for security purpose (this will disable most of the output).
  38. # This will not affect the ALWAYS_FULLSCREEN option. ALWAYS_FULLSCREEN will always disable the output.
  39. SUPPRESS_OUTPUT=false
  40.  
  41. # Twitch says it MUST have a 44100 rate, please do not change it unless you know what you are doing.
  42. AUDIO_RATE="44100"
  43. # Twitch says it MUST be 2, please do not change it unless you know what you are doing.
  44. KEY_FRAME="2"
  45.  
  46. # ============================================== END OPTIONS ===================================================
  47. # The following values are changed automatically, so do not change them
  48. TOPXY="0,0"          # Position of the Window (You don't need to change this)
  49. INRES="0x0"          # Game Resolution (You don't need to change this)
  50. LOGLEVEL_ARG=""      # LogLevel, for security purpose (You don't need to change this)
  51. SCREEN_SETUP=0       # Do not change this. it's used for the args.
  52. STREAM_SAVE=0        # Do not change this. it's used for the args.
  53. # ================================================= CHECKS =====================================================
  54. # To see the output.
  55. ECHO_LOG=""
  56.  
  57. # checks to avoid a false "true" where it checks for the webcam
  58. if [ -z "$WEBCAM" ]; then
  59.     ECHO_LOG=$ECHO_LOG"\nYour Webcam has been disabled because there isn't a WEBCAM in the options"
  60.     WEBCAM="/dev/no-webcam"
  61. elif [ -z "$WEBCAM_WH" ]; then
  62. # checks to avoid a fail on loading the Webcam
  63.     ECHO_LOG=$ECHO_LOG"\nYour Webcam has been disabled because there isn't a WEBCAM_WH in the options"
  64.     WEBCAM="/dev/no-webcam"
  65. fi
  66. # Find stream key
  67. if [ -f ~/.twitch_key ]; then
  68.     ECHO_LOG=$ECHO_LOG"\nUsing global twitch key located in home directory"
  69.     STREAM_KEY=$(cat ~/.twitch_key)
  70. else
  71.     if [ -f ./twitch_key ]; then
  72.         ECHO_LOG=$ECHO_LOG"\nUsing twitch key located in current running directory"
  73.         STREAM_KEY=$(cat ./twitch_key)
  74.     else
  75.         echo "Could not locate ~/.twitch_key or twitch_key"
  76.         exit 1
  77.     fi
  78. fi
  79.  
  80.  
  81. # Find script name
  82. SCRIPT_NAME=${0##*/}
  83.  
  84. # Suppress output for security purpose
  85. if [ $SUPPRESS_OUTPUT = true ]; then
  86.     ECHO_LOG=$ECHO_LOG"\nOutput blocked!"
  87.     LOGLEVEL_ARG="-loglevel 0"
  88. fi
  89.  
  90. # checks to avoid fails
  91. if [ -z "$SERVER" ]; then
  92.      SERVER="live"
  93. fi
  94. if [ -z "$OUTRES" ]; then
  95.      OUTRES="1280x720"
  96. fi
  97. if [ -z "$FPS" ]; then
  98.      FPS="30"
  99.      GOP="60"
  100.      GOPMIN="30"
  101. else
  102.      GOP=$(($FPS*2))
  103.      GOPMIN=$FPS
  104. fi
  105. if [ -z "$THREADS" ]; then
  106.      THREADS="4"
  107. fi
  108. if [ -z "$QUALITY" ]; then
  109.      QUALITY="fast"
  110. fi
  111. if [ -z "$CBR" ]; then
  112.      CBR="1000k"
  113. fi
  114. if [ -z "$ALWAYS_FULLSCREEN" ]; then
  115.      ALWAYS_FULLSCREEN=false
  116. fi
  117. if [ -z "$AUDIO_RATE" ]; then
  118.      AUDIO_RATE="44100"
  119. fi
  120. if [ -z "$LOGLEVEL_ARG" ]; then
  121.      LOGLEVEL_ARG=""
  122. fi
  123. if [ -z "$SUPPRESS_OUTPUT" ]; then
  124.      SUPPRESS_OUTPUT=false
  125. fi
  126. if [ -z "$FILE_VIDEO" ]; then
  127.      FILE_VIDEO="video.flv"
  128. fi
  129. if [ ! $SCREEN_SETUP -eq 0 ]; then
  130.      SCREEN_SETUP=0
  131. fi
  132. if [ ! $STREAM_SAVE -eq 0 ]; then
  133.      STREAM_SAVE=0
  134. fi
  135. if [ -z "$STREAM_KEY" ]; then
  136.      ECHO_LOG=$ECHO_LOG"\nSTREAM_KEY not set or there is a problem with it... Aborting."
  137.      ECHO_LOG=$ECHO_LOG"\nCheck if the path to the file or the streaming key is correctly set."
  138.      exit 1
  139. fi
  140.  
  141. # ================================================= CODE =======================================================
  142. # DO NOT CHANGE THE CODE!
  143. MODULE_LOAD1=""
  144. MODULE_LOAD2=""
  145. APP_RETURN=""
  146.  
  147. checkFileExists(){
  148.     if [ -f $FILE_VIDEO ]; then
  149.          i=0
  150.          TMP="OLD_"$i"_"$FILE_VIDEO
  151.          echo "$FILE_VIDEO already exists! finding a new name for the old file"
  152.          while [ -f $TMP ]
  153.          do
  154.             i=$((i+1))
  155.             TMP="OLD_"$i"_"$FILE_VIDEO
  156.         echo "$TMP already exists"
  157.          done
  158.          echo "The old stream $FILE_VIDEO has been renamed as $TMP"
  159.          echo "The new stream will be saved into $FILE_VIDEO"
  160.          mv $FILE_VIDEO $TMP
  161.     fi
  162. }
  163.  
  164. streamWebcam(){
  165.         echo "Webcam found!!"
  166.         echo "You should be online! Check on http://twitch.tv/ (Press CTRL+C to stop)"
  167.         echo " "
  168.         if [ -z "$WEBCAM_XY" ]; then
  169.                 # checks to avoid a fail on loading the Webcam
  170.                 #standard position is: main_w - overlay_w - 10:10
  171.                 WEBCAM_XY="$(($(echo $INRES | awk -F"x" '{ print $1 }') - $(echo $WEBCAM_WH | awk -F":" '{ print $1 }') - 10)):10"
  172.                 echo "There isn't a WEBCAM_XY in the options, i'll generate the standard one ($WEBCAM_XY)"
  173.         fi
  174.         $FFMPEG_PATH -f x11grab -s $INRES -framerate "$FPS" -i :0.0+$TOPXY -f alsa -i pulse -f flv -ac 2 -ar $AUDIO_RATE -vcodec libx264 -filter:v fps="$FPS" -force_key_frames "expr:gte(t,n_forced*$KEY_FRAME)" -g $GOP -keyint_min $GOPMIN -b $CBR -minrate $CBR -maxrate $CBR -pix_fmt yuv420p -s $OUTRES -preset $QUALITY -tune film  -acodec libmp3lame -threads $THREADS -vf "movie=$WEBCAM:f=video4linux2, scale=$WEBCAM_WH , setpts=PTS-STARTPTS [WebCam]; [in] setpts=PTS-STARTPTS [Screen]; [Screen][WebCam] overlay=$WEBCAM_XY [out]" -strict normal -bufsize $CBR $LOGLEVEL_ARG "rtmp://$SERVER.twitch.tv/app/$STREAM_KEY"
  175.         APP_RETURN=$?
  176. }
  177.  
  178. streamNoWebcam(){
  179.         echo "Webcam NOT found!! ("$WEBCAM")"
  180.         echo "You should be online! Check on http://twitch.tv/ (Press CTRL+C to stop)"
  181.         echo " "
  182.         $FFMPEG_PATH -f x11grab -s $INRES -framerate "$FPS" -i :0.0+$TOPXY -f alsa -i pulse -f flv -ac 2 -ar $AUDIO_RATE -vcodec libx264 -filter:v fps="$FPS" -force_key_frames "expr:gte(t,n_forced*$KEY_FRAME)" -g $GOP -keyint_min $GOPMIN  -b:v $CBR -minrate $CBR -maxrate $CBR -pix_fmt yuv420p -s $OUTRES -preset $QUALITY -tune film -acodec libmp3lame -threads $THREADS -strict normal -bufsize $CBR $LOGLEVEL_ARG "rtmp://$SERVER.twitch.tv/app/$STREAM_KEY"
  183.         APP_RETURN=$?
  184. }
  185.  
  186. saveStreamWebcam(){
  187.         echo "Webcam found!!"
  188.         echo "You should be online! Check on http://twitch.tv/ (Press CTRL+C to stop)"
  189.         echo " "
  190.         if [ -z "$WEBCAM_XY" ]; then
  191.                 # checks to avoid a fail on loading the Webcam
  192.                 #standard position is: main_w - overlay_w - 10:10
  193.                 WEBCAM_XY="$(($(echo $INRES | awk -F"x" '{ print $1 }') - $(echo $WEBCAM_WH | awk -F":" '{ print $1 }') - 10)):10"
  194.                 echo "There isn't a WEBCAM_XY in the options, i'll generate the standard one ($WEBCAM_XY)"
  195.         fi
  196.         $FFMPEG_PATH -f x11grab -s $INRES -framerate "$FPS" -i :0.0+$TOPXY -f alsa -i pulse -f flv -ac 2 -ar $AUDIO_RATE -vcodec libx264 -force_key_frames "expr:gte(t,n_forced*$KEY_FRAME)" -g $GOP -keyint_min $GOPMIN -b $CBR -minrate $CBR -maxrate $CBR -pix_fmt yuv420p -s $OUTRES -preset $QUALITY -tune film  -acodec libmp3lame -threads $THREADS -vf "movie=$WEBCAM:f=video4linux2, scale=$WEBCAM_WH , setpts=PTS-STARTPTS [WebCam]; [in] setpts=PTS-STARTPTS [Screen]; [Screen][WebCam] overlay=$WEBCAM_XY [out]" -strict normal -bufsize $CBR $LOGLEVEL_ARG $FILE_VIDEO
  197.         APP_RETURN=$?
  198. }
  199.  
  200. saveStreamNoWebcam(){
  201.         echo "Webcam NOT found!! ("$WEBCAM")"
  202.         echo "You should be online! Check on http://twitch.tv/ (Press CTRL+C to stop)"
  203.         echo " "
  204.         $FFMPEG_PATH -f x11grab -s $INRES -framerate "$FPS" -i :0.0+$TOPXY -f alsa -i pulse -f flv -ac 2 -ar $AUDIO_RATE -vcodec libx264 -filter:v fps="$FPS" -force_key_frames "expr:gte(t,n_forced*$KEY_FRAME)" -g $GOP -keyint_min $GOPMIN  -b:v $CBR -minrate $CBR -maxrate $CBR -pix_fmt yuv420p -s $OUTRES -preset $QUALITY -tune film -acodec libmp3lame -threads $THREADS -strict normal -bufsize $CBR $LOGLEVEL_ARG $FILE_VIDEO
  205.         APP_RETURN=$?
  206. }
  207.  
  208. doDefaults(){
  209.     if [ $ALWAYS_FULLSCREEN = true ]; then
  210.         echo "[+] ALWAYS_FULLSCREEN is ON. Going to fullscreen!"
  211.         echo "[+] Output blocked!"
  212.         TOPXY="0,0"
  213.         INRES=$(xwininfo -root | awk '/geometry/ {print $2}'i | sed -e 's/\+[0-9]//g')
  214.         LOGLEVEL_ARG="-loglevel 0"
  215.         SUPPRESS_OUTPUT=true
  216.     else
  217.         echo "[+] Click, with the mouse, on the Window that you want to Stream"
  218.         rm -f twitch_tmp 2> /dev/null
  219.         xwininfo -stats >> twitch_tmp
  220.         TOPXY=$(cat twitch_tmp | awk 'FNR == 8 {print $4}')","$(cat twitch_tmp | awk 'FNR == 9 {print $4}')
  221.         INRES=$(cat twitch_tmp | awk 'FNR == 12 {print $2}')"x"$(cat twitch_tmp | awk 'FNR == 13 {print $2}')
  222.         rm -f twitch_tmp 2> /dev/null
  223.         echo " "
  224.     fi
  225. }
  226.  
  227. loadModule(){
  228.     MODULE_LOAD1=$(pactl load-module module-null-sink sink_name=GameAudio sink_properties=device.description="GameAudio") # For Game Audio
  229.     MODULE_LOAD2=$(pactl load-module module-null-sink sink_name=MicAudio sink_properties=device.description="MicAudio") # For Mic Audio
  230.     pactl load-module module-device-manager >> /dev/null
  231.     pactl load-module module-loopback sink=GameAudio >> /dev/null
  232.     pactl load-module module-loopback sink=MicAudio >> /dev/null
  233. }
  234.  
  235. unloadModule(){
  236.     echo "Stopping Audio (Don't worry if you see errors here)"
  237.     pactl unload-module $MODULE_LOAD1
  238.     pactl unload-module $MODULE_LOAD2
  239.     pactl unload-module module-device-manager
  240.     pactl unload-module module-null-sink
  241.     pactl unload-module module-loopback
  242.     echo "Exit!"
  243. }
  244.  
  245. showUsage(){
  246.         echo "usage:"
  247.         echo "      "$SCRIPT_NAME" [options]"
  248.         echo "      -h          | show usage screen"
  249.         echo "      -fullscreen | enable the fullscreen"
  250.         echo "                    and disable the output"
  251.         echo "      -window     | enable the window mode"
  252.         echo "      -coords     | set the screen resolution"
  253.         echo "                    by using SET_XY SET_INRES"
  254.         echo "                    defined inside the script"
  255.         echo "      -save       | save the video to a file"
  256.         echo "                    instead of streaming it"
  257.         echo "      -quiet      | disables most of the outputs"
  258. }
  259.  
  260.  
  261. echo " "
  262. echo "Twitch Streamer for Linux ("$SCRIPT_NAME")"
  263. echo "Copyright (c) 2013 - 2014, Giovanni Dante Grazioli (deroad)"
  264. # To be sure to unload everything
  265. trap "unloadModule; exit" SIGHUP SIGINT SIGTERM
  266. echo -e $ECHO_LOG
  267. if [ $# -ge 1 ]; then
  268.     for ARG in "$@"
  269.     do
  270.     if [ $ARG == "-h" ]; then
  271.         showUsage
  272.         exit 1
  273.     elif [ $ARG == "-fullscreen" ]; then
  274.         if [ ! $SCREEN_SETUP -eq 0 ]; then
  275.             continue
  276.         fi
  277.         echo "[+] Going to fullscreen! Output blocked!"
  278.         TOPXY="0,0"
  279.         INRES=$(xwininfo -root | awk '/geometry/ {print $2}'i | sed -e 's/\+[0-9]//g')
  280.         LOGLEVEL_ARG="-loglevel 0"
  281.         SUPPRESS_OUTPUT=true
  282.         SCREEN_SETUP=1
  283.     elif [ $ARG == "-window" ]; then
  284.         if [ $SCREEN_SETUP -eq 1 ]; then
  285.              continue
  286.         fi
  287.         echo "[+] Click, with the mouse, on the Window that you want to Stream"
  288.         rm -f twitch_tmp 2> /dev/null
  289.         xwininfo -stats >> twitch_tmp
  290.         TOPXY=$(cat twitch_tmp | awk 'FNR == 8 {print $4}')","$(cat twitch_tmp | awk 'FNR == 9 {print $4}')
  291.         INRES=$(cat twitch_tmp | awk 'FNR == 12 {print $2}')"x"$(cat twitch_tmp | awk 'FNR == 13 {print $2}')
  292.         rm -f twitch_tmp 2> /dev/null
  293.         SCREEN_SETUP=2
  294.     elif [ $ARG == "-coords" ]; then
  295.         if [ $SCREEN_SETUP -eq 1 ]; then
  296.              continue
  297.         elif [ "$SET_INRES" != "0x0" ]; then
  298.             TOPXY=$SET_XY
  299.             INRES=$SET_INRES
  300.             echo "[+] Using pre-defined screen coords (X,Y = $TOPXY) (WxH = $INRES)."
  301.             SCREEN_SETUP=2
  302.         else
  303.             echo "[+] Could not use pre-defined screen coords, because 'SET_INRES' equals '0x0'."
  304.         fi
  305.     elif [ $ARG == "-save" ]; then
  306.         if [ ! $STREAM_SAVE -eq 0 ]; then
  307.              continue
  308.         fi
  309.         echo "[+] Saving the video into $FILE_VIDEO instead of stream to Twitch.tv"
  310.         STREAM_SAVE=1
  311.     elif [ $ARG == "-quiet" ]; then
  312.         if [ $SUPPRESS_OUTPUT = true ]; then
  313.              continue
  314.         fi
  315.         echo "[+] Quiet Mode"
  316.         LOGLEVEL_ARG="-loglevel 0"
  317.         SUPPRESS_OUTPUT=true
  318.     else
  319.         echo "[+] Unknown param:" $ARG
  320.         showUsage
  321.         exit 1
  322.     fi
  323.     done
  324. elif [ $# -eq 0 ]; then
  325.     doDefaults
  326.     SCREEN_SETUP=1;
  327. else
  328.     # You should never get here.. but who knows..
  329.     echo "[+] There are some unknown params, please check what you wrote!"
  330.     echo "[+] Params: " $@
  331.     showUsage
  332.     exit 1
  333. fi
  334. echo " "
  335. # Setup
  336. echo "Please setup the Audio Output to sink null (something like 'pavucontrol')"
  337. # if you see errors here, please report on github
  338. loadModule
  339.  
  340. # Disable trap
  341. trap - SIGHUP SIGINT SIGTERM
  342. # Checks if the screen got a setup
  343. if [ $SCREEN_SETUP -eq 0 ]; then
  344.     # if not then, get the defaults
  345.     doDefaults
  346. fi
  347. # Checks if the webcam is loaded
  348. if [ $STREAM_SAVE -eq 1 ]; then
  349.      checkFileExists
  350.      if [ -c $WEBCAM ]; then
  351.     saveStreamWebcam
  352.      else
  353.     saveStreamNoWebcam
  354.      fi
  355. else
  356.      if [ -c $WEBCAM ]; then
  357.     streamWebcam
  358.      else
  359.     streamNoWebcam
  360.      fi
  361. fi
  362. # Checks if any error returned
  363. if [ $APP_RETURN -eq 1 ]; then
  364.     if [ $SUPPRESS_OUTPUT = true ]; then
  365.         echo "[+] Something went wrong. check the log without FULLSCREEN or SUPPRESS_OUTPUT options"
  366.     fi
  367. fi
  368. echo " "
  369.  
  370. # Closing..
  371. unloadModule
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement