├── .coveragerc ├── .gitignore ├── .travis.yml ├── CHANGES.rst ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py ├── index.rst └── modules │ ├── chat.rst │ ├── modules.rst │ ├── outputvideo.rst │ └── twitchstream.rst ├── examples ├── __init__.py ├── basic_chat.py ├── basic_video_out.py └── color.py ├── requirements.txt ├── setup.cfg ├── setup.py └── twitchstream ├── __init__.py ├── chat.py ├── outputvideo.py └── tests ├── conftest.py ├── test_chat.py ├── test_inputvideo.py └── test_outputvideo.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = twitchstream/tests/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .coverage 3 | .cache/ 4 | 5 | build 6 | dist 7 | python_twitch_stream.egg-info 8 | 9 | 10 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 11 | 12 | *.iml 13 | 14 | ## Directory-based project format: 15 | .idea/ 16 | # if you remove the above rule, at least ignore the following: 17 | 18 | # User-specific stuff: 19 | # .idea/workspace.xml 20 | # .idea/tasks.xml 21 | # .idea/dictionaries 22 | # .idea/shelf 23 | 24 | # Sensitive or high-churn files: 25 | # .idea/dataSources.ids 26 | # .idea/dataSources.xml 27 | # .idea/sqlDataSources.xml 28 | # .idea/dynamic.xml 29 | # .idea/uiDesigner.xml 30 | 31 | # Gradle: 32 | # .idea/gradle.xml 33 | # .idea/libraries 34 | 35 | # Mongo Explorer plugin: 36 | # .idea/mongoSettings.xml 37 | 38 | ## File-based project format: 39 | *.ipr 40 | *.iws 41 | 42 | ## Plugin-specific files: 43 | 44 | # IntelliJ 45 | /out/ 46 | 47 | # mpeltonen/sbt-idea plugin 48 | .idea_modules/ 49 | 50 | # JIRA plugin 51 | atlassian-ide-plugin.xml 52 | 53 | # Crashlytics plugin (for Android Studio and IntelliJ) 54 | com_crashlytics_export_strings.xml 55 | crashlytics.properties 56 | crashlytics-build.properties 57 | fabric.properties 58 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | sudo: false 3 | python: 4 | - "2.7" 5 | - "3.4" 6 | addons: 7 | apt: 8 | packages: 9 | - ffmpeg 10 | before_install: 11 | - pip install -U pip 12 | install: 13 | - travis_wait travis_retry pip install -r requirements.txt 14 | - travis_retry pip install python-coveralls 15 | - travis_retry python setup.py dev 16 | script: py.test --runslow --cov-config=.coveragerc 17 | after_success: 18 | - coveralls 19 | cache: 20 | - apt 21 | - directories: 22 | - $HOME/.cache/pip 23 | notifications: 24 | email: 25 | on_success: never # default: change 26 | on_failure: always # default: always -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | --------- 3 | 4 | 1.0 (2015-10-30) 5 | ~~~~~~~~~~~~~~~~ 6 | 7 | First release. 8 | Features: 9 | 10 | * Sending Twitch streams (video and audio) 11 | * Reading and sending Twitch chats. 12 | 13 | * core contributors, in alphabetical order: 14 | 15 | * Jonas Degrave (@317070) 16 | 17 | * Special thanks to 18 | 19 | * Frederik Tejner Witte for his `great tutorial `_! 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 Jonas Degrave 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.rst 2 | include *.txt 3 | include LICENSE 4 | 5 | recursive-include twitchstream/tests *.py 6 | include .coveragerc 7 | recursive-include docs *.rst conf.py Makefile -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://readthedocs.org/projects/python-twitch-stream/badge/ 2 | :target: http://python-twitch-stream.readthedocs.org/en/latest/ 3 | 4 | .. image:: https://travis-ci.org/317070/python-twitch-stream.svg 5 | :target: https://travis-ci.org/317070/python-twitch-stream 6 | 7 | .. image:: https://coveralls.io/repos/317070/python-twitch-stream/badge.svg 8 | :target: https://coveralls.io/github/317070/python-twitch-stream 9 | 10 | .. image:: https://img.shields.io/badge/license-MIT-green.svg 11 | :target: https://github.com/Lasagne/Lasagne/blob/master/LICENSE 12 | 13 | Python-Twitch-Stream 14 | ==================== 15 | 16 | Python-twitch-stream is a simple lightweight library, which you can use to 17 | send your python video to twitch and react with the chat in real time. 18 | Its main features are: 19 | 20 | * Supports sending of audio and video in a thread safe way to your twitch 21 | channel. 22 | * Allows to interact with the chat of your channel by sending chat messages 23 | and reading what other users post. 24 | 25 | 26 | Installation 27 | ------------ 28 | 29 | In short, you can install a known compatible version of ffmpeg and 30 | the latest stable version over pip. 31 | 32 | .. code-block:: bash 33 | 34 | pip install python-twitch-stream 35 | 36 | Make sure to also install a recent ffmpeg version: 37 | 38 | .. code-block:: bash 39 | 40 | sudo add-apt-repository ppa:mc3man/trusty-media 41 | sudo apt-get update && sudo apt-get install ffmpeg 42 | 43 | The ffmpeg library needs to be very recent (written in october 2015). 44 | There are plenty of bugs when 45 | running a stream using older versions of ffmpeg or avconv, including but 46 | not limited to 6GB of memory use, problems with the audio and 47 | synchronization of the audio and the video. 48 | 49 | Or alternatively, install the latest 50 | python-twitch-stream development version via: 51 | 52 | .. code-block:: bash 53 | 54 | pip install git+https://github.com/317070/python-twitch-stream 55 | 56 | 57 | Documentation 58 | ------------- 59 | 60 | Documentation is available online: http://python-twitch-stream.readthedocs.org/ 61 | 62 | For support, please use the github issues on `the repository 63 | `_. 64 | 65 | 66 | Example 67 | ------- 68 | 69 | This is a small example which creates a twitch stream which 70 | changes the color of the video according to the colors provided in 71 | the chat. 72 | 73 | .. code-block:: python 74 | 75 | from __future__ import print_function 76 | from twitchstream.outputvideo import TwitchBufferedOutputStream 77 | from twitchstream.chat import TwitchChatStream 78 | import argparse 79 | import time 80 | import numpy as np 81 | 82 | if __name__ == "__main__": 83 | parser = argparse.ArgumentParser(description=__doc__) 84 | required = parser.add_argument_group('required arguments') 85 | required.add_argument('-u', '--username', 86 | help='twitch username', 87 | required=True) 88 | required.add_argument('-o', '--oauth', 89 | help='twitch oauth ' 90 | '(visit https://twitchapps.com/tmi/ ' 91 | 'to create one for your account)', 92 | required=True) 93 | required.add_argument('-s', '--streamkey', 94 | help='twitch streamkey', 95 | required=True) 96 | args = parser.parse_args() 97 | 98 | # load two streams: 99 | # * one stream to send the video 100 | # * one stream to interact with the chat 101 | with TwitchBufferedOutputStream( 102 | twitch_stream_key=args.streamkey, 103 | width=640, 104 | height=480, 105 | fps=30., 106 | enable_audio=True, 107 | verbose=False) as videostream, \ 108 | TwitchChatStream( 109 | username=args.username.lower(), # Must provide a lowercase username. 110 | oauth=args.oauth, 111 | verbose=False) as chatstream: 112 | 113 | # Send a chat message to let everybody know you've arrived 114 | chatstream.send_chat_message("Taking requests!") 115 | 116 | frame = np.zeros((480, 640, 3)) 117 | frequency = 100 118 | last_phase = 0 119 | 120 | # The main loop to create videos 121 | while True: 122 | 123 | # Every loop, call to receive messages. 124 | # This is important, when it is not called, 125 | # Twitch will automatically log you out. 126 | # This call is non-blocking. 127 | received = chatstream.twitch_receive_messages() 128 | 129 | # process all the messages 130 | if received: 131 | for chat_message in received: 132 | print("Got a message '%s' from %s" % ( 133 | chat_message['message'], 134 | chat_message['username'] 135 | )) 136 | if chat_message['message'] == "red": 137 | frame[:, :, :] = np.array( 138 | [1, 0, 0])[None, None, :] 139 | elif chat_message['message'] == "green": 140 | frame[:, :, :] = np.array( 141 | [0, 1, 0])[None, None, :] 142 | elif chat_message['message'] == "blue": 143 | frame[:, :, :] = np.array( 144 | [0, 0, 1])[None, None, :] 145 | elif chat_message['message'].isdigit(): 146 | frequency = int(chat_message['message']) 147 | 148 | # If there are not enough video frames left, 149 | # add some more. 150 | if videostream.get_video_frame_buffer_state() < 30: 151 | videostream.send_video_frame(frame) 152 | 153 | # If there are not enough audio fragments left, 154 | # add some more, but take care to stay in sync with 155 | # the video! Audio and video buffer separately, 156 | # so they will go out of sync if the number of video 157 | # frames does not match the number of audio samples! 158 | elif videostream.get_audio_buffer_state() < 30: 159 | x = np.linspace(last_phase, 160 | last_phase + 161 | frequency*2*np.pi/videostream.fps, 162 | int(44100 / videostream.fps) + 1) 163 | last_phase = x[-1] 164 | audio = np.sin(x[:-1]) 165 | videostream.send_audio(audio, audio) 166 | 167 | # If nothing is happening, it is okay to sleep for a while 168 | # and take some pressure of the CPU. But not too long, if 169 | # the buffers run dry, audio and video will go out of sync. 170 | else: 171 | time.sleep(.001) 172 | 173 | 174 | For a fully-functional example, see `examples/color.py `_, 175 | and check the `Tutorial 176 | `_ for in-depth 177 | explanations of the same. More examples are maintained in the `examples directory 178 | `_. 179 | 180 | 181 | Development 182 | ----------- 183 | 184 | Python-twitch-stream is a work in progress, but is stable. Feel free to ask 185 | for features or add pull-requests with updates on the code. 186 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-twitch-stream.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-twitch-stream.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python-twitch-stream" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-twitch-stream" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # python-twitch-stream documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Oct 21 19:45:57 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.autosummary', 34 | 'sphinx.ext.doctest', 35 | 'sphinx.ext.mathjax', 36 | 'sphinx.ext.linkcode', # link to github, see linkcode_resolve() below 37 | 'numpydoc', 38 | ] 39 | 40 | # see http://stackoverflow.com/q/12206334/562769 41 | numpydoc_show_class_members = False 42 | 43 | # Add any paths that contain templates here, relative to this directory. 44 | templates_path = ['_templates'] 45 | 46 | # The suffix of source filenames. 47 | source_suffix = '.rst' 48 | 49 | # The encoding of source files. 50 | #source_encoding = 'utf-8-sig' 51 | 52 | # The master toctree document. 53 | master_doc = 'index' 54 | 55 | # General information about the project. 56 | project = u'python-twitch-stream' 57 | copyright = u'2015, Jonas Degrave' 58 | 59 | # The version info for the project you're documenting, acts as replacement for 60 | # |version| and |release|, also used in various other places throughout the 61 | # built documents. 62 | # 63 | # The short X.Y version. 64 | import twitchstream 65 | # The short X.Y version. 66 | version = '.'.join(twitchstream.__version__.split('.', 2)[:2]) 67 | # The full version, including alpha/beta/rc tags. 68 | release = twitchstream.__version__ 69 | 70 | version = '0.0.dev1' 71 | # The full version, including alpha/beta/rc tags. 72 | release = '0.0.dev1' 73 | 74 | # The language for content autogenerated by Sphinx. Refer to documentation 75 | # for a list of supported languages. 76 | #language = None 77 | 78 | # There are two options for replacing |today|: either, you set today to some 79 | # non-false value, then it is used: 80 | #today = '' 81 | # Else, today_fmt is used as the format for a strftime call. 82 | #today_fmt = '%B %d, %Y' 83 | 84 | # List of patterns, relative to source directory, that match files and 85 | # directories to ignore when looking for source files. 86 | exclude_patterns = ['_build'] 87 | 88 | # The reST default role (used for this markup: `text`) to use for all 89 | # documents. 90 | #default_role = None 91 | 92 | # If true, '()' will be appended to :func: etc. cross-reference text. 93 | #add_function_parentheses = True 94 | 95 | # If true, the current module name will be prepended to all description 96 | # unit titles (such as .. function::). 97 | #add_module_names = True 98 | 99 | # If true, sectionauthor and moduleauthor directives will be shown in the 100 | # output. They are ignored by default. 101 | #show_authors = False 102 | 103 | # The name of the Pygments (syntax highlighting) style to use. 104 | pygments_style = 'sphinx' 105 | 106 | # A list of ignored prefixes for module index sorting. 107 | #modindex_common_prefix = [] 108 | 109 | # If true, keep warnings as "system message" paragraphs in the built documents. 110 | #keep_warnings = False 111 | 112 | # Resolve function for the linkcode extension. 113 | def linkcode_resolve(domain, info): 114 | """Resolve the links to github matching the documentation""" 115 | def find_source(): 116 | """try to find the file and line number, 117 | based on code from numpy""" 118 | # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286 119 | obj = sys.modules[info['module']] 120 | for part in info['fullname'].split('.'): 121 | obj = getattr(obj, part) 122 | import inspect 123 | import os 124 | fn = inspect.getsourcefile(obj) 125 | fn = os.path.relpath(fn, 126 | start=os.path.dirname( 127 | twitchstream.__file__) 128 | ) 129 | source, lineno = inspect.getsourcelines(obj) 130 | return fn, lineno, lineno + len(source) - 1 131 | 132 | if domain != 'py' or not info['module']: 133 | return None 134 | try: 135 | filename = 'twitchstream/%s#L%d-L%d' % find_source() 136 | except Exception: 137 | filename = info['module'].replace('.', '/') + '.py' 138 | tag = 'master' if 'dev' in release else ('v' + release) 139 | return "https://github.com/317070/python-twitch-stream/blob/%s/%s" % (tag, filename) 140 | 141 | 142 | # -- Options for HTML output ---------------------------------------------- 143 | 144 | # The theme to use for HTML and HTML Help pages. See the documentation for 145 | # a list of builtin themes. 146 | html_theme = 'default' 147 | 148 | # Theme options are theme-specific and customize the look and feel of a theme 149 | # further. For a list of options available for each theme, see the 150 | # documentation. 151 | #html_theme_options = {} 152 | 153 | # Add any paths that contain custom themes here, relative to this directory. 154 | #html_theme_path = [] 155 | 156 | # The name for this set of Sphinx documents. If None, it defaults to 157 | # " v documentation". 158 | #html_title = None 159 | 160 | # A shorter title for the navigation bar. Default is the same as html_title. 161 | #html_short_title = None 162 | 163 | # The name of an image file (relative to this directory) to place at the top 164 | # of the sidebar. 165 | #html_logo = None 166 | 167 | # The name of an image file (within the static path) to use as favicon of the 168 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 169 | # pixels large. 170 | #html_favicon = None 171 | 172 | # Add any paths that contain custom static files (such as style sheets) here, 173 | # relative to this directory. They are copied after the builtin static files, 174 | # so a file named "default.css" will overwrite the builtin "default.css". 175 | html_static_path = ['_static'] 176 | 177 | # Add any extra paths that contain custom files (such as robots.txt or 178 | # .htaccess) here, relative to this directory. These files are copied 179 | # directly to the root of the documentation. 180 | #html_extra_path = [] 181 | 182 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 183 | # using the given strftime format. 184 | #html_last_updated_fmt = '%b %d, %Y' 185 | 186 | # If true, SmartyPants will be used to convert quotes and dashes to 187 | # typographically correct entities. 188 | #html_use_smartypants = True 189 | 190 | # Custom sidebar templates, maps document names to template names. 191 | #html_sidebars = {} 192 | 193 | # Additional templates that should be rendered to pages, maps page names to 194 | # template names. 195 | #html_additional_pages = {} 196 | 197 | # If false, no module index is generated. 198 | #html_domain_indices = True 199 | 200 | # If false, no index is generated. 201 | #html_use_index = True 202 | 203 | # If true, the index is split into individual pages for each letter. 204 | #html_split_index = False 205 | 206 | # If true, links to the reST sources are added to the pages. 207 | #html_show_sourcelink = True 208 | 209 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 210 | #html_show_sphinx = True 211 | 212 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 213 | #html_show_copyright = True 214 | 215 | # If true, an OpenSearch description file will be output, and all pages will 216 | # contain a tag referring to it. The value of this option must be the 217 | # base URL from which the finished HTML is served. 218 | #html_use_opensearch = '' 219 | 220 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 221 | #html_file_suffix = None 222 | 223 | # Output file base name for HTML help builder. 224 | htmlhelp_basename = 'python-twitch-streamdoc' 225 | 226 | 227 | # -- Options for LaTeX output --------------------------------------------- 228 | 229 | latex_elements = { 230 | # The paper size ('letterpaper' or 'a4paper'). 231 | #'papersize': 'letterpaper', 232 | 233 | # The font size ('10pt', '11pt' or '12pt'). 234 | #'pointsize': '10pt', 235 | 236 | # Additional stuff for the LaTeX preamble. 237 | #'preamble': '', 238 | } 239 | 240 | # Grouping the document tree into LaTeX files. List of tuples 241 | # (source start file, target name, title, 242 | # author, documentclass [howto, manual, or own class]). 243 | latex_documents = [ 244 | ('index', 'python-twitch-stream.tex', u'python-twitch-stream Documentation', 245 | u'Jonas Degrave', 'manual'), 246 | ] 247 | 248 | # The name of an image file (relative to this directory) to place at the top of 249 | # the title page. 250 | #latex_logo = None 251 | 252 | # For "manual" documents, if this is true, then toplevel headings are parts, 253 | # not chapters. 254 | #latex_use_parts = False 255 | 256 | # If true, show page references after internal links. 257 | #latex_show_pagerefs = False 258 | 259 | # If true, show URL addresses after external links. 260 | #latex_show_urls = False 261 | 262 | # Documents to append as an appendix to all manuals. 263 | #latex_appendices = [] 264 | 265 | # If false, no module index is generated. 266 | #latex_domain_indices = True 267 | 268 | 269 | # -- Options for manual page output --------------------------------------- 270 | 271 | # One entry per manual page. List of tuples 272 | # (source start file, name, description, authors, manual section). 273 | man_pages = [ 274 | ('index', 'python-twitch-stream', u'python-twitch-stream Documentation', 275 | [u'Jonas Degrave'], 1) 276 | ] 277 | 278 | # If true, show URL addresses after external links. 279 | #man_show_urls = False 280 | 281 | 282 | # -- Options for Texinfo output ------------------------------------------- 283 | 284 | # Grouping the document tree into Texinfo files. List of tuples 285 | # (source start file, target name, title, author, 286 | # dir menu entry, description, category) 287 | texinfo_documents = [ 288 | ('index', 'python-twitch-stream', u'python-twitch-stream Documentation', 289 | u'Jonas Degrave', 'python-twitch-stream', 'Interface for Twitch video and chat streams.', 290 | 'Miscellaneous'), 291 | ] 292 | 293 | # Documents to append as an appendix to all manuals. 294 | #texinfo_appendices = [] 295 | 296 | # If false, no module index is generated. 297 | #texinfo_domain_indices = True 298 | 299 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 300 | #texinfo_show_urls = 'footnote' 301 | 302 | # If true, do not generate a @detailmenu in the "Top" node's menu. 303 | #texinfo_no_detailmenu = False 304 | 305 | 306 | # Example configuration for intersphinx: refer to the Python standard library. 307 | intersphinx_mapping = {'http://docs.python.org/': None} 308 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. python-twitch-stream documentation master file, created by 2 | sphinx-quickstart on Wed Oct 21 19:45:57 2015. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to python-twitch-stream's documentation! 7 | ================================================ 8 | 9 | Python-twitch-stream is a simple lightweight library, which you can use to 10 | send your python video to twitch and react with the chat in real time. 11 | Its main features are: 12 | 13 | * Supports sending of audio and video in a thread safe way to your twitch 14 | channel. 15 | * Allows to interact with the chat of your channel by sending chat messages 16 | and reading what other users post. 17 | 18 | There is a complete tutorial available at `Tutorial 19 | `_. 20 | 21 | Installation 22 | ------------ 23 | 24 | In short, you can install the latest stable version over pip. 25 | 26 | .. code-block:: bash 27 | 28 | pip install python-twitch-stream 29 | 30 | Make sure to also install a recent ffmpeg version: 31 | 32 | .. code-block:: bash 33 | 34 | sudo add-apt-repository ppa:mc3man/trusty-media 35 | sudo apt-get update && sudo apt-get install ffmpeg 36 | 37 | The ffmpeg library needs to be very recent (written in october 2015). 38 | There are plenty of bugs when 39 | running a stream using older versions of ffmpeg or avconv, including but 40 | not limited to 6GB of memory use, problems with the audio and 41 | synchronization of the audio and the video. 42 | 43 | Or alternatively, install the latest 44 | python-twitch-stream development version via: 45 | 46 | .. code-block:: bash 47 | 48 | pip install git+https://github.com/317070/python-twitch-stream 49 | 50 | 51 | Support 52 | ------- 53 | 54 | For support, please use the github issues on `the repository 55 | `_. 56 | 57 | 58 | Contents 59 | ======== 60 | .. toctree:: 61 | :maxdepth: 2 62 | 63 | modules/chat 64 | modules/inputvideo 65 | modules/outputvideo 66 | -------------------------------------------------------------------------------- /docs/modules/chat.rst: -------------------------------------------------------------------------------- 1 | :mod:`twitchstream.chat` 2 | =============================== 3 | 4 | .. automodule:: twitchstream.chat 5 | :members: 6 | :undoc-members: 7 | -------------------------------------------------------------------------------- /docs/modules/modules.rst: -------------------------------------------------------------------------------- 1 | twitchstream 2 | ============ 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | twitchstream 8 | -------------------------------------------------------------------------------- /docs/modules/outputvideo.rst: -------------------------------------------------------------------------------- 1 | :mod:`twitchstream.outputvideo` 2 | =============================== 3 | 4 | .. automodule:: twitchstream.outputvideo 5 | :members: 6 | :undoc-members: 7 | -------------------------------------------------------------------------------- /docs/modules/twitchstream.rst: -------------------------------------------------------------------------------- 1 | twitchstream package 2 | ==================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | twitchstream.chat module 8 | ------------------------ 9 | 10 | .. automodule:: twitchstream.chat 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | twitchstream.inputvideo module 16 | ------------------------------ 17 | 18 | .. automodule:: twitchstream.inputvideo 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | twitchstream.outputvideo module 24 | ------------------------------- 25 | 26 | .. automodule:: twitchstream.outputvideo 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | 32 | Module contents 33 | --------------- 34 | 35 | .. automodule:: twitchstream 36 | :members: 37 | :undoc-members: 38 | :show-inheritance: 39 | -------------------------------------------------------------------------------- /examples/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Examples of the twitchstream library 5 | """ -------------------------------------------------------------------------------- /examples/basic_chat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | This is a small example which connects to a user's chat channel to 5 | send and receive the messages posted there 6 | """ 7 | from __future__ import print_function 8 | from twitchstream.outputvideo import TwitchOutputStreamRepeater 9 | from twitchstream.chat import TwitchChatStream 10 | import argparse 11 | import time 12 | import numpy as np 13 | 14 | if __name__ == "__main__": 15 | parser = argparse.ArgumentParser(description=__doc__) 16 | required = parser.add_argument_group('required arguments') 17 | required.add_argument('-u', '--username', 18 | help='twitch username', 19 | required=True) 20 | required.add_argument('-o', '--oauth', 21 | help='twitch oauth ' 22 | '(visit https://twitchapps.com/tmi/ ' 23 | 'to create one for your account)', 24 | required=True) 25 | args = parser.parse_args() 26 | 27 | # Launch a verbose (!) twitch stream 28 | with TwitchChatStream(username=args.username, 29 | oauth=args.oauth, 30 | verbose=True) as chatstream: 31 | 32 | # Send a message to this twitch stream 33 | chatstream.send_chat_message("I'm reading this!") 34 | 35 | # Continuously check if messages are received (every ~10s) 36 | # This is necessary, if not, the chat stream will close itself 37 | # after a couple of minutes (due to ping messages from twitch) 38 | while True: 39 | received = chatstream.twitch_receive_messages() 40 | if received: 41 | print("received:", received) 42 | time.sleep(1) 43 | -------------------------------------------------------------------------------- /examples/basic_video_out.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | This is a small example which creates a twitch stream to connect with 5 | and changes the color of the video according to the colors provided in 6 | the chat. 7 | """ 8 | from __future__ import print_function 9 | from twitchstream.outputvideo import TwitchBufferedOutputStream 10 | import argparse 11 | import numpy as np 12 | 13 | if __name__ == "__main__": 14 | parser = argparse.ArgumentParser(description=__doc__) 15 | required = parser.add_argument_group('required arguments') 16 | required.add_argument('-s', '--streamkey', 17 | help='twitch streamkey', 18 | required=True) 19 | args = parser.parse_args() 20 | 21 | with TwitchBufferedOutputStream( 22 | twitch_stream_key=args.streamkey, 23 | width=640, 24 | height=480, 25 | fps=30., 26 | verbose=True, 27 | enable_audio=True) as videostream: 28 | 29 | frame = np.zeros((480, 640, 3)) 30 | 31 | while True: 32 | if videostream.get_video_frame_buffer_state() < 30: 33 | frame = np.random.rand(480, 640, 3) 34 | videostream.send_video_frame(frame) 35 | 36 | if videostream.get_audio_buffer_state() < 30: 37 | left_audio = np.random.randn(1470) 38 | right_audio = np.random.randn(1470) 39 | videostream.send_audio(left_audio, right_audio) 40 | 41 | -------------------------------------------------------------------------------- /examples/color.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | This is a small example which creates a twitch stream to connect with 5 | and changes the color of the video according to the colors provided in 6 | the chat. 7 | """ 8 | from __future__ import print_function 9 | from twitchstream.outputvideo import TwitchBufferedOutputStream 10 | from twitchstream.chat import TwitchChatStream 11 | import argparse 12 | import time 13 | import numpy as np 14 | 15 | if __name__ == "__main__": 16 | parser = argparse.ArgumentParser(description=__doc__) 17 | required = parser.add_argument_group('required arguments') 18 | required.add_argument('-u', '--username', 19 | help='twitch username', 20 | required=True) 21 | required.add_argument('-o', '--oauth', 22 | help='twitch oauth ' 23 | '(visit https://twitchapps.com/tmi/ ' 24 | 'to create one for your account)', 25 | required=True) 26 | required.add_argument('-s', '--streamkey', 27 | help='twitch streamkey', 28 | required=True) 29 | args = parser.parse_args() 30 | 31 | # load two streams: 32 | # * one stream to send the video 33 | # * one stream to interact with the chat 34 | with TwitchBufferedOutputStream( 35 | twitch_stream_key=args.streamkey, 36 | width=640, 37 | height=480, 38 | fps=30., 39 | enable_audio=True, 40 | verbose=False) as videostream, \ 41 | TwitchChatStream( 42 | username=args.username, 43 | oauth=args.oauth, 44 | verbose=False) as chatstream: 45 | 46 | # Send a chat message to let everybody know you've arrived 47 | chatstream.send_chat_message("Taking requests!") 48 | 49 | frame = np.zeros((480, 640, 3)) 50 | frequency = 100 51 | last_phase = 0 52 | 53 | # The main loop to create videos 54 | while True: 55 | 56 | # Every loop, call to receive messages. 57 | # This is important, when it is not called, 58 | # Twitch will automatically log you out. 59 | # This call is non-blocking. 60 | received = chatstream.twitch_receive_messages() 61 | 62 | # process all the messages 63 | if received: 64 | for chat_message in received: 65 | print("Got a message '%s' from %s" % ( 66 | chat_message['message'], 67 | chat_message['username'] 68 | )) 69 | if chat_message['message'] == "red": 70 | frame[:, :, :] = np.array( 71 | [1, 0, 0])[None, None, :] 72 | elif chat_message['message'] == "green": 73 | frame[:, :, :] = np.array( 74 | [0, 1, 0])[None, None, :] 75 | elif chat_message['message'] == "blue": 76 | frame[:, :, :] = np.array( 77 | [0, 0, 1])[None, None, :] 78 | elif chat_message['message'].isdigit(): 79 | frequency = int(chat_message['message']) 80 | 81 | # If there are not enough video frames left, 82 | # add some more. 83 | if videostream.get_video_frame_buffer_state() < 30: 84 | videostream.send_video_frame(frame) 85 | 86 | # If there are not enough audio fragments left, 87 | # add some more, but take care to stay in sync with 88 | # the video! Audio and video buffer separately, 89 | # so they will go out of sync if the number of video 90 | # frames does not match the number of audio samples! 91 | elif videostream.get_audio_buffer_state() < 30: 92 | x = np.linspace(last_phase, 93 | last_phase + 94 | frequency*2*np.pi/videostream.fps, 95 | int(44100 / videostream.fps) + 1) 96 | last_phase = x[-1] 97 | audio = np.sin(x[:-1]) 98 | videostream.send_audio(audio, audio) 99 | 100 | # If nothing is happening, it is okay to sleep for a while 101 | # and take some pressure of the CPU. But not too long, if 102 | # the buffers run dry, audio and video will go out of sync. 103 | else: 104 | time.sleep(.001) 105 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | mock 3 | numpydoc 4 | pep8==1.6.2 5 | pytest 6 | pytest-cov 7 | pytest-pep8 8 | Jinja2==2.7.3 9 | Sphinx==1.2.3 10 | sphinx_rtd_theme 11 | requests -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | dev = develop easy_install python-twitch-stream[testing] 3 | 4 | [pytest] 5 | addopts = 6 | -v --doctest-modules 7 | --cov=twitchstream --cov-report=term-missing 8 | --pep8 9 | twitchstream/ 10 | python_files = test_*.py -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | The setup file for installing the library 5 | """ 6 | import os 7 | from setuptools import find_packages 8 | from setuptools import setup 9 | from twitchstream import __version__ as VERSION 10 | version = VERSION 11 | 12 | here = os.path.abspath(os.path.dirname(__file__)) 13 | try: 14 | README = open(os.path.join(here, 'README.rst')).read() 15 | CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() 16 | except IOError: 17 | README = CHANGES = '' 18 | 19 | 20 | 21 | install_requires = [ 22 | 'numpy', 23 | ] 24 | 25 | tests_require = [ 26 | 'mock', 27 | 'pytest', 28 | 'pytest-cov', 29 | 'pytest-pep8', 30 | ] 31 | 32 | setup( 33 | name="python-twitch-stream", 34 | version=version, 35 | description="An interface to the Twitch website, to interact with " 36 | "their video and chat", 37 | long_description="\n\n".join([README, CHANGES]), 38 | classifiers=[ 39 | "Development Status :: 5 - Production/Stable", 40 | "Intended Audience :: Developers", 41 | "Intended Audience :: Science/Research", 42 | "Intended Audience :: Other Audience", 43 | "License :: OSI Approved :: MIT License", 44 | "Natural Language :: English", 45 | "Operating System :: POSIX :: Linux", 46 | "Programming Language :: Python :: 2.7", 47 | "Programming Language :: Python :: 3.4", 48 | "Topic :: Communications :: Chat :: Internet Relay Chat", 49 | "Topic :: Multimedia :: Video" 50 | ], 51 | keywords="twitch, stream, video, chat", 52 | author="Jonas Degrave", 53 | author_email="erstaateenknolraapinmijntuin+pythontwitch@gmail.com", 54 | url="https://github.com/317070/python-twitch-stream", 55 | license="MIT", 56 | packages=find_packages(), 57 | include_package_data=False, 58 | zip_safe=False, 59 | install_requires=install_requires, 60 | extras_require={ 61 | 'testing': tests_require, 62 | }, 63 | ) 64 | -------------------------------------------------------------------------------- /twitchstream/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Tools interface with Twitch using python, concretely, interfacing with 5 | the chat and video streams. 6 | """ 7 | __version__ = "1.0.2c" 8 | -------------------------------------------------------------------------------- /twitchstream/chat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This file contains the python code used to interface with the Twitch 6 | chat. Twitch chat is IRC-based, so it is basically an IRC-bot, but with 7 | special features for Twitch, such as congestion control built in. 8 | """ 9 | from __future__ import print_function 10 | import time 11 | import socket 12 | import re 13 | import fcntl 14 | import os 15 | import errno 16 | 17 | 18 | class TwitchChatStream(object): 19 | """ 20 | The TwitchChatStream is used for interfacing with the Twitch chat of 21 | a channel. To use this, an oauth-account (of the user chatting) 22 | should be created. At the moment of writing, this can be done here: 23 | https://twitchapps.com/tmi/ 24 | 25 | :param username: Twitch username 26 | :type username: string 27 | :param oauth: oauth for logging in (see https://twitchapps.com/tmi/) 28 | :type oauth: string 29 | :param verbose: show all stream messages on stdout (for debugging) 30 | :type verbose: boolean 31 | """ 32 | 33 | def __init__(self, username, oauth, verbose=False): 34 | """Create a new stream object, and try to connect.""" 35 | self.username = username 36 | self.oauth = oauth 37 | self.verbose = verbose 38 | self.current_channel = "" 39 | self.last_sent_time = time.time() 40 | self.buffer = [] 41 | self.s = None 42 | 43 | def __enter__(self): 44 | self.connect() 45 | return self 46 | 47 | def __exit__(self, type, value, traceback): 48 | self.s.close() 49 | 50 | @staticmethod 51 | def _logged_in_successful(data): 52 | """ 53 | Test the login status from the returned communication of the 54 | server. 55 | 56 | :param data: bytes received from server during login 57 | :type data: list of bytes 58 | 59 | :return boolean, True when you are logged in. 60 | """ 61 | if re.match(r'^:(testserver\.local|tmi\.twitch\.tv)' 62 | r' NOTICE \* :' 63 | r'(Login unsuccessful|Error logging in)*$', 64 | data.strip()): 65 | return False 66 | else: 67 | return True 68 | 69 | @staticmethod 70 | def _check_has_ping(data): 71 | """ 72 | Check if the data from the server contains a request to ping. 73 | 74 | :param data: the byte string from the server 75 | :type data: list of bytes 76 | :return: True when there is a request to ping, False otherwise 77 | """ 78 | return re.match( 79 | r'^PING :tmi\.twitch\.tv$', data) 80 | 81 | @staticmethod 82 | def _check_has_channel(data): 83 | """ 84 | Check if the data from the server contains a channel switch. 85 | 86 | :param data: the byte string from the server 87 | :type data: list of bytes 88 | :return: Name of channel when new channel, False otherwise 89 | """ 90 | return re.findall( 91 | r'^:[a-zA-Z0-9_]+\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+' 92 | r'\.tmi\.twitch\.tv ' 93 | r'JOIN #([a-zA-Z0-9_]+)$', data) 94 | 95 | @staticmethod 96 | def _check_has_message(data): 97 | """ 98 | Check if the data from the server contains a message a user 99 | typed in the chat. 100 | 101 | :param data: the byte string from the server 102 | :type data: list of bytes 103 | :return: returns iterator over these messages 104 | """ 105 | return re.match(r'^:[a-zA-Z0-9_]+\![a-zA-Z0-9_]+@[a-zA-Z0-9_]+' 106 | r'\.tmi\.twitch\.tv ' 107 | r'PRIVMSG #[a-zA-Z0-9_]+ :.+$', data) 108 | 109 | def connect(self): 110 | """ 111 | Connect to Twitch 112 | """ 113 | 114 | # Do not use non-blocking stream, they are not reliably 115 | # non-blocking 116 | # s.setblocking(False) 117 | # s.settimeout(1.0) 118 | 119 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 120 | connect_host = "irc.twitch.tv" 121 | connect_port = 6667 122 | try: 123 | s.connect((connect_host, connect_port)) 124 | except (Exception, IOError): 125 | print("Unable to create a socket to %s:%s" % ( 126 | connect_host, 127 | connect_port)) 128 | raise # unexpected, because it is a blocking socket 129 | 130 | # Connected to twitch 131 | # Sending our details to twitch... 132 | s.send(('PASS %s\r\n' % self.oauth).encode('utf-8')) 133 | s.send(('NICK %s\r\n' % self.username).encode('utf-8')) 134 | if self.verbose: 135 | print('PASS %s\r\n' % self.oauth) 136 | print('NICK %s\r\n' % self.username) 137 | 138 | received = s.recv(1024).decode() 139 | if self.verbose: 140 | print(received) 141 | if not TwitchChatStream._logged_in_successful(received): 142 | # ... and they didn't accept our details 143 | raise IOError("Twitch did not accept the username-oauth " 144 | "combination") 145 | else: 146 | # ... and they accepted our details 147 | # Connected to twitch.tv! 148 | # now make this socket non-blocking on the OS-level 149 | fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK) 150 | if self.s is not None: 151 | self.s.close() # close the previous socket 152 | self.s = s # store the new socket 153 | self.join_channel(self.username) 154 | 155 | # Wait until we have switched channels 156 | while self.current_channel != self.username: 157 | self.twitch_receive_messages() 158 | 159 | def _push_from_buffer(self): 160 | """ 161 | Push a message on the stack to the IRC stream. 162 | This is necessary to avoid Twitch overflow control. 163 | """ 164 | if len(self.buffer) > 0: 165 | if time.time() - self.last_sent_time > 5: 166 | try: 167 | message = self.buffer.pop(0) 168 | self.s.send(message.encode('utf-8')) 169 | if self.verbose: 170 | print(message) 171 | finally: 172 | self.last_sent_time = time.time() 173 | 174 | def _send(self, message): 175 | """ 176 | Send a message to the IRC stream 177 | 178 | :param message: the message to be sent. 179 | :type message: string 180 | """ 181 | if len(message) > 0: 182 | self.buffer.append(message + "\n") 183 | 184 | def _send_pong(self): 185 | """ 186 | Send a pong message, usually in reply to a received ping message 187 | """ 188 | self._send("PONG") 189 | 190 | def join_channel(self, channel): 191 | """ 192 | Join a different chat channel on Twitch. 193 | Note, this function returns immediately, but the switch might 194 | take a moment 195 | 196 | :param channel: name of the channel (without #) 197 | """ 198 | self.s.send(('JOIN #%s\r\n' % channel).encode('utf-8')) 199 | if self.verbose: 200 | print('JOIN #%s\r\n' % channel) 201 | 202 | def send_chat_message(self, message): 203 | """ 204 | Send a chat message to the server. 205 | 206 | :param message: String to send (don't use \\n) 207 | """ 208 | self._send("PRIVMSG #{0} :{1}".format(self.username, message)) 209 | 210 | def _parse_message(self, data): 211 | """ 212 | Parse the bytes received from the socket. 213 | 214 | :param data: the bytes received from the socket 215 | :return: 216 | """ 217 | if TwitchChatStream._check_has_ping(data): 218 | self._send_pong() 219 | if TwitchChatStream._check_has_channel(data): 220 | self.current_channel = \ 221 | TwitchChatStream._check_has_channel(data)[0] 222 | 223 | if TwitchChatStream._check_has_message(data): 224 | return { 225 | 'channel': re.findall(r'^:.+![a-zA-Z0-9_]+' 226 | r'@[a-zA-Z0-9_]+' 227 | r'.+ ' 228 | r'PRIVMSG (.*?) :', 229 | data)[0], 230 | 'username': re.findall(r'^:([a-zA-Z0-9_]+)!', data)[0], 231 | 'message': re.findall(r'PRIVMSG #[a-zA-Z0-9_]+ :(.+)', 232 | data)[0] 233 | } 234 | else: 235 | return None 236 | 237 | def twitch_receive_messages(self): 238 | """ 239 | Call this function to process everything received by the socket 240 | This needs to be called frequently enough (~10s) Twitch logs off 241 | users not replying to ping commands. 242 | 243 | :return: list of chat messages received. Each message is a dict 244 | with the keys ['channel', 'username', 'message'] 245 | """ 246 | self._push_from_buffer() 247 | result = [] 248 | while True: 249 | # process the complete buffer, until no data is left no more 250 | try: 251 | msg = self.s.recv(4096).decode() # NON-BLOCKING RECEIVE! 252 | except socket.error as e: 253 | err = e.args[0] 254 | if err == errno.EAGAIN or err == errno.EWOULDBLOCK: 255 | # There is no more data available to read 256 | return result 257 | else: 258 | # a "real" error occurred 259 | # import traceback 260 | # import sys 261 | # print(traceback.format_exc()) 262 | # print("Trying to recover...") 263 | self.connect() 264 | return result 265 | else: 266 | if self.verbose: 267 | print(msg) 268 | rec = [self._parse_message(line) 269 | for line in filter(None, msg.split('\r\n'))] 270 | rec = [r for r in rec if r] # remove Nones 271 | result.extend(rec) 272 | -------------------------------------------------------------------------------- /twitchstream/outputvideo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This file contains the classes used to send videostreams to Twitch 6 | """ 7 | from __future__ import print_function, division 8 | import numpy as np 9 | import subprocess 10 | import signal 11 | import threading 12 | import sys 13 | try: 14 | import Queue as queue 15 | except ImportError: 16 | import queue 17 | import time 18 | import os 19 | 20 | import requests 21 | 22 | AUDIORATE = 44100 23 | 24 | 25 | class TwitchOutputStream(object): 26 | """ 27 | Initialize a TwitchOutputStream object and starts the pipe. 28 | The stream is only started on the first frame. 29 | 30 | :param twitch_stream_key: 31 | :type twitch_stream_key: 32 | :param width: the width of the videostream (in pixels) 33 | :type width: int 34 | :param height: the height of the videostream (in pixels) 35 | :type height: int 36 | :param fps: the number of frames per second of the videostream 37 | :type fps: float 38 | :param enable_audio: whether there will be sound or not 39 | :type enable_audio: boolean 40 | :param ffmpeg_binary: the binary to use to create a videostream 41 | This is usually ffmpeg, but avconv on some (older) platforms 42 | :type ffmpeg_binary: String 43 | :param verbose: show ffmpeg output in stdout 44 | :type verbose: boolean 45 | """ 46 | def __init__(self, 47 | twitch_stream_key, 48 | width=640, 49 | height=480, 50 | fps=30., 51 | ffmpeg_binary="ffmpeg", 52 | enable_audio=False, 53 | verbose=False): 54 | self.twitch_stream_key = twitch_stream_key 55 | self.width = width 56 | self.height = height 57 | self.fps = fps 58 | self.ffmpeg_process = None 59 | self.audio_pipe = None 60 | self.ffmpeg_binary = ffmpeg_binary 61 | self.verbose = verbose 62 | self.audio_enabled = enable_audio 63 | try: 64 | self.reset() 65 | except OSError: 66 | print("There seems to be no %s available" % ffmpeg_binary) 67 | if ffmpeg_binary == "ffmpeg": 68 | print("ffmpeg can be installed using the following" 69 | "commands") 70 | print("> sudo add-apt-repository " 71 | "ppa:mc3man/trusty-media") 72 | print("> sudo apt-get update && " 73 | "sudo apt-get install ffmpeg") 74 | sys.exit(1) 75 | 76 | def reset(self): 77 | """ 78 | Reset the videostream by restarting ffmpeg 79 | """ 80 | 81 | if self.ffmpeg_process is not None: 82 | # Close the previous stream 83 | try: 84 | self.ffmpeg_process.send_signal(signal.SIGINT) 85 | except OSError: 86 | pass 87 | 88 | command = [] 89 | command.extend([ 90 | self.ffmpeg_binary, 91 | '-loglevel', 'verbose', 92 | '-y', # overwrite previous file/stream 93 | # '-re', # native frame-rate 94 | '-analyzeduration', '1', 95 | '-f', 'rawvideo', 96 | '-r', '%d' % self.fps, # set a fixed frame rate 97 | '-vcodec', 'rawvideo', 98 | # size of one frame 99 | '-s', '%dx%d' % (self.width, self.height), 100 | '-pix_fmt', 'rgb24', # The input are raw bytes 101 | '-thread_queue_size', '1024', 102 | '-i', '-', # The input comes from a pipe 103 | 104 | # Twitch needs to receive sound in their streams! 105 | # '-an', # Tells FFMPEG not to expect any audio 106 | ]) 107 | if self.audio_enabled: 108 | command.extend([ 109 | '-ar', '%d' % AUDIORATE, 110 | '-ac', '2', 111 | '-f', 's16le', 112 | '-thread_queue_size', '1024', 113 | '-i', '/tmp/audiopipe' 114 | ]) 115 | else: 116 | command.extend([ 117 | '-f', 'lavfi', 118 | '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100' 119 | ]) 120 | command.extend([ 121 | # VIDEO CODEC PARAMETERS 122 | '-vcodec', 'libx264', 123 | '-r', '%d' % self.fps, 124 | '-b:v', '3000k', 125 | '-s', '%dx%d' % (self.width, self.height), 126 | '-preset', 'faster', '-tune', 'zerolatency', 127 | '-crf', '23', 128 | '-pix_fmt', 'yuv420p', 129 | # '-force_key_frames', r'expr:gte(t,n_forced*2)', 130 | '-minrate', '3000k', '-maxrate', '3000k', 131 | '-bufsize', '12000k', 132 | '-g', '60', # key frame distance 133 | '-keyint_min', '1', 134 | # '-filter:v "setpts=0.25*PTS"' 135 | # '-vsync','passthrough', 136 | 137 | # AUDIO CODEC PARAMETERS 138 | '-acodec', 'libmp3lame', '-ar', '44100', '-b:a', '160k', 139 | # '-bufsize', '8192k', 140 | '-ac', '1', 141 | # '-acodec', 'aac', '-strict', 'experimental', 142 | # '-ab', '128k', '-ar', '44100', '-ac', '1', 143 | # '-async','44100', 144 | # '-filter_complex', 'asplit', #for audio sync? 145 | 146 | # STORE THE VIDEO PARAMETERS 147 | # '-vcodec', 'libx264', '-s', '%dx%d'%(width, height), 148 | # '-preset', 'libx264-fast', 149 | # 'my_output_videofile2.avi' 150 | 151 | # MAP THE STREAMS 152 | # use only video from first input and only audio from second 153 | '-map', '0:v', '-map', '1:a', 154 | 155 | # NUMBER OF THREADS 156 | '-threads', '2', 157 | 158 | # STREAM TO TWITCH 159 | '-f', 'flv', self.get_closest_ingest(), 160 | ]) 161 | 162 | devnullpipe = subprocess.DEVNULL 163 | if self.verbose: 164 | devnullpipe = None 165 | self.ffmpeg_process = subprocess.Popen( 166 | command, 167 | stdin=subprocess.PIPE, 168 | stderr=devnullpipe, 169 | stdout=devnullpipe) 170 | 171 | def __enter__(self): 172 | return self 173 | 174 | def __exit__(self, type, value, traceback): 175 | # sigint so avconv can clean up the stream nicely 176 | self.ffmpeg_process.send_signal(signal.SIGINT) 177 | # waiting doesn't work because of reasons I don't know 178 | # self.pipe.wait() 179 | 180 | def send_video_frame(self, frame): 181 | """Send frame of shape (height, width, 3) 182 | with values between 0 and 1. 183 | Raises an OSError when the stream is closed. 184 | 185 | :param frame: array containing the frame. 186 | :type frame: numpy array with shape (height, width, 3) 187 | containing values between 0.0 and 1.0 188 | """ 189 | 190 | assert frame.shape == (self.height, self.width, 3) 191 | 192 | frame = np.clip(255*frame, 0, 255).astype('uint8') 193 | try: 194 | self.ffmpeg_process.stdin.write(frame.tostring()) 195 | except OSError: 196 | # The pipe has been closed. Reraise and handle it further 197 | # downstream 198 | raise 199 | 200 | def send_audio(self, left_channel, right_channel): 201 | """Add the audio samples to the stream. The left and the right 202 | channel should have the same shape. 203 | Raises an OSError when the stream is closed. 204 | 205 | :param left_channel: array containing the audio signal. 206 | :type left_channel: numpy array with shape (k, ) 207 | containing values between -1.0 and 1.0. k can be any integer 208 | :param right_channel: array containing the audio signal. 209 | :type right_channel: numpy array with shape (k, ) 210 | containing values between -1.0 and 1.0. k can be any integer 211 | """ 212 | if self.audio_pipe is None: 213 | if not os.path.exists('/tmp/audiopipe'): 214 | os.mkfifo('/tmp/audiopipe') 215 | self.audio_pipe = os.open('/tmp/audiopipe', os.O_WRONLY) 216 | 217 | assert len(left_channel.shape) == 1 218 | assert left_channel.shape == right_channel.shape 219 | 220 | frame = np.column_stack((left_channel, right_channel)).flatten() 221 | 222 | frame = np.clip(32767*frame, -32767, 32767).astype('int16') 223 | try: 224 | os.write(self.audio_pipe, frame.tostring()) 225 | except OSError: 226 | # The pipe has been closed. Reraise and handle it further 227 | # downstream 228 | raise 229 | 230 | def get_closest_ingest(self): 231 | closest_server = requests.get(url='https://ingest.twitch.tv/api/v2/ingests').json()['ingests'][0] 232 | url_template = closest_server['url_template'] 233 | print("Streaming to closest server: %s at %s" % (closest_server['name'], 234 | url_template.replace('/app/{stream_key}', ''))) 235 | return url_template.format( 236 | stream_key=self.twitch_stream_key) 237 | 238 | 239 | class TwitchOutputStreamRepeater(TwitchOutputStream): 240 | """ 241 | This stream makes sure a steady framerate is kept by repeating the 242 | last frame when needed. 243 | 244 | Note: this will not generate a stable, stutter-less stream! 245 | It does not keep a buffer and you cannot synchronize using this 246 | stream. Use TwitchBufferedOutputStream for this. 247 | """ 248 | def __init__(self, *args, **kwargs): 249 | super(TwitchOutputStreamRepeater, self).__init__(*args, **kwargs) 250 | 251 | self.lastframe = np.ones((self.height, self.width, 3)) 252 | self._send_last_video_frame() # Start sending the stream 253 | 254 | if self.audio_enabled: 255 | # some audible sine waves 256 | xl = np.linspace(0.0, 10*np.pi, int(AUDIORATE/self.fps) + 1)[:-1] 257 | xr = np.linspace(0.0, 100*np.pi, int(AUDIORATE/self.fps) + 1)[:-1] 258 | self.lastaudioframe_left = np.sin(xl) 259 | self.lastaudioframe_right = np.sin(xr) 260 | self._send_last_audio() # Start sending the stream 261 | 262 | def _send_last_video_frame(self): 263 | try: 264 | super(TwitchOutputStreamRepeater, 265 | self).send_video_frame(self.lastframe) 266 | except OSError: 267 | # stream has been closed. 268 | # This function is still called once when that happens. 269 | pass 270 | else: 271 | # send the next frame at the appropriate time 272 | threading.Timer(1./self.fps, 273 | self._send_last_video_frame).start() 274 | 275 | def _send_last_audio(self): 276 | try: 277 | super(TwitchOutputStreamRepeater, 278 | self).send_audio(self.lastaudioframe_left, 279 | self.lastaudioframe_right) 280 | except OSError: 281 | # stream has been closed. 282 | # This function is still called once when that happens. 283 | pass 284 | else: 285 | # send the next frame at the appropriate time 286 | threading.Timer(1./self.fps, 287 | self._send_last_audio).start() 288 | 289 | def send_video_frame(self, frame): 290 | """Send frame of shape (height, width, 3) 291 | with values between 0 and 1. 292 | 293 | :param frame: array containing the frame. 294 | :type frame: numpy array with shape (height, width, 3) 295 | containing values between 0.0 and 1.0 296 | """ 297 | self.lastframe = frame 298 | 299 | def send_audio(self, left_channel, right_channel): 300 | """Add the audio samples to the stream. The left and the right 301 | channel should have the same shape. 302 | 303 | :param left_channel: array containing the audio signal. 304 | :type left_channel: numpy array with shape (k, ) 305 | containing values between -1.0 and 1.0. k can be any integer 306 | :param right_channel: array containing the audio signal. 307 | :type right_channel: numpy array with shape (k, ) 308 | containing values between -1.0 and 1.0. k can be any integer 309 | """ 310 | self.lastaudioframe_left = left_channel 311 | self.lastaudioframe_right = right_channel 312 | 313 | 314 | class TwitchBufferedOutputStream(TwitchOutputStream): 315 | """ 316 | This stream makes sure a steady framerate is kept by buffering 317 | frames. Make sure not to have too many frames in buffer, since it 318 | will increase the memory load considerably! 319 | 320 | Adding frames is thread safe. 321 | """ 322 | def __init__(self, *args, **kwargs): 323 | super(TwitchBufferedOutputStream, self).__init__(*args, **kwargs) 324 | self.last_frame = np.ones((self.height, self.width, 3)) 325 | self.last_frame_time = None 326 | self.next_video_send_time = None 327 | self.frame_counter = 0 328 | self.q_video = queue.PriorityQueue() 329 | 330 | # don't call the functions directly, as they block on the first 331 | # call 332 | self.t = threading.Timer(0.0, self._send_video_frame) 333 | self.t.daemon = True 334 | self.t.start() 335 | 336 | if self.audio_enabled: 337 | # send audio at about the same rate as video 338 | # this can be changed 339 | self.last_audio = (np.zeros((int(AUDIORATE/self.fps), )), 340 | np.zeros((int(AUDIORATE/self.fps), ))) 341 | self.last_audio_time = None 342 | self.next_audio_send_time = None 343 | self.audio_frame_counter = 0 344 | self.q_audio = queue.PriorityQueue() 345 | self.t = threading.Timer(0.0, self._send_audio) 346 | self.t.daemon = True 347 | self.t.start() 348 | 349 | def _send_video_frame(self): 350 | start_time = time.time() 351 | try: 352 | frame = self.q_video.get_nowait() 353 | # frame[0] is frame count of the frame 354 | # frame[1] is the frame 355 | frame = frame[1] 356 | except IndexError: 357 | frame = self.last_frame 358 | except queue.Empty: 359 | frame = self.last_frame 360 | else: 361 | self.last_frame = frame 362 | 363 | try: 364 | super(TwitchBufferedOutputStream, self 365 | ).send_video_frame(frame) 366 | except OSError: 367 | # stream has been closed. 368 | # This function is still called once when that happens. 369 | # Don't call this function again and everything should be 370 | # cleaned up just fine. 371 | return 372 | 373 | # send the next frame at the appropriate time 374 | if self.next_video_send_time is None: 375 | self.t = threading.Timer(1./self.fps, self._send_video_frame) 376 | self.next_video_send_time = start_time + 1./self.fps 377 | else: 378 | self.next_video_send_time += 1./self.fps 379 | next_event_time = self.next_video_send_time - start_time 380 | if next_event_time > 0: 381 | self.t = threading.Timer(next_event_time, 382 | self._send_video_frame) 383 | else: 384 | # we should already have sent something! 385 | # 386 | # not allowed for recursion problems :-( 387 | # (maximum recursion depth) 388 | # self.send_me_last_frame_again() 389 | # 390 | # other solution: 391 | self.t = threading.Thread( 392 | target=self._send_video_frame) 393 | 394 | self.t.daemon = True 395 | self.t.start() 396 | 397 | def _send_audio(self): 398 | start_time = time.time() 399 | try: 400 | _, left_audio, right_audio = self.q_audio.get_nowait() 401 | except IndexError: 402 | left_audio, right_audio = self.last_audio 403 | except queue.Empty: 404 | left_audio, right_audio = self.last_audio 405 | else: 406 | self.last_audio = (left_audio, right_audio) 407 | 408 | try: 409 | super(TwitchBufferedOutputStream, self 410 | ).send_audio(left_audio, right_audio) 411 | except OSError: 412 | # stream has been closed. 413 | # This function is still called once when that happens. 414 | # Don't call this function again and everything should be 415 | # cleaned up just fine. 416 | return 417 | 418 | # send the next frame at the appropriate time 419 | downstream_time = len(left_audio) / AUDIORATE 420 | 421 | if self.next_audio_send_time is None: 422 | self.t = threading.Timer(downstream_time, 423 | self._send_audio) 424 | self.next_audio_send_time = start_time + downstream_time 425 | else: 426 | self.next_audio_send_time += downstream_time 427 | next_event_time = self.next_audio_send_time - start_time 428 | if next_event_time > 0: 429 | self.t = threading.Timer(next_event_time, 430 | self._send_audio) 431 | else: 432 | # we should already have sent something! 433 | # 434 | # not allowed for recursion problems :-( 435 | # (maximum recursion depth) 436 | # self.send_me_last_frame_again() 437 | # 438 | # other solution: 439 | self.t = threading.Thread( 440 | target=self._send_audio) 441 | 442 | self.t.daemon = True 443 | self.t.start() 444 | 445 | def send_video_frame(self, frame, frame_counter=None): 446 | """send frame of shape (height, width, 3) 447 | with values between 0 and 1 448 | 449 | :param frame: array containing the frame. 450 | :type frame: numpy array with shape (height, width, 3) 451 | containing values between 0.0 and 1.0 452 | :param frame_counter: frame position number within stream. 453 | Provide this when multi-threading to make sure frames don't 454 | switch position 455 | :type frame_counter: int 456 | """ 457 | if frame_counter is None: 458 | frame_counter = self.frame_counter 459 | self.frame_counter += 1 460 | 461 | self.q_video.put((frame_counter, frame)) 462 | 463 | def send_audio(self, 464 | left_channel, 465 | right_channel, 466 | frame_counter=None): 467 | """Add the audio samples to the stream. The left and the right 468 | channel should have the same shape. 469 | 470 | :param left_channel: array containing the audio signal. 471 | :type left_channel: numpy array with shape (k, ) 472 | containing values between -1.0 and 1.0. l can be any integer 473 | :param right_channel: array containing the audio signal. 474 | :type right_channel: numpy array with shape (k, ) 475 | containing values between -1.0 and 1.0. l can be any integer 476 | :param frame_counter: frame position number within stream. 477 | Provide this when multi-threading to make sure frames don't 478 | switch position 479 | :type frame_counter: int 480 | """ 481 | if frame_counter is None: 482 | frame_counter = self.audio_frame_counter 483 | self.audio_frame_counter += 1 484 | 485 | self.q_audio.put((frame_counter, left_channel, right_channel)) 486 | 487 | def get_video_frame_buffer_state(self): 488 | """Find out how many video frames are left in the buffer. 489 | The buffer should never run dry, or audio and video will go out 490 | of sync. Likewise, the more filled the buffer, the higher the 491 | memory use and the delay between you putting your frame in the 492 | stream and the frame showing up on Twitch. 493 | 494 | :return integer estimate of the number of video frames left. 495 | """ 496 | return self.q_video.qsize() 497 | 498 | def get_audio_buffer_state(self): 499 | """Find out how many audio fragments are left in the buffer. 500 | The buffer should never run dry, or audio and video will go out 501 | of sync. Likewise, the more filled the buffer, the higher the 502 | memory use and the delay between you putting your frame in the 503 | stream and the frame showing up on Twitch. 504 | 505 | :return integer estimate of the number of audio fragments left. 506 | """ 507 | return self.q_audio.qsize() 508 | 509 | -------------------------------------------------------------------------------- /twitchstream/tests/conftest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Configuration of the testing 5 | """ 6 | import pytest 7 | 8 | 9 | def pytest_addoption(parser): 10 | """ 11 | Add options for testing 12 | :param parser: 13 | :return: 14 | """ 15 | parser.addoption("--runslow", 16 | action="store_true", 17 | help="run slow tests") 18 | 19 | 20 | def pytest_runtest_setup(item): 21 | """ 22 | Skip the slow tests when running with --runslow 23 | :param item: 24 | :return: 25 | """ 26 | if 'slow' in item.keywords and \ 27 | not item.config.getoption("--runslow"): 28 | pytest.skip("need --runslow option to run") 29 | -------------------------------------------------------------------------------- /twitchstream/tests/test_chat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Tests for chat.py 5 | """ 6 | 7 | 8 | def test_logged_in_successful(): 9 | """ 10 | Test TwitchChatStream._logged_in_successful 11 | """ 12 | from twitchstream.chat import TwitchChatStream 13 | res = TwitchChatStream._logged_in_successful( 14 | ":tmi.twitch.tv NOTICE * :Error logging in") 15 | assert res is False 16 | res = TwitchChatStream._logged_in_successful( 17 | ":tmi.twitch.tv NOTICE * :Error logging in\n") 18 | assert res is False 19 | res = TwitchChatStream._logged_in_successful( 20 | ":tmi.twitch.tv NOTICE * :Error logging in\r\n") 21 | assert res is False 22 | res = TwitchChatStream._logged_in_successful( 23 | ":tmi.twitch.tv 001 sdsd :Welcome, GLHF!") 24 | assert res is True 25 | res = TwitchChatStream._logged_in_successful( 26 | ":tmi.twitch.tv 001 sdsd :Your host is tmi.twitch.tv") 27 | assert res is True 28 | res = TwitchChatStream._logged_in_successful( 29 | ":tmi.twitch.tv 001 sdsd :This server is rather new") 30 | assert res is True 31 | res = TwitchChatStream._logged_in_successful( 32 | ":tmi.twitch.tv 001 sdsd :-!") 33 | assert res is True 34 | res = TwitchChatStream._logged_in_successful( 35 | ":tmi.twitch.tv 001 sdsd :You are in a maze of twisty passages," 36 | " all alike.") 37 | assert res is True 38 | res = TwitchChatStream._logged_in_successful( 39 | ":tmi.twitch.tv 001 sdsd :>") 40 | assert res is True 41 | -------------------------------------------------------------------------------- /twitchstream/tests/test_inputvideo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Tests for inputvideo.py 5 | """ 6 | -------------------------------------------------------------------------------- /twitchstream/tests/test_outputvideo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Tests for outputvideo.py 5 | """ 6 | --------------------------------------------------------------------------------