def test_comma_list_filter(self):
        # (acceptable, values, result)
        test_data = [
            (['foo', 'bar', 'com'], 'foo,bar,example.com', ['foo', 'bar']),
            (['/var/run/foo', 'FO'], '/var/run/foo,/var/run/bar',
             ['/var/run/foo']),
            (['hls', 'hls5', 'dash'], 'hls,hls5', ['hls', 'hls5']),
            (['EU', 'RU'], 'DE,FR,RU,US', ['RU']),
        ]

        for _a, _v, _r in test_data:
            func = comma_list_filter(_a)
            self.assertEqual(func(_v), _r)
예제 #2
0
    def test_comma_list_filter(self):
        # (acceptable, values, result)
        test_data = [
            (['foo', 'bar', 'com'], 'foo,bar,example.com', ['foo', 'bar']),
            (['/var/run/foo', 'FO'], '/var/run/foo,/var/run/bar',
             ['/var/run/foo']),
            (['hls', 'hls5', 'dash'], 'hls,hls5', ['hls', 'hls5']),
            (['EU', 'RU'], 'DE,FR,RU,US', ['RU']),
        ]

        for _a, _v, _r in test_data:
            func = comma_list_filter(_a)
            self.assertEqual(func(_v), _r)
예제 #3
0
class Zattoo(Plugin):
    API_CHANNELS = '{0}/zapi/v2/cached/channels/{1}?details=False'
    API_HELLO = '{0}/zapi/session/hello'
    API_HELLO_V3 = '{0}/zapi/v3/session/hello'
    API_LOGIN = '******'
    API_LOGIN_V3 = '{0}/zapi/v3/account/login'
    API_SESSION = '{0}/zapi/v2/session'
    API_WATCH = '{0}/zapi/watch'
    API_WATCH_REC = '{0}/zapi/watch/recording/{1}'
    API_WATCH_VOD = '{0}/zapi/avod/videos/{1}/watch'

    STREAMS_ZATTOO = ['dash', 'hls', 'hls5']

    TIME_CONTROL = 60 * 60 * 2
    TIME_SESSION = 60 * 60 * 24 * 30

    _url_re = re.compile(r'''(?x)
        https?://
        (?P<base_url>
            (?:(?:
                iptv\.glattvision|www\.(?:myvisiontv|saktv|vtxtv)
            )\.ch
            )|(?:(?:
                mobiltv\.quickline|www\.quantum-tv|zattoo
            )\.com
            )|(?:(?:
                tvonline\.ewe|nettv\.netcologne|tvplus\.m-net
            )\.de
            )|(?:(?:
                player\.waly|www\.(?:1und1|netplus)
            )\.tv)
            |www\.bbv-tv\.net
            |www\.meinewelt\.cc
        )/
        (?:
            (?:
                recording(?:s\?recording=|/)
                |
                (?:ondemand/)?(?:watch/(?:[^/\s]+)(?:/[^/]+/))
            )(?P<recording_id>\d+)
            |
            (?:
                (?:live/|watch/)|(?:channels(?:/\w+)?|guide)\?channel=
            )(?P<channel>[^/\s]+)
            |
            ondemand(?:\?video=|/watch/)(?P<vod_id>[^-]+)
        )
        ''')

    _app_token_re = re.compile(r"""window\.appToken\s+=\s+'([^']+)'""")

    _channels_schema = validate.Schema(
        {
            'success':
            bool,
            'channel_groups': [{
                'channels': [
                    {
                        'display_alias': validate.text,
                        'cid': validate.text
                    },
                ]
            }]
        },
        validate.get('channel_groups'),
    )

    _session_schema = validate.Schema(
        {
            'success': bool,
            'session': {
                'loggedin': bool
            }
        }, validate.get('session'))

    arguments = PluginArguments(
        PluginArgument("email",
                       requires=["password"],
                       metavar="EMAIL",
                       help="""
            The email associated with your zattoo account,
            required to access any zattoo stream.
            """),
        PluginArgument("password",
                       sensitive=True,
                       metavar="PASSWORD",
                       help="""
            A zattoo account password to use with --zattoo-email.
            """),
        PluginArgument("purge-credentials",
                       action="store_true",
                       help="""
            Purge cached zattoo credentials to initiate a new session
            and reauthenticate.
            """),
        PluginArgument('stream-types',
                       metavar='TYPES',
                       type=comma_list_filter(STREAMS_ZATTOO),
                       default=['hls'],
                       help='''
            A comma-delimited list of stream types which should be used,
            the following types are allowed:

            - {0}

            Default is "hls".
            '''.format('\n            - '.join(STREAMS_ZATTOO))))

    def __init__(self, url):
        super(Zattoo, self).__init__(url)
        self.domain = self._url_re.match(url).group('base_url')
        self._session_attributes = Cache(
            filename='plugin-cache.json',
            key_prefix='zattoo:attributes:{0}'.format(self.domain))
        self._uuid = self._session_attributes.get('uuid')
        self._authed = (self._session_attributes.get('power_guide_hash')
                        and self._uuid and self.session.http.cookies.get(
                            'pzuid', domain=self.domain)
                        and self.session.http.cookies.get('beaker.session.id',
                                                          domain=self.domain))
        self._session_control = self._session_attributes.get(
            'session_control', False)
        self.base_url = 'https://{0}'.format(self.domain)
        self.headers = {
            'User-Agent': useragents.CHROME,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': self.base_url
        }

    @classmethod
    def can_handle_url(cls, url):
        return cls._url_re.match(url) is not None

    def _hello(self):
        log.debug('_hello ...')

        # a new session is required for the app_token
        self.session.http.cookies = cookiejar_from_dict({})
        if self.base_url == 'https://zattoo.com':
            app_token_url = 'https://zattoo.com/int/'
        elif self.base_url == 'https://www.quantum-tv.com':
            app_token_url = 'https://www.quantum-tv.com/token-4d0d61d4ce0bf8d9982171f349d19f34.json'
        else:
            app_token_url = self.base_url
        res = self.session.http.get(app_token_url)
        match = self._app_token_re.search(res.text)

        if self.base_url == 'https://www.quantum-tv.com':
            app_token = self.session.http.json(res)["session_token"]
            hello_url = self.API_HELLO_V3.format(self.base_url)
        else:
            app_token = match.group(1)
            hello_url = self.API_HELLO.format(self.base_url)

        if self._uuid:
            __uuid = self._uuid
        else:
            __uuid = str(uuid.uuid4())
            self._session_attributes.set('uuid',
                                         __uuid,
                                         expires=self.TIME_SESSION)

        params = {
            'client_app_token': app_token,
            'uuid': __uuid,
        }

        if self.base_url == 'https://www.quantum-tv.com':
            params['app_version'] = '3.2028.3'
        else:
            params['lang'] = 'en'
            params['format'] = 'json'

        res = self.session.http.post(hello_url,
                                     headers=self.headers,
                                     data=params)

    def _login(self, email, password):
        log.debug('_login ... Attempting login as {0}'.format(email))

        params = {'login': email, 'password': password, 'remember': 'true'}

        if self.base_url == 'https://quantum-tv.com':
            login_url = self.API_LOGIN_V3.format(self.base_url)
        else:
            login_url = self.API_LOGIN.format(self.base_url)

        try:
            res = self.session.http.post(login_url,
                                         headers=self.headers,
                                         data=params)
        except Exception as e:
            if '400 Client Error' in str(e):
                raise PluginError(
                    'Failed to login, check your username/password')
            raise e

        data = self.session.http.json(res)
        self._authed = data['success']
        log.debug('New Session Data')
        self.save_cookies(default_expires=self.TIME_SESSION)
        self._session_attributes.set('power_guide_hash',
                                     data['session']['power_guide_hash'],
                                     expires=self.TIME_SESSION)
        self._session_attributes.set('session_control',
                                     True,
                                     expires=self.TIME_CONTROL)

    def _watch(self):
        log.debug('_watch ...')
        match = self._url_re.match(self.url)
        if not match:
            log.debug('_watch ... no match')
            return
        channel = match.group('channel')
        vod_id = match.group('vod_id')
        recording_id = match.group('recording_id')

        params = {'https_watch_urls': True}
        if channel:
            watch_url = self.API_WATCH.format(self.base_url)
            params_cid = self._get_params_cid(channel)
            if not params_cid:
                return
            params.update(params_cid)
        elif vod_id:
            log.debug('Found vod_id: {0}'.format(vod_id))
            watch_url = self.API_WATCH_VOD.format(self.base_url, vod_id)
        elif recording_id:
            log.debug('Found recording_id: {0}'.format(recording_id))
            watch_url = self.API_WATCH_REC.format(self.base_url, recording_id)
        else:
            log.debug('Missing watch_url')
            return

        zattoo_stream_types = self.get_option('stream-types') or ['hls']
        for stream_type in zattoo_stream_types:
            params_stream_type = {'stream_type': stream_type}
            params.update(params_stream_type)

            try:
                res = self.session.http.post(watch_url,
                                             headers=self.headers,
                                             data=params)
            except Exception as e:
                if '404 Client Error' in str(e):
                    log.error('Unfortunately streaming is not permitted in '
                              'this country or this channel does not exist.')
                elif '402 Client Error: Payment Required' in str(e):
                    log.error('Paid subscription required for this channel.')
                    log.info('If paid subscription exist, use --zattoo-purge'
                             '-credentials to start a new session.')
                elif '403 Client Error' in str(e):
                    log.debug('Force session reset for watch_url')
                    self.reset_session()
                else:
                    log.error(str(e))
                return

            data = self.session.http.json(res)
            log.debug('Found data for {0}'.format(stream_type))
            if data['success'] and stream_type in ['hls', 'hls5']:
                for url in data['stream']['watch_urls']:
                    for s in HLSStream.parse_variant_playlist(
                            self.session, url['url']).items():
                        yield s
            elif data['success'] and stream_type == 'dash':
                for url in data['stream']['watch_urls']:
                    for s in DASHStream.parse_manifest(self.session,
                                                       url['url']).items():
                        yield s

    def _get_params_cid(self, channel):
        log.debug('get channel ID for {0}'.format(channel))

        channels_url = self.API_CHANNELS.format(
            self.base_url, self._session_attributes.get('power_guide_hash'))

        try:
            res = self.session.http.get(channels_url, headers=self.headers)
        except Exception:
            log.debug('Force session reset for _get_params_cid')
            self.reset_session()
            return False

        data = self.session.http.json(res, schema=self._channels_schema)

        c_list = []
        for d in data:
            for c in d['channels']:
                c_list.append(c)

        cid = []
        zattoo_list = []
        for c in c_list:
            zattoo_list.append(c['display_alias'])
            if c['display_alias'] == channel:
                cid = c['cid']

        log.debug('Available zattoo channels in this country: {0}'.format(
            ', '.join(sorted(zattoo_list))))

        if not cid:
            cid = channel

        log.debug('CHANNEL ID: {0}'.format(cid))

        return {'cid': cid}

    def reset_session(self):
        self._session_attributes.set('power_guide_hash', None, expires=0)
        self._session_attributes.set('uuid', None, expires=0)
        self.clear_cookies()
        self._authed = False

    def _get_streams(self):
        email = self.get_option('email')
        password = self.get_option('password')

        if self.options.get('purge_credentials'):
            self.reset_session()
            log.info('All credentials were successfully removed.')
        elif (self._authed and not self._session_control):
            # check every two hours, if the session is actually valid
            log.debug('Session control for {0}'.format(self.domain))
            res = self.session.http.get(self.API_SESSION.format(self.base_url))
            res = self.session.http.json(res, schema=self._session_schema)
            if res['loggedin']:
                self._session_attributes.set('session_control',
                                             True,
                                             expires=self.TIME_CONTROL)
            else:
                log.debug('User is not logged in')
                self._authed = False

        if not self._authed and (not email and not password):
            log.error(
                'A login for Zattoo is required, use --zattoo-email EMAIL'
                ' --zattoo-password PASSWORD to set them')
            return

        if not self._authed:
            self._hello()
            self._login(email, password)

        return self._watch()
예제 #4
0
def build_parser():
    parser = ArgumentParser(
        prog="streamlink",
        fromfile_prefix_chars="@",
        formatter_class=HelpFormatter,
        add_help=False,
        usage="%(prog)s [OPTIONS] <URL> [STREAM]",
        description=dedent("""
        Streamlink is a command-line utility that extracts streams from various
        services and pipes them into a video player of choice.
        """),
        epilog=dedent("""
        For more in-depth documentation see:
          https://streamlink.github.io

        Please report broken plugins or bugs to the issue tracker on Github:
          https://github.com/streamlink/streamlink/issues
        """)
    )

    positional = parser.add_argument_group("Positional arguments")
    positional.add_argument(
        "url",
        metavar="URL",
        nargs="?",
        help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted ("https://"),
        depending on the implementation of the plugin being used.

        Alternatively, the URL can also be specified by using the --url option.
        """
    )
    positional.add_argument(
        "stream",
        metavar="STREAM",
        nargs="?",
        type=comma_list,
        help="""
        Stream to play.

        Use ``best`` or ``worst`` for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        If no stream is specified and --default-stream is not used, then a list
        of available streams will be printed.
        """
    )

    general = parser.add_argument_group("General options")
    general.add_argument(
        "-h", "--help",
        action="store_true",
        help="""
        Show this help message and exit.
        """
    )
    general.add_argument(
        "-V", "--version",
        action="version",
        version=f"%(prog)s {streamlink_version}",
        help="""
        Show version number and exit.
        """
    )
    general.add_argument(
        "--plugins",
        action="store_true",
        help="""
        Print a list of all currently installed plugins.
        """
    )
    general.add_argument(
        "--plugin-dirs",
        metavar="DIRECTORY",
        type=comma_list,
        help="""
        Attempts to load plugins from these directories.

        Multiple directories can be used by separating them with a comma.
        """
    )
    general.add_argument(
        "--can-handle-url",
        metavar="URL",
        help="""
        Check if Streamlink has a plugin that can handle the specified URL.

        Returns status code 1 for false and 0 for true.

        Useful for external scripting.
        """
    )
    general.add_argument(
        "--can-handle-url-no-redirect",
        metavar="URL",
        help="""
        Same as --can-handle-url but without following redirects when looking up
        the URL.
        """
    )
    general.add_argument(
        "--config",
        action="append",
        metavar="FILENAME",
        help="""
        Load options from this config file.

        Can be repeated to load multiple files, in which case the options are
        merged on top of each other where the last config has highest priority.
        """
    )
    general.add_argument(
        "-l", "--loglevel",
        metavar="LEVEL",
        choices=logger.levels,
        default="info",
        help="""
        Set the log message threshold.

        Valid levels are: none, error, warning, info, debug, trace
        """
    )
    general.add_argument(
        "--logfile",
        metavar="FILE",
        help="""
        Append log output to FILE instead of writing to stdout/stderr.

        User prompts and download progress won't be written to FILE.

        A value of ``-`` will set the file name to an ISO8601-like string
        and will choose the following default log directories.

        Windows:

          %%TEMP%%\\streamlink\\logs

        macOS:

          ${HOME}/Library/Logs/streamlink

        Linux/BSD:

          ${XDG_STATE_HOME:-${HOME}/.local/state}/streamlink/logs
        """
    )
    general.add_argument(
        "-Q", "--quiet",
        action="store_true",
        help="""
        Hide all log output.

        Alias for "--loglevel none".
        """
    )
    general.add_argument(
        "-j", "--json",
        action="store_true",
        help="""
        Output JSON representations instead of the normal text output.

        Useful for external scripting.
        """
    )
    general.add_argument(
        "--auto-version-check",
        type=boolean,
        metavar="{yes,true,1,on,no,false,0,off}",
        default=False,
        help="""
        Enable or disable the automatic check for a new version of Streamlink.

        Default is "no".
        """
    )
    general.add_argument(
        "--version-check",
        action="store_true",
        help="""
        Runs a version check and exits.
        """
    )
    general.add_argument(
        "--locale",
        type=str,
        metavar="LOCALE",
        help="""
        The preferred locale setting, for selecting the preferred subtitle and
        audio language.

        The locale is formatted as [language_code]_[country_code], eg. en_US or
        es_ES.

        Default is system locale.
        """
    )
    general.add_argument(
        "--interface",
        type=str,
        metavar="INTERFACE",
        help="""
        Set the network interface.
        """
    )
    general.add_argument(
        "-4", "--ipv4",
        action="store_true",
        help="""
        Resolve address names to IPv4 only. This option overrides :option:`-6`.
        """
    )
    general.add_argument(
        "-6", "--ipv6",
        action="store_true",
        help="""
        Resolve address names to IPv6 only. This option overrides :option:`-4`.
        """
    )

    player = parser.add_argument_group("Player options")
    player.add_argument(
        "-p", "--player",
        metavar="COMMAND",
        default=find_default_player(),
        help="""
        Player to feed stream data to. By default, VLC will be used if it can be
        found in its default location.

        This is a shell-like syntax to support using a specific player:

          %(prog)s --player=vlc <url> [stream]

        Absolute or relative paths can also be passed via this option in the
        event the player's executable can not be resolved:

          %(prog)s --player=/path/to/vlc <url> [stream]
          %(prog)s --player=./vlc-player/vlc <url> [stream]

        To use a player that is located in a path with spaces you must quote the
        parameter or its value:

          %(prog)s "--player=/path/with spaces/vlc" <url> [stream]
          %(prog)s --player "C:\\path\\with spaces\\mpc-hc64.exe" <url> [stream]

        Options may also be passed to the player. For example:

          %(prog)s --player "vlc --file-caching=5000" <url> [stream]

        As an alternative to this, see the --player-args parameter, which does
        not log any custom player arguments.
        """
    )
    player.add_argument(
        "-a", "--player-args",
        metavar="ARGUMENTS",
        default="",
        help=f"""
        This option allows you to customize the default arguments which are put
        together with the value of --player to create a command to execute.

        It's usually enough to only use --player instead of this unless you need
        to add arguments after the player's input argument or if you don't want
        any of the player arguments to be logged.

        The value can contain formatting variables surrounded by curly braces,
        {{ and }}. If you need to include a brace character, it can be escaped
        by doubling, e.g. {{{{ and }}}}.

        Formatting variables available:

        {{{PLAYER_ARGS_INPUT_DEFAULT}}}
            This is the input that the player will use. For standard input (stdin),
            it is ``-``, but it can also be a URL, depending on the options used.

        {{{PLAYER_ARGS_INPUT_FALLBACK}}}
            The old fallback variable name with the same functionality.

        Example:

          %(prog)s -p vlc -a "--play-and-exit {{{PLAYER_ARGS_INPUT_DEFAULT}}}" <url> [stream]

        Note: When neither of the variables are found, ``{{{PLAYER_ARGS_INPUT_DEFAULT}}}``
        will be appended to the whole parameter value, to ensure that the player
        always receives an input argument.
        """
    )
    player.add_argument(
        "-v", "--verbose-player",
        action="store_true",
        help="""
        Allow the player to display its console output.
        """
    )
    player.add_argument(
        "-n", "--player-fifo", "--fifo",
        action="store_true",
        help="""
        Make the player read the stream through a named pipe instead of the
        stdin pipe.
        """
    )
    player.add_argument(
        "--player-http",
        action="store_true",
        help="""
        Make the player read the stream through HTTP instead of the stdin pipe.
        """
    )
    player.add_argument(
        "--player-continuous-http",
        action="store_true",
        help="""
        Make the player read the stream through HTTP, but unlike --player-http
        it will continuously try to open the stream if the player requests it.

        This makes it possible to handle stream disconnects if your player is
        capable of reconnecting to a HTTP stream. This is usually done by
        setting your player to a "repeat mode".
        """
    )
    player.add_argument(
        "--player-external-http",
        action="store_true",
        help="""
        Serve stream data through HTTP without running any player. This is
        useful to allow external devices like smartphones or streaming boxes to
        watch streams they wouldn't be able to otherwise.

        Behavior will be similar to the continuous HTTP option, but no player
        program will be started, and the server will listen on all available
        connections instead of just in the local (loopback) interface.

        The URLs that can be used to access the stream will be printed to the
        console, and the server can be interrupted using CTRL-C.
        """
    )
    player.add_argument(
        "--player-external-http-port",
        metavar="PORT",
        type=num(int, min=0, max=65535),
        default=0,
        help="""
        A fixed port to use for the external HTTP server if that mode is
        enabled. Omit or set to 0 to use a random high ( >1024) port.
        """
    )
    player.add_argument(
        "--player-passthrough",
        metavar="TYPES",
        type=comma_list_filter(STREAM_PASSTHROUGH),
        default=[],
        help="""
        A comma-delimited list of stream types to pass to the player as a URL to
        let it handle the transport of the stream instead.

        Stream types that can be converted into a playable URL are:

        - {0}

        Make sure your player can handle the stream type when using this.
        """.format("\n        - ".join(STREAM_PASSTHROUGH))
    )
    player.add_argument(
        "--player-no-close",
        action="store_true",
        help="""
        By default Streamlink will close the player when the stream
        ends. This is to avoid "dead" GUI players lingering after a
        stream ends.

        It does however have the side-effect of sometimes closing a
        player before it has played back all of its cached data.

        This option will instead let the player decide when to exit.
        """
    )
    player.add_argument(
        "-t", "--title",
        metavar="TITLE",
        help="""
        This option allows you to supply a title to be displayed in the
        title bar of the window that the video player is launched in.

        This value can contain formatting variables surrounded by curly braces,
        {{ and }}. If you need to include a brace character, it can be escaped
        by doubling, e.g. {{{{ and }}}}.

        This option is only supported for the following players: {0}.

        VLC specific information:
            VLC has certain codes you can use inside your title.
            These are accessible inside --title by using a backslash
            before the dollar sign VLC uses to denote a format character.

            e.g. to put the current date in your VLC window title,
            the string "\\$A" could be inserted inside your --title string.

            A full list of the format codes VLC uses is available here:
            https://wiki.videolan.org/Documentation:Format_String/

        mpv specific information:
            mpv has certain codes you can use inside your title.
            These are accessible inside --title by using a backslash
            before the dollar sign mpv uses to denote a format character.

            e.g. to put the current version of mpv running inside your
            mpv window title, the string "\\${{{{mpv-version}}}}" could be
            inserted inside your --title string.

            A full list of the format codes mpv uses is available here:
            https://mpv.io/manual/stable/#property-list

        Formatting variables available to use in --title:

        {{title}}
            If available, this is the title of the stream.
            Otherwise, it is the string "{1}"

        {{author}}
            If available, this is the author of the stream.
            Otherwise, it is the string "{2}"

        {{category}}
            If available, this is the category the stream has been placed into.

            - For Twitch, this is the game being played
            - For YouTube, it's the category e.g. Gaming, Sports, Music...

            Otherwise, it is the string "{3}"

        {{game}}
            This is just a synonym for {{category}} which may make more sense for
            gaming oriented platforms. "Game being played" is a way to categorize
            the stream, so it doesn't need its own separate handling.

        {{url}}
            URL of the stream.

        Examples:

            %(prog)s -p vlc --title "{{title}} -!- {{author}} -!- {{category}} \\$A" <url> [stream]
            %(prog)s -p mpv --title "{{title}} -- {{author}} -- {{category}} -- (\\${{{{mpv-version}}}})" <url> [stream]

        """.format(', '.join(sorted(SUPPORTED_PLAYERS.keys())),
                   DEFAULT_STREAM_METADATA['title'],
                   DEFAULT_STREAM_METADATA['author'],
                   DEFAULT_STREAM_METADATA['category'])
    )

    output = parser.add_argument_group("File output options")
    output.add_argument(
        "-o", "--output",
        metavar="FILENAME",
        help="""
        Write stream data to FILENAME instead of playing it.

        You will be prompted if the file already exists.
        """
    )
    output.add_argument(
        "-f", "--force",
        action="store_true",
        help="""
        When using -o or -r, always write to file even if it already exists.
        """
    )
    output.add_argument(
        "--force-progress",
        action="store_true",
        help="""
        When using -o or -r,
        show the download progress bar even if there is no terminal.
        """
    )
    output.add_argument(
        "-O", "--stdout",
        action="store_true",
        help="""
        Write stream data to stdout instead of playing it.
        """
    )
    output.add_argument(
        "-r", "--record",
        metavar="FILENAME",
        help="""
        Open the stream in the player, while at the same time writing it to FILENAME.

        You will be prompted if the file already exists.
        """
    )
    output.add_argument(
        "-R", "--record-and-pipe",
        metavar="FILENAME",
        help="""
        Write stream data to stdout, while at the same time writing it to FILENAME.

        You will be prompted if the file already exists.
        """
    )

    stream = parser.add_argument_group("Stream options")
    stream.add_argument(
        "--url",
        dest="url_param",
        metavar="URL",
        help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted (https://),
        depending on the implementation of the plugin being used.

        This is an alternative to setting the URL using a positional argument
        and can be useful if set in a config file.
        """
    )
    stream.add_argument(
        "--default-stream",
        type=comma_list,
        metavar="STREAM",
        help="""
        Stream to play.

        Use ``best`` or ``worst`` for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        This is an alternative to setting the stream using a positional argument
        and can be useful if set in a config file.
        """
    )
    stream.add_argument(
        "--stream-url",
        action="store_true",
        help="""
        If possible, translate the resolved stream to a URL and print it.
        """
    )
    stream.add_argument(
        "--retry-streams",
        metavar="DELAY",
        type=num(float, min=0),
        help="""
        Retry fetching the list of available streams until streams are found
        while waiting DELAY second(s) between each attempt. If unset, only one
        attempt will be made to fetch the list of streams available.

        The number of fetch retry attempts can be capped with --retry-max.
        """
    )
    stream.add_argument(
        "--retry-max",
        metavar="COUNT",
        type=num(int, min=-1),
        help="""
        When using --retry-streams, stop retrying the fetch after COUNT retry
        attempt(s). Fetch will retry infinitely if COUNT is zero or unset.

        If --retry-max is set without setting --retry-streams, the delay between
        retries will default to 1 second.
        """
    )
    stream.add_argument(
        "--retry-open",
        metavar="ATTEMPTS",
        type=num(int, min=0),
        default=1,
        help="""
        After a successful fetch, try ATTEMPTS time(s) to open the stream until
        giving up.

        Default is 1.
        """
    )
    stream.add_argument(
        "--stream-types", "--stream-priority",
        metavar="TYPES",
        type=comma_list,
        help="""
        A comma-delimited list of stream types to allow.

        The order will be used to separate streams when there are multiple
        streams with the same name but different stream types. Any stream type
        not listed will be omitted from the available streams list.  A ``*`` can
        be used as a wildcard to match any other type of stream, eg. muxed-stream.

        Default is "rtmp,hls,hds,http,akamaihd,*".
        """
    )
    stream.add_argument(
        "--stream-sorting-excludes",
        metavar="STREAMS",
        type=comma_list,
        help="""
        Fine tune the ``best`` and ``worst`` stream name synonyms by excluding unwanted streams.

        If all of the available streams get excluded, ``best`` and ``worst`` will become
        inaccessible and new special stream synonyms ``best-unfiltered`` and ``worst-unfiltered``
        can be used as a fallback selection method.

        Uses a filter expression in the format:

          [operator]<value>

        Valid operators are ``>``, ``>=``, ``<`` and ``<=``. If no operator is specified then
        equality is tested.

        For example this will exclude streams ranked higher than "480p":

          ">480p"

        Multiple filters can be used by separating each expression with a comma.

        For example this will exclude streams from two quality types:

          ">480p,>medium"

        """
    )

    transport = parser.add_argument_group("Stream transport options")
    transport.add_argument(
        "--hds-live-edge",
        type=num(float, min=0),
        metavar="SECONDS",
        help="""
        The time live HDS streams will start from the edge of stream.

        Default is 10.0.
        """
    )
    transport.add_argument(
        "--hds-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each HDS segment before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hds-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download HDS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """
    )
    transport.add_argument(
        "--hds-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        HDS segment connect and read timeout.

        Default is 10.0.
        """
    )
    transport.add_argument(
        "--hds-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HDS streams.

        Default is 60.0.
        """
    )
    transport.add_argument(
        "--hls-live-edge",
        type=num(int, min=0),
        metavar="SEGMENTS",
        help="""
        How many segments from the end to start live HLS streams on.

        The lower the value the lower latency from the source you will be,
        but also increases the chance of buffering.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-segment-stream-data",
        action="store_true",
        help="""
        Immediately write segment data into output buffer while downloading.
        """
    )
    transport.add_argument(
        "--hls-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each HLS segment before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-playlist-reload-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to reload the HLS playlist before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-playlist-reload-time",
        metavar="TIME",
        help="""
        Set a custom HLS playlist reload time value, either in seconds
        or by using one of the following keywords:

            segment: The duration of the last segment in the current playlist
            live-edge: The sum of segment durations of the live edge value minus one
            default: The playlist's target duration metadata

        Default is default.
        """
    )
    transport.add_argument(
        "--hls-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download HLS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """
    )
    transport.add_argument(
        "--hls-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        HLS segment connect and read timeout.

        Default is 10.0.
        """)
    transport.add_argument(
        "--hls-segment-ignore-names",
        metavar="NAMES",
        type=comma_list,
        help="""
        A comma-delimited list of segment names that will get filtered out.

        Example: --hls-segment-ignore-names 000,001,002

        This will ignore every segment that ends with 000.ts, 001.ts and 002.ts

        Default is None.
        """
    )
    transport.add_argument(
        "--hls-segment-key-uri",
        metavar="URI",
        type=str,
        help="""
        URI to segment encryption key. If no URI is specified, the URI contained
        in the segments will be used.

        URI can be templated using the following variables, which will be
        replaced with its respective part from the source segment URI:

          {url} {scheme} {netloc} {path} {query}

        Examples:

          --hls-segment-key-uri "https://example.com/hls/encryption_key"
          --hls-segment-key-uri "{scheme}://1.2.3.4{path}{query}"
          --hls-segment-key-uri "{scheme}://{netloc}/custom/path/to/key"

        Default is None.
        """
    )
    transport.add_argument(
        "--hls-audio-select",
        type=comma_list,
        metavar="CODE",
        help="""
        Selects a specific audio source or sources, by language code or name,
        when multiple audio sources are available. Can be * to download all
        audio sources.

        Examples:

          --hls-audio-select "English,German"
          --hls-audio-select "en,de"
          --hls-audio-select "*"

        Note: This is only useful in special circumstances where the regular
        locale option fails, such as when multiple sources of the same language
        exists.
        """)
    transport.add_argument(
        "--hls-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HLS streams.

        Default is 60.0.
        """)
    transport.add_argument(
        "--hls-start-offset",
        type=hours_minutes_seconds,
        metavar="[HH:]MM:SS",
        default=None,
        help="""
        Amount of time to skip from the beginning of the stream. For live
        streams, this is a negative offset from the end of the stream (rewind).

        Default is 00:00:00.
        """)
    transport.add_argument(
        "--hls-duration",
        type=hours_minutes_seconds,
        metavar="[HH:]MM:SS",
        default=None,
        help="""
        Limit the playback duration, useful for watching segments of a stream.
        The actual duration may be slightly longer, as it is rounded to the
        nearest HLS segment.

        Default is unlimited.
        """)
    transport.add_argument(
        "--hls-live-restart",
        action="store_true",
        help="""
        Skip to the beginning of a live stream, or as far back as possible.
        """)
    transport.add_argument(
        "--http-stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HTTP streams.

        Default is 60.0.
        """)
    transport.add_argument(
        "--ringbuffer-size",
        metavar="SIZE",
        type=filesize,
        help="""
        The maximum size of ringbuffer. Add a M or K suffix to specify mega or
        kilo bytes instead of bytes.

        The ringbuffer is used as a temporary storage between the stream and the
        player. This is to allows us to download the stream faster than the
        player wants to read it.

        The smaller the size, the higher chance of the player buffering if there
        are download speed dips and the higher size the more data we can use as
        a storage to catch up from speed dips.

        It also allows you to temporary pause as long as the ringbuffer doesn't
        get full since we continue to download the stream in the background.

        Default is "16M".

        Note: A smaller size is recommended on lower end systems (such as
        Raspberry Pi) when playing stream types that require some extra
        processing (such as HDS) to avoid unnecessary background processing.
        """)
    transport.add_argument(
        "--rtmp-proxy",
        metavar="PROXY",
        help="""
        A SOCKS proxy that RTMP streams will use.

        Example: 127.0.0.1:9050
        """
    )
    transport.add_argument(
        "--rtmp-rtmpdump",
        metavar="FILENAME",
        help="""
        RTMPDump is used to access RTMP streams. You can specify the
        location of the rtmpdump executable if it is not in your PATH.

        Example: "/usr/local/bin/rtmpdump"
        """
    )
    transport.add_argument("--rtmpdump", help=argparse.SUPPRESS)
    transport.add_argument(
        "--rtmp-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from RTMP streams.

        Default is 60.0.
        """
    )
    transport.add_argument(
        "--stream-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each segment before giving
        up.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 3.
        """
    )
    transport.add_argument(
        "--stream-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download segments. Minimum value is
        1 and maximum is 10.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 1.
        """
    )
    transport.add_argument(
        "--stream-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Segment connect and read timeout.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 10.0.
        """)
    transport.add_argument(
        "--stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from streams.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 60.0.
        """)
    transport.add_argument(
        "--subprocess-cmdline",
        action="store_true",
        help="""
        Print the command-line used internally to play the stream.

        This is only available on RTMP streams.
        """
    )
    transport.add_argument(
        "--subprocess-errorlog",
        action="store_true",
        help="""
        Log possible errors from internal subprocesses to a temporary file. The
        file will be saved in your systems temporary directory.

        Useful when debugging rtmpdump related issues.
        """
    )
    transport.add_argument(
        "--subprocess-errorlog-path",
        type=str,
        metavar="PATH",
        help="""
        Log the subprocess errorlog to a specific file rather than a temporary
        file. Takes precedence over subprocess-errorlog.

        Useful when debugging rtmpdump related issues.
        """
    )
    transport.add_argument(
        "--ffmpeg-ffmpeg",
        metavar="FILENAME",
        help="""
        FFMPEG is used to access or mux separate video and audio streams. You
        can specify the location of the ffmpeg executable if it is not in your
        PATH.

        Example: "/usr/local/bin/ffmpeg"
        """
    )
    transport.add_argument(
        "--ffmpeg-verbose",
        action="store_true",
        help="""
        Write the console output from ffmpeg to the console.
        """
    )
    transport.add_argument(
        "--ffmpeg-verbose-path",
        type=str,
        metavar="PATH",
        help="""
        Path to write the output from the ffmpeg console.
        """
    )
    transport.add_argument(
        "--ffmpeg-fout",
        type=str,
        metavar="OUTFORMAT",
        help="""
        When muxing streams, set the output format to OUTFORMAT.

        Default is "matroska".

        Example: "mpegts"
        """
    )
    transport.add_argument(
        "--ffmpeg-video-transcode",
        metavar="CODEC",
        help="""
        When muxing streams, transcode the video to CODEC.

        Default is "copy".

        Example: "h264"
        """
    )
    transport.add_argument(
        "--ffmpeg-audio-transcode",
        metavar="CODEC",
        help="""
        When muxing streams, transcode the audio to CODEC.

        Default is "copy".

        Example: "aac"
        """
    )
    transport.add_argument(
        "--ffmpeg-copyts",
        action="store_true",
        help="""
        Forces the -copyts ffmpeg option and does not remove
        the initial start time offset value.
        """
    )
    transport.add_argument(
        "--ffmpeg-start-at-zero",
        action="store_true",
        help="""
        Enable the -start_at_zero ffmpeg option when using copyts.
        """
    )
    transport.add_argument(
        "--mux-subtitles",
        action="store_true",
        help="""
        Automatically mux available subtitles into the output stream.

        Needs to be supported by the used plugin.
        """
    )

    http = parser.add_argument_group("HTTP options")
    http.add_argument(
        "--http-proxy",
        metavar="HTTP_PROXY",
        help="""
        A HTTP proxy to use for all HTTP requests, including WebSocket connections.
        By default this proxy will be used for all HTTPS requests too.

        Example: "http://hostname:port/"
        """
    )
    http.add_argument(
        "--https-proxy",
        metavar="HTTPS_PROXY",
        help="""
        A HTTPS capable proxy to use for all HTTPS requests.

        Example: "https://hostname:port/"
        """
    )
    http.add_argument(
        "--http-cookie",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A cookie to add to each HTTP request.

        Can be repeated to add multiple cookies.
        """
    )
    http.add_argument(
        "--http-header",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A header to add to each HTTP request.

        Can be repeated to add multiple headers.
        """
    )
    http.add_argument(
        "--http-query-param",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A query parameter to add to each HTTP request.

        Can be repeated to add multiple query parameters.
        """
    )
    http.add_argument(
        "--http-ignore-env",
        action="store_true",
        help="""
        Ignore HTTP settings set in the environment such as environment
        variables (HTTP_PROXY, etc) or ~/.netrc authentication.
        """
    )
    http.add_argument(
        "--http-no-ssl-verify",
        action="store_true",
        help="""
        Don't attempt to verify SSL certificates.

        Usually a bad idea, only use this if you know what you're doing.
        """
    )
    http.add_argument(
        "--http-disable-dh",
        action="store_true",
        help="""
        Disable Diffie Hellman key exchange

        Usually a bad idea, only use this if you know what you're doing.
        """
    )
    http.add_argument(
        "--http-ssl-cert",
        metavar="FILENAME",
        help="""
        SSL certificate to use.

        Expects a .pem file.
        """
    )
    http.add_argument(
        "--http-ssl-cert-crt-key",
        metavar=("CRT_FILENAME", "KEY_FILENAME"),
        nargs=2,
        help="""
        SSL certificate to use.

        Expects a .crt and a .key file.
        """
    )
    http.add_argument(
        "--http-timeout",
        metavar="TIMEOUT",
        type=num(float, min=0),
        help="""
        General timeout used by all HTTP requests except the ones covered by
        other options.

        Default is 20.0.
        """
    )

    return parser
예제 #5
0
class Zattoo(Plugin):
    STREAMS_ZATTOO = ['dash', 'hls7']

    TIME_CONTROL = 60 * 60 * 2
    TIME_SESSION = 60 * 60 * 24 * 30

    arguments = PluginArguments(
        PluginArgument(
            "email",
            requires=["password"],
            metavar="EMAIL",
            help="""
            The email associated with your zattoo account,
            required to access any zattoo stream.
            """),
        PluginArgument(
            "password",
            sensitive=True,
            metavar="PASSWORD",
            help="""
            A zattoo account password to use with --zattoo-email.
            """),
        PluginArgument(
            "purge-credentials",
            action="store_true",
            help="""
            Purge cached zattoo credentials to initiate a new session
            and reauthenticate.
            """),
        PluginArgument(
            'stream-types',
            metavar='TYPES',
            type=comma_list_filter(STREAMS_ZATTOO),
            default=['dash'],
            help='''
            A comma-delimited list of stream types which should be used,
            the following types are allowed:

            - {0}

            Default is "dash".
            '''.format('\n            - '.join(STREAMS_ZATTOO))
        )
    )

    def __init__(self, url):
        super().__init__(url)
        self.domain = self.match.group('base_url')
        self._session_attributes = Cache(
            filename='plugin-cache.json',
            key_prefix='zattoo:attributes:{0}'.format(self.domain))
        self._uuid = self._session_attributes.get('uuid')
        self._authed = (self._session_attributes.get('power_guide_hash')
                        and self._uuid
                        and self.session.http.cookies.get('pzuid', domain=self.domain)
                        and self.session.http.cookies.get('beaker.session.id', domain=self.domain)
                        )
        self._session_control = self._session_attributes.get('session_control',
                                                             False)
        self.base_url = 'https://{0}'.format(self.domain)
        self.headers = {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': self.base_url
        }

    def _hello(self):
        log.debug('_hello ...')
        app_token = self.session.http.get(
            f'{self.base_url}/token.json',
            schema=validate.Schema(validate.parse_json(), {
                'success': bool,
                'session_token': str,
            }, validate.get('session_token'))
        )
        if self._uuid:
            __uuid = self._uuid
        else:
            __uuid = str(uuid.uuid4())
            self._session_attributes.set(
                'uuid', __uuid, expires=self.TIME_SESSION)

        params = {
            'app_version': '3.2120.1',
            'client_app_token': app_token,
            'format': 'json',
            'lang': 'en',
            'uuid': __uuid,
        }
        res = self.session.http.post(
            f'{self.base_url}/zapi/v3/session/hello',
            headers=self.headers,
            data=params,
            schema=validate.Schema(
                validate.parse_json(),
                validate.any({'active': bool}, {'success': bool})
            )
        )
        if res.get('active') or res.get('success'):
            log.debug('Hello was successful.')
        else:
            log.debug('Hello failed.')

    def _login(self, email, password):
        log.debug('_login ...')
        data = self.session.http.post(
            f'{self.base_url}/zapi/v3/account/login',
            headers=self.headers,
            data={
                'login': email,
                'password': password,
                'remember': 'true',
                'format': 'json',
            },
            acceptable_status=(200, 400),
            schema=validate.Schema(validate.parse_json(), validate.any(
                {'active': bool, 'power_guide_hash': str},
                {'success': bool},
            )),
        )

        if data.get('active'):
            log.debug('Login was successful.')
        else:
            log.debug('Login failed.')
            return

        self._authed = data['active']
        self.save_cookies(default_expires=self.TIME_SESSION)
        self._session_attributes.set('power_guide_hash',
                                     data['power_guide_hash'],
                                     expires=self.TIME_SESSION)
        self._session_attributes.set(
            'session_control', True, expires=self.TIME_CONTROL)

    def _watch(self):
        log.debug('_watch ...')
        channel = self.match.group('channel')
        vod_id = self.match.group('vod_id')
        recording_id = self.match.group('recording_id')

        params = {'https_watch_urls': True}
        if channel:
            watch_url = f'{self.base_url}/zapi/watch'
            params_cid = self._get_params_cid(channel)
            if not params_cid:
                return
            params.update(params_cid)
        elif vod_id:
            log.debug('Found vod_id: {0}'.format(vod_id))
            watch_url = f'{self.base_url}/zapi/avod/videos/{vod_id}/watch'
        elif recording_id:
            log.debug('Found recording_id: {0}'.format(recording_id))
            watch_url = f'{self.base_url}/zapi/watch/recording/{recording_id}'
        else:
            log.debug('Missing watch_url')
            return

        zattoo_stream_types = self.get_option('stream-types')
        for stream_type in zattoo_stream_types:
            params_stream_type = {'stream_type': stream_type}
            params.update(params_stream_type)

            data = self.session.http.post(
                watch_url,
                headers=self.headers,
                data=params,
                acceptable_status=(200, 402, 403, 404),
                schema=validate.Schema(validate.parse_json(), validate.any({
                    'success': validate.transform(bool),
                    'stream': {
                        'watch_urls': [{
                            'url': validate.url(),
                            validate.optional('maxrate'): int,
                            validate.optional('audio_channel'): str,
                        }],
                        validate.optional('quality'): str,
                    },
                }, {
                    'success': validate.transform(bool),
                    'internal_code': int,
                    validate.optional('http_status'): int,
                })),
            )

            if not data['success']:
                if data['internal_code'] == 401:
                    log.error(f'invalid stream_type {stream_type}')
                elif data['internal_code'] == 421:
                    log.error('Unfortunately streaming is not permitted in this country or this channel does not exist.')
                elif data['internal_code'] == 422:
                    log.error('Paid subscription required for this channel.')
                    log.info('If paid subscription exist, use --zattoo-purge-credentials to start a new session.')
                else:
                    log.debug(f'unknown error {data!r}')
                    log.debug('Force session reset for watch_url')
                    self.reset_session()
                continue

            log.debug(f'Found data for {stream_type}')
            if stream_type == 'hls7':
                for url in data['stream']['watch_urls']:
                    yield from HLSStream.parse_variant_playlist(self.session, url['url']).items()
            elif stream_type == 'dash':
                for url in data['stream']['watch_urls']:
                    yield from DASHStream.parse_manifest(self.session, url['url']).items()

    def _get_params_cid(self, channel):
        log.debug('get channel ID for {0}'.format(channel))
        try:
            res = self.session.http.get(
                f'{self.base_url}/zapi/v2/cached/channels/{self._session_attributes.get("power_guide_hash")}',
                headers=self.headers,
                params={'details': 'False'}
            )
        except Exception:
            log.debug('Force session reset for _get_params_cid')
            self.reset_session()
            return False

        data = self.session.http.json(
            res, schema=validate.Schema({
                'success': validate.transform(bool),
                'channel_groups': [{
                    'channels': [
                        {
                            'display_alias': str,
                            'cid': str,
                            'qualities': [{
                                'title': str,
                                'stream_types': validate.all(
                                    [str],
                                    validate.filter(lambda n: not re.match(r"(.+_(?:fairplay|playready|widevine))", n))
                                ),
                                'level': str,
                                'availability': str,
                            }],
                        },
                    ],
                }]},
                validate.get('channel_groups'),
            )
        )

        c_list = []
        for d in data:
            for c in d['channels']:
                c_list.append(c)

        cid = None
        zattoo_list = []
        for c in c_list:
            zattoo_list.append(c['display_alias'])
            if c['display_alias'] == channel:
                cid = c['cid']
                log.debug(f'{c!r}')

        log.trace('Available zattoo channels in this country: {0}'.format(
            ', '.join(sorted(zattoo_list))))

        if not cid:
            cid = channel

        log.debug('CHANNEL ID: {0}'.format(cid))
        return {'cid': cid}

    def reset_session(self):
        self._session_attributes.set('power_guide_hash', None, expires=0)
        self._session_attributes.set('uuid', None, expires=0)
        self.clear_cookies()
        self._authed = False

    def _get_streams(self):
        email = self.get_option('email')
        password = self.get_option('password')

        if self.options.get('purge_credentials'):
            self.reset_session()
            log.info('All credentials were successfully removed.')
        elif (self._authed and not self._session_control):
            # check every two hours, if the session is actually valid
            log.debug('Session control for {0}'.format(self.domain))
            active = self.session.http.get(
                f'{self.base_url}/zapi/v3/session',
                schema=validate.Schema(validate.parse_json(),
                                       {'active': bool}, validate.get('active'))
            )
            if active:
                self._session_attributes.set(
                    'session_control', True, expires=self.TIME_CONTROL)
                log.debug('User is logged in')
            else:
                log.debug('User is not logged in')
                self._authed = False

        if not self._authed and (not email and not password):
            log.error(
                'A login for Zattoo is required, use --zattoo-email EMAIL'
                ' --zattoo-password PASSWORD to set them')
            return

        if not self._authed:
            self._hello()
            self._login(email, password)

        if self._authed:
            return self._watch()
예제 #6
0
def build_parser():
    global PARSER
    PARSER = ArgumentParser(fromfile_prefix_chars="@",
                            formatter_class=HelpFormatter,
                            add_help=False,
                            usage="%(prog)s [OPTIONS] <URL> [STREAM]",
                            description=dedent("""
        Streamlink is command-line utility that extracts streams from
        various services and pipes them into a video player of choice.
        """),
                            epilog=dedent("""
        For more in-depth documentation see:
        https://streamlink.github.io
        Please report broken plugins or bugs to the issue tracker on Github:
        https://github.com/streamlink/streamlink/issues
        """))

    general = PARSER.add_argument_group("General options")
    general.add_argument(
        "-h",
        "--help",
        action="store_true",
    )
    general.add_argument(
        "--locale",
        type=str,
        metavar="LOCALE",
    )
    general.add_argument(
        "-l",
        "--loglevel",
        metavar="LEVEL",
        choices=logger.levels,
        default=DEFAULT_LEVEL,
    )
    general.add_argument(
        "--interface",
        type=str,
        metavar="INTERFACE",
    )
    general.add_argument(
        "-4",
        "--ipv4",
        action="store_true",
    )
    general.add_argument(
        "-6",
        "--ipv6",
        action="store_true",
    )

    player = PARSER.add_argument_group("Player options")
    player.add_argument(
        "--player-passthrough",
        metavar="TYPES",
        type=comma_list_filter(STREAM_PASSTHROUGH),
        default=[],
    )

    http = PARSER.add_argument_group("HTTP options")
    http.add_argument(
        "--http-proxy",
        metavar="HTTP_PROXY",
    )
    http.add_argument(
        "--https-proxy",
        metavar="HTTPS_PROXY",
    )
    http.add_argument(
        "--http-cookie",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
    )
    http.add_argument(
        "--http-header",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
    )
    http.add_argument(
        "--http-query-param",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
    )
    http.add_argument(
        "--http-ignore-env",
        action="store_true",
    )
    http.add_argument(
        "--http-no-ssl-verify",
        action="store_true",
    )
    http.add_argument(
        "--http-disable-dh",
        action="store_true",
    )
    http.add_argument(
        "--http-ssl-cert",
        metavar="FILENAME",
    )
    http.add_argument(
        "--http-ssl-cert-crt-key",
        metavar=("CRT_FILENAME", "KEY_FILENAME"),
        nargs=2,
    )
    http.add_argument(
        "--http-timeout",
        metavar="TIMEOUT",
        type=num(float, min=0),
    )

    transport = PARSER.add_argument_group("Stream transport options")
    transport.add_argument(
        "--hds-live-edge",
        type=num(float, min=0),
        metavar="SECONDS",
    )
    transport.add_argument(
        "--hds-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
    )
    transport.add_argument(
        "--hds-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
    )
    transport.add_argument(
        "--hds-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--hds-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--hls-live-edge",
        type=num(int, min=0),
        metavar="SEGMENTS",
    )
    transport.add_argument(
        "--hls-segment-stream-data",
        action="store_true",
    )
    transport.add_argument(
        "--hls-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
    )
    transport.add_argument(
        "--hls-playlist-reload-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
    )
    transport.add_argument(
        "--hls-playlist-reload-time",
        metavar="TIME",
    )
    transport.add_argument(
        "--hls-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
    )
    transport.add_argument(
        "--hls-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--hls-segment-ignore-names",
        metavar="NAMES",
        type=comma_list,
    )
    transport.add_argument(
        "--hls-segment-key-uri",
        metavar="URI",
        type=str,
    )
    transport.add_argument(
        "--hls-audio-select",
        type=comma_list,
        metavar="CODE",
    )
    transport.add_argument(
        "--hls-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--hls-start-offset",
        type=hours_minutes_seconds,
        metavar="HH:MM:SS",
        default=None,
    )
    transport.add_argument(
        "--hls-duration",
        type=hours_minutes_seconds,
        metavar="HH:MM:SS",
        default=None,
    )
    transport.add_argument(
        "--hls-live-restart",
        action="store_true",
    )
    transport.add_argument(
        "--http-stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--ringbuffer-size",
        metavar="SIZE",
        type=filesize,
    )
    transport.add_argument(
        "--rtmp-proxy",
        metavar="PROXY",
    )
    transport.add_argument(
        "--rtmp-rtmpdump",
        metavar="FILENAME",
    )
    transport.add_argument("--rtmpdump", help=argparse.SUPPRESS)
    transport.add_argument(
        "--rtmp-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--stream-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
    )
    transport.add_argument(
        "--stream-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
    )
    transport.add_argument(
        "--stream-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
    )
    transport.add_argument(
        "--subprocess-errorlog",
        action="store_true",
    )
    transport.add_argument(
        "--subprocess-errorlog-path",
        type=str,
        metavar="PATH",
    )
    transport.add_argument(
        "--ffmpeg-ffmpeg",
        metavar="FILENAME",
    )
    transport.add_argument(
        "--ffmpeg-verbose",
        action="store_true",
    )
    transport.add_argument(
        "--ffmpeg-verbose-path",
        type=str,
        metavar="PATH",
    )
    transport.add_argument(
        "--ffmpeg-fout",
        type=str,
        metavar="OUTFORMAT",
    )
    transport.add_argument(
        "--ffmpeg-video-transcode",
        metavar="CODEC",
    )
    transport.add_argument(
        "--ffmpeg-audio-transcode",
        metavar="CODEC",
    )
    transport.add_argument(
        "--ffmpeg-copyts",
        action="store_true",
    )
    transport.add_argument(
        "--ffmpeg-start-at-zero",
        action="store_true",
    )
    transport.add_argument(
        "--mux-subtitles",
        action="store_true",
    )

    stream = PARSER.add_argument_group("Stream options")
    stream.add_argument(
        "--stream-types",
        "--stream-priority",
        metavar="TYPES",
        type=comma_list,
    )
    stream.add_argument(
        "--stream-sorting-excludes",
        metavar="STREAMS",
        type=comma_list,
    )
    stream.add_argument(
        "--retry-open",
        metavar="ATTEMPTS",
        type=num(int, min=0),
        default=1,
    )

    return PARSER
예제 #7
0
def build_parser():
    parser = ArgumentParser(prog="streamlink",
                            fromfile_prefix_chars="@",
                            formatter_class=HelpFormatter,
                            add_help=False,
                            usage="%(prog)s [OPTIONS] <URL> [STREAM]",
                            description=dedent("""
        Streamlink is command-line utility that extracts streams from various
        services and pipes them into a video player of choice.
        """),
                            epilog=dedent("""
        For more in-depth documentation see:
          https://streamlink.github.io

        Please report broken plugins or bugs to the issue tracker on Github:
          https://github.com/streamlink/streamlink/issues
        """))

    positional = parser.add_argument_group("Positional arguments")
    positional.add_argument("url",
                            metavar="URL",
                            nargs="?",
                            help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted ("https://"),
        depending on the implementation of the plugin being used.

        Alternatively, the URL can also be specified by using the --url option.
        """)
    positional.add_argument("stream",
                            metavar="STREAM",
                            nargs="?",
                            type=comma_list,
                            help="""
        Stream to play.

        Use "best" or "worst" for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        If no stream is specified and --default-stream is not used, then a list
        of available streams will be printed.
        """)

    general = parser.add_argument_group("General options")
    general.add_argument("-h",
                         "--help",
                         action="store_true",
                         help="""
        Show this help message and exit.
        """)
    general.add_argument("-V",
                         "--version",
                         action="version",
                         version="%(prog)s {0}".format(LIVESTREAMER_VERSION),
                         help="""
        Show version number and exit.
        """)
    general.add_argument("--plugins",
                         action="store_true",
                         help="""
        Print a list of all currently installed plugins.
        """)
    general.add_argument("--plugin-dirs",
                         metavar="DIRECTORY",
                         type=comma_list,
                         help="""
        Attempts to load plugins from these directories.

        Multiple directories can be used by separating them with a comma.
        """)
    general.add_argument("--can-handle-url",
                         metavar="URL",
                         help="""
        Check if Streamlink has a plugin that can handle the specified URL.

        Returns status code 1 for false and 0 for true.

        Useful for external scripting.
        """)
    general.add_argument("--can-handle-url-no-redirect",
                         metavar="URL",
                         help="""
        Same as --can-handle-url but without following redirects when looking up
        the URL.
        """)
    general.add_argument("--config",
                         action="append",
                         metavar="FILENAME",
                         help="""
        Load options from this config file.

        Can be repeated to load multiple files, in which case the options are
        merged on top of each other where the last config has highest priority.
        """)
    general.add_argument("-l",
                         "--loglevel",
                         metavar="LEVEL",
                         choices=logger.levels,
                         default="info",
                         help="""
        Set the log message threshold.

        Valid levels are: none, error, warning, info, debug, trace
        """)
    general.add_argument("-Q",
                         "--quiet",
                         action="store_true",
                         help="""
        Hide all log output.

        Alias for "--loglevel none".
        """)
    general.add_argument("-j",
                         "--json",
                         action="store_true",
                         help="""
        Output JSON representations instead of the normal text output.

        Useful for external scripting.
        """)
    general.add_argument("--auto-version-check",
                         type=boolean,
                         metavar="{yes,true,1,on,no,false,0,off}",
                         default=False,
                         help="""
        Enable or disable the automatic check for a new version of Streamlink.

        Default is "no".
        """)
    general.add_argument("--version-check",
                         action="store_true",
                         help="""
        Runs a version check and exits.
        """)
    general.add_argument("--locale",
                         type=str,
                         metavar="LOCALE",
                         help="""
        The preferred locale setting, for selecting the preferred subtitle and
        audio language.

        The locale is formatted as [language_code]_[country_code], eg. en_US or
        es_ES.

        Default is system locale.
        """)
    general.add_argument("--twitch-oauth-authenticate",
                         action="store_true",
                         help="""
        Open a web browser where you can grant Streamlink access to your Twitch
        account which creates a token for use with --twitch-oauth-token.
        """)

    player = parser.add_argument_group("Player options")
    player.add_argument("-p",
                        "--player",
                        metavar="COMMAND",
                        default=find_default_player(),
                        help="""
        Player to feed stream data to. By default, VLC will be used if it can be
        found in its default location.

        This is a shell-like syntax to support using a specific player:

          %(prog)s --player=vlc <url> [stream]

        Absolute or relative paths can also be passed via this option in the
        event the player's executable can not be resolved:

          %(prog)s --player=/path/to/vlc <url> [stream]
          %(prog)s --player=./vlc-player/vlc <url> [stream]

        To use a player that is located in a path with spaces you must quote the
        parameter or its value:

          %(prog)s "--player=/path/with spaces/vlc" <url> [stream]
          %(prog)s --player "C:\\path\\with spaces\\mpc-hc64.exe" <url> [stream]

        Options may also be passed to the player. For example:

          %(prog)s --player "vlc --file-caching=5000" <url> [stream]

        As an alternative to this, see the --player-args parameter, which does
        not log any custom player arguments.
        """)
    player.add_argument("-a",
                        "--player-args",
                        metavar="ARGUMENTS",
                        default=DEFAULT_PLAYER_ARGUMENTS,
                        help="""
        This option allows you to customize the default arguments which are put
        together with the value of --player to create a command to execute.
        Unlike the --player parameter, custom player arguments will not be logged.

        This value can contain formatting variables surrounded by curly braces,
        {{ and }}. If you need to include a brace character, it can be escaped
        by doubling, e.g. {{{{ and }}}}.

        Formatting variables available:

        filename
            This is the filename that the player will use. It's usually "-"
            (stdin), but can also be a URL or a file depending on the options
            used.

        It's usually enough to use --player instead of this unless you need to
        add arguments after the filename.

        Default is "{0}".

        Example:

          %(prog)s -p vlc -a "--play-and-exit {{filename}}" <url> [stream]

        """.format(DEFAULT_PLAYER_ARGUMENTS))
    player.add_argument("-v",
                        "--verbose-player",
                        action="store_true",
                        help="""
        Allow the player to display its console output.
        """)
    player.add_argument("-n",
                        "--player-fifo",
                        "--fifo",
                        action="store_true",
                        help="""
        Make the player read the stream through a named pipe instead of the
        stdin pipe.
        """)
    player.add_argument("--player-http",
                        action="store_true",
                        help="""
        Make the player read the stream through HTTP instead of the stdin pipe.
        """)
    player.add_argument("--player-continuous-http",
                        action="store_true",
                        help="""
        Make the player read the stream through HTTP, but unlike --player-http
        it will continuously try to open the stream if the player requests it.

        This makes it possible to handle stream disconnects if your player is
        capable of reconnecting to a HTTP stream. This is usually done by
        setting your player to a "repeat mode".
        """)
    player.add_argument("--player-external-http",
                        action="store_true",
                        help="""
        Serve stream data through HTTP without running any player. This is
        useful to allow external devices like smartphones or streaming boxes to
        watch streams they wouldn't be able to otherwise.

        Behavior will be similar to the continuous HTTP option, but no player
        program will be started, and the server will listen on all available
        connections instead of just in the local (loopback) interface.

        The URLs that can be used to access the stream will be printed to the
        console, and the server can be interrupted using CTRL-C.
        """)
    player.add_argument("--player-external-http-port",
                        metavar="PORT",
                        type=num(int, min=0, max=65535),
                        default=0,
                        help="""
        A fixed port to use for the external HTTP server if that mode is
        enabled. Omit or set to 0 to use a random high ( >1024) port.
        """)
    player.add_argument("--player-passthrough",
                        metavar="TYPES",
                        type=comma_list_filter(STREAM_PASSTHROUGH),
                        default=[],
                        help="""
        A comma-delimited list of stream types to pass to the player as a URL to
        let it handle the transport of the stream instead.

        Stream types that can be converted into a playable URL are:

        - {0}

        Make sure your player can handle the stream type when using this.
        """.format("\n        - ".join(STREAM_PASSTHROUGH)))
    player.add_argument("--player-no-close",
                        action="store_true",
                        help="""
        By default Streamlink will close the player when the stream
        ends. This is to avoid "dead" GUI players lingering after a
        stream ends.

        It does however have the side-effect of sometimes closing a
        player before it has played back all of its cached data.

        This option will instead let the player decide when to exit.
        """)

    output = parser.add_argument_group("File output options")
    output.add_argument("-o",
                        "--output",
                        metavar="FILENAME",
                        help="""
        Write stream data to FILENAME instead of playing it.

        You will be prompted if the file already exists.
        """)
    output.add_argument("-f",
                        "--force",
                        action="store_true",
                        help="""
        When using -o, always write to file even if it already exists.
        """)
    output.add_argument("-O",
                        "--stdout",
                        action="store_true",
                        help="""
        Write stream data to stdout instead of playing it.
        """)

    stream = parser.add_argument_group("Stream options")
    stream.add_argument("--url",
                        dest="url_param",
                        metavar="URL",
                        help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted (https://),
        depending on the implementation of the plugin being used.

        This is an alternative to setting the URL using a positional argument
        and can be useful if set in a config file.
        """)
    stream.add_argument("--default-stream",
                        type=comma_list,
                        metavar="STREAM",
                        help="""
        Stream to play.

        Use "best" or "worst" for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        This is an alternative to setting the stream using a positional argument
        and can be useful if set in a config file.
        """)
    stream.add_argument("--retry-streams",
                        metavar="DELAY",
                        type=num(float, min=0),
                        help="""
        Retry fetching the list of available streams until streams are found
        while waiting DELAY second(s) between each attempt. If unset, only one
        attempt will be made to fetch the list of streams available.

        The number of fetch retry attempts can be capped with --retry-max.
        """)
    stream.add_argument("--retry-max",
                        metavar="COUNT",
                        type=num(int, min=-1),
                        help="""
        When using --retry-streams, stop retrying the fetch after COUNT retry
        attempt(s). Fetch will retry infinitely if COUNT is zero or unset.

        If --retry-max is set without setting --retry-streams, the delay between
        retries will default to 1 second.
        """)
    stream.add_argument("--retry-open",
                        metavar="ATTEMPTS",
                        type=num(int, min=0),
                        default=1,
                        help="""
        After a successful fetch, try ATTEMPTS time(s) to open the stream until
        giving up.

        Default is 1.
        """)
    stream.add_argument("--stream-types",
                        "--stream-priority",
                        metavar="TYPES",
                        type=comma_list,
                        help="""
        A comma-delimited list of stream types to allow.

        The order will be used to separate streams when there are multiple
        streams with the same name but different stream types. Any stream type
        not listed will be omitted from the available streams list.  A ``*`` can
        be used as a wildcard to match any other type of stream, eg. muxed-stream.

        Default is "rtmp,hls,hds,http,akamaihd,*".
        """)
    stream.add_argument("--stream-sorting-excludes",
                        metavar="STREAMS",
                        type=comma_list,
                        help="""
        Fine tune best/worst synonyms by excluding unwanted streams.

        Uses a filter expression in the format:

          [operator]<value>

        Valid operators are >, >=, < and <=. If no operator is specified then
        equality is tested.

        For example this will exclude streams ranked higher than "480p":

          ">480p"

        Multiple filters can be used by separating each expression with a comma.

        For example this will exclude streams from two quality types:

          ">480p,>medium"

        """)

    transport = parser.add_argument_group("Stream transport options")
    transport.add_argument("--hds-live-edge",
                           type=num(float, min=0),
                           metavar="SECONDS",
                           help="""
        The time live HDS streams will start from the edge of stream.

        Default is 10.0.
        """)
    transport.add_argument("--hds-segment-attempts",
                           type=num(int, min=0),
                           metavar="ATTEMPTS",
                           help="""
        How many attempts should be done to download each HDS segment before
        giving up.

        Default is 3.
        """)
    transport.add_argument("--hds-segment-threads",
                           type=num(int, max=10),
                           metavar="THREADS",
                           help="""
        The size of the thread pool used to download HDS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """)
    transport.add_argument("--hds-segment-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        HDS segment connect and read timeout.

        Default is 10.0.
        """)
    transport.add_argument("--hds-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Timeout for reading data from HDS streams.

        Default is 60.0.
        """)
    transport.add_argument("--hls-live-edge",
                           type=num(int, min=0),
                           metavar="SEGMENTS",
                           help="""
        How many segments from the end to start live HLS streams on.

        The lower the value the lower latency from the source you will be,
        but also increases the chance of buffering.

        Default is 3.
        """)
    transport.add_argument("--hls-segment-attempts",
                           type=num(int, min=0),
                           metavar="ATTEMPTS",
                           help="""
        How many attempts should be done to download each HLS segment before
        giving up.

        Default is 3.
        """)
    transport.add_argument("--hls-playlist-reload-attempts",
                           type=num(int, min=0),
                           metavar="ATTEMPTS",
                           help="""
        How many attempts should be done to reload the HLS playlist before
        giving up.

        Default is 3.
        """)
    transport.add_argument("--hls-segment-threads",
                           type=num(int, max=10),
                           metavar="THREADS",
                           help="""
        The size of the thread pool used to download HLS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """)
    transport.add_argument("--hls-segment-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        HLS segment connect and read timeout.

        Default is 10.0.
        """)
    transport.add_argument("--hls-segment-ignore-names",
                           metavar="NAMES",
                           type=comma_list,
                           help="""
        A comma-delimited list of segment names that will not be fetched.

        Example: --hls-segment-ignore-names 000,001,002

        This will ignore every segment that ends with 000.ts, 001.ts and 002.ts

        Default is None.

        Note: The --hls-timeout must be increased, to a time that is longer than
        the ignored break.
        """)
    transport.add_argument("--hls-audio-select",
                           type=comma_list,
                           metavar="CODE",
                           help="""
        Selects a specific audio source or sources, by language code or name,
        when multiple audio sources are available. Can be * to download all
        audio sources.

        Examples:

          --hls-audio-select "English,German"
          --hls-audio-select "en,de"
          --hls-audio-select "*"

        Note: This is only useful in special circumstances where the regular
        locale option fails, such as when multiple sources of the same language
        exists.
        """)
    transport.add_argument("--hls-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Timeout for reading data from HLS streams.

        Default is 60.0.
        """)
    transport.add_argument("--hls-start-offset",
                           type=hours_minutes_seconds,
                           metavar="HH:MM:SS",
                           default=None,
                           help="""
        Amount of time to skip from the beginning of the stream. For live
        streams, this is a negative offset from the end of the stream (rewind).

        Default is 00:00:00.
        """)
    transport.add_argument("--hls-duration",
                           type=hours_minutes_seconds,
                           metavar="HH:MM:SS",
                           default=None,
                           help="""
        Limit the playback duration, useful for watching segments of a stream.
        The actual duration may be slightly longer, as it is rounded to the
        nearest HLS segment.

        Default is unlimited.
        """)
    transport.add_argument("--hls-live-restart",
                           action="store_true",
                           help="""
        Skip to the beginning of a live stream, or as far back as possible.
        """)
    transport.add_argument("--http-stream-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Timeout for reading data from HTTP streams.

        Default is 60.0.
        """)
    transport.add_argument("--ringbuffer-size",
                           metavar="SIZE",
                           type=filesize,
                           help="""
        The maximum size of ringbuffer. Add a M or K suffix to specify mega or
        kilo bytes instead of bytes.

        The ringbuffer is used as a temporary storage between the stream and the
        player. This is to allows us to download the stream faster than the
        player wants to read it.

        The smaller the size, the higher chance of the player buffering if there
        are download speed dips and the higher size the more data we can use as
        a storage to catch up from speed dips.

        It also allows you to temporary pause as long as the ringbuffer doesn't
        get full since we continue to download the stream in the background.

        Default is "16M".

        Note: A smaller size is recommended on lower end systems (such as
        Raspberry Pi) when playing stream types that require some extra
        processing (such as HDS) to avoid unnecessary background processing.
        """)
    transport.add_argument("--rtmp-proxy",
                           "--rtmpdump-proxy",
                           metavar="PROXY",
                           help="""
        A SOCKS proxy that RTMP streams will use.

        Example: 127.0.0.1:9050
        """)
    transport.add_argument("--rtmp-rtmpdump",
                           "--rtmpdump",
                           "-r",
                           metavar="FILENAME",
                           help="""
        RTMPDump is used to access RTMP streams. You can specify the
        location of the rtmpdump executable if it is not in your PATH.

        Example: "/usr/local/bin/rtmpdump"
        """)
    transport.add_argument("--rtmp-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Timeout for reading data from RTMP streams.

        Default is 60.0.
        """)
    transport.add_argument("--stream-segment-attempts",
                           type=num(int, min=0),
                           metavar="ATTEMPTS",
                           help="""
        How many attempts should be done to download each segment before giving
        up.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 3.
        """)
    transport.add_argument("--stream-segment-threads",
                           type=num(int, max=10),
                           metavar="THREADS",
                           help="""
        The size of the thread pool used to download segments. Minimum value is
        1 and maximum is 10.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 1.
        """)
    transport.add_argument("--stream-segment-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Segment connect and read timeout.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 10.0.
        """)
    transport.add_argument("--stream-timeout",
                           type=num(float, min=0),
                           metavar="TIMEOUT",
                           help="""
        Timeout for reading data from streams.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 60.0.
        """)
    transport.add_argument("--stream-url",
                           action="store_true",
                           help="""
        If possible, translate the stream to a URL and print it.
        """)
    transport.add_argument("--subprocess-cmdline",
                           "--cmdline",
                           "-c",
                           action="store_true",
                           help="""
        Print the command-line used internally to play the stream.

        This is only available on RTMP streams.
        """)
    transport.add_argument("--subprocess-errorlog",
                           "--errorlog",
                           "-e",
                           action="store_true",
                           help="""
        Log possible errors from internal subprocesses to a temporary file. The
        file will be saved in your systems temporary directory.

        Useful when debugging rtmpdump related issues.
        """)
    transport.add_argument("--subprocess-errorlog-path",
                           "--errorlog-path",
                           type=str,
                           metavar="PATH",
                           help="""
        Log the subprocess errorlog to a specific file rather than a temporary
        file. Takes precedence over subprocess-errorlog.

        Useful when debugging rtmpdump related issues.
        """)
    transport.add_argument("--ffmpeg-ffmpeg",
                           metavar="FILENAME",
                           help="""
        FFMPEG is used to access or mux separate video and audio streams. You
        can specify the location of the ffmpeg executable if it is not in your
        PATH.

        Example: "/usr/local/bin/ffmpeg"
        """)
    transport.add_argument("--ffmpeg-verbose",
                           action="store_true",
                           help="""
        Write the console output from ffmpeg to the console.
        """)
    transport.add_argument("--ffmpeg-verbose-path",
                           type=str,
                           metavar="PATH",
                           help="""
        Path to write the output from the ffmpeg console.
        """)
    transport.add_argument("--ffmpeg-video-transcode",
                           metavar="CODEC",
                           help="""
        When muxing streams transcode the video to this CODEC.

        Default is "copy".

        Example: "h264"
        """)
    transport.add_argument("--ffmpeg-audio-transcode",
                           metavar="CODEC",
                           help="""
        When muxing streams transcode the audio to this CODEC.

        Default is "copy".

        Example: "aac"
        """)

    http = parser.add_argument_group("HTTP options")
    http.add_argument("--http-proxy",
                      metavar="HTTP_PROXY",
                      help="""
        A HTTP proxy to use for all HTTP requests.

        Example: "http://hostname:port/"
        """)
    http.add_argument("--https-proxy",
                      metavar="HTTPS_PROXY",
                      help="""
        A HTTPS capable proxy to use for all HTTPS requests.

        Example: "https://hostname:port/"
        """)
    http.add_argument("--http-cookie",
                      metavar="KEY=VALUE",
                      type=keyvalue,
                      action="append",
                      help="""
        A cookie to add to each HTTP request.

        Can be repeated to add multiple cookies.
        """)
    http.add_argument("--http-header",
                      metavar="KEY=VALUE",
                      type=keyvalue,
                      action="append",
                      help="""
        A header to add to each HTTP request.

        Can be repeated to add multiple headers.
        """)
    http.add_argument("--http-query-param",
                      metavar="KEY=VALUE",
                      type=keyvalue,
                      action="append",
                      help="""
        A query parameter to add to each HTTP request.

        Can be repeated to add multiple query parameters.
        """)
    http.add_argument("--http-ignore-env",
                      action="store_true",
                      help="""
        Ignore HTTP settings set in the environment such as environment
        variables (HTTP_PROXY, etc) or ~/.netrc authentication.
        """)
    http.add_argument("--http-no-ssl-verify",
                      action="store_true",
                      help="""
        Don't attempt to verify SSL certificates.

        Usually a bad idea, only use this if you know what you're doing.
        """)
    http.add_argument("--http-disable-dh",
                      action="store_true",
                      help="""
        Disable Diffie Hellman key exchange

        Usually a bad idea, only use this if you know what you're doing.
        """)
    http.add_argument("--http-ssl-cert",
                      metavar="FILENAME",
                      help="""
        SSL certificate to use.

        Expects a .pem file.
        """)
    http.add_argument("--http-ssl-cert-crt-key",
                      metavar=("CRT_FILENAME", "KEY_FILENAME"),
                      nargs=2,
                      help="""
        SSL certificate to use.

        Expects a .crt and a .key file.
        """)
    http.add_argument("--http-timeout",
                      metavar="TIMEOUT",
                      type=num(float, min=0),
                      help="""
        General timeout used by all HTTP requests except the ones covered by
        other options.

        Default is 20.0.
        """)

    # Deprecated options
    stream.add_argument("--best-stream-default",
                        action="store_true",
                        help=argparse.SUPPRESS)
    player.add_argument("-q",
                        "--quiet-player",
                        action="store_true",
                        help=argparse.SUPPRESS)
    transport.add_argument("--hds-fragment-buffer",
                           type=int,
                           metavar="fragments",
                           help=argparse.SUPPRESS)
    http.add_argument("--http-cookies",
                      metavar="COOKIES",
                      help=argparse.SUPPRESS)
    http.add_argument("--http-headers",
                      metavar="HEADERS",
                      help=argparse.SUPPRESS)
    http.add_argument("--http-query-params",
                      metavar="PARAMS",
                      help=argparse.SUPPRESS)
    general.add_argument("--no-version-check",
                         action="store_true",
                         help=argparse.SUPPRESS)
    return parser
예제 #8
0
def build_parser():
    parser = ArgumentParser(
        prog="streamlink",
        fromfile_prefix_chars="@",
        formatter_class=HelpFormatter,
        add_help=False,
        usage="%(prog)s [OPTIONS] <URL> [STREAM]",
        description=dedent("""
        Streamlink is command-line utility that extracts streams from various
        services and pipes them into a video player of choice.
        """),
        epilog=dedent("""
        For more in-depth documentation see:
          https://streamlink.github.io

        Please report broken plugins or bugs to the issue tracker on Github:
          https://github.com/streamlink/streamlink/issues
        """)
    )

    positional = parser.add_argument_group("Positional arguments")
    positional.add_argument(
        "url",
        metavar="URL",
        nargs="?",
        help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted ("https://"),
        depending on the implementation of the plugin being used.

        Alternatively, the URL can also be specified by using the --url option.
        """
    )
    positional.add_argument(
        "stream",
        metavar="STREAM",
        nargs="?",
        type=comma_list,
        help="""
        Stream to play.

        Use ``best`` or ``worst`` for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        If no stream is specified and --default-stream is not used, then a list
        of available streams will be printed.
        """
    )

    general = parser.add_argument_group("General options")
    general.add_argument(
        "-h", "--help",
        action="store_true",
        help="""
        Show this help message and exit.
        """
    )
    general.add_argument(
        "-V", "--version",
        action="version",
        version="%(prog)s {0}".format(LIVESTREAMER_VERSION),
        help="""
        Show version number and exit.
        """
    )
    general.add_argument(
        "--plugins",
        action="store_true",
        help="""
        Print a list of all currently installed plugins.
        """
    )
    general.add_argument(
        "--plugin-dirs",
        metavar="DIRECTORY",
        type=comma_list,
        help="""
        Attempts to load plugins from these directories.

        Multiple directories can be used by separating them with a comma.
        """
    )
    general.add_argument(
        "--can-handle-url",
        metavar="URL",
        help="""
        Check if Streamlink has a plugin that can handle the specified URL.

        Returns status code 1 for false and 0 for true.

        Useful for external scripting.
        """
    )
    general.add_argument(
        "--can-handle-url-no-redirect",
        metavar="URL",
        help="""
        Same as --can-handle-url but without following redirects when looking up
        the URL.
        """
    )
    general.add_argument(
        "--config",
        action="append",
        metavar="FILENAME",
        help="""
        Load options from this config file.

        Can be repeated to load multiple files, in which case the options are
        merged on top of each other where the last config has highest priority.
        """
    )
    general.add_argument(
        "-l", "--loglevel",
        metavar="LEVEL",
        choices=logger.levels,
        default="info",
        help="""
        Set the log message threshold.

        Valid levels are: none, error, warning, info, debug, trace
        """
    )
    general.add_argument(
        "-Q", "--quiet",
        action="store_true",
        help="""
        Hide all log output.

        Alias for "--loglevel none".
        """
    )
    general.add_argument(
        "-j", "--json",
        action="store_true",
        help="""
        Output JSON representations instead of the normal text output.

        Useful for external scripting.
        """
    )
    general.add_argument(
        "--auto-version-check",
        type=boolean,
        metavar="{yes,true,1,on,no,false,0,off}",
        default=False,
        help="""
        Enable or disable the automatic check for a new version of Streamlink.

        Default is "no".
        """
    )
    general.add_argument(
        "--version-check",
        action="store_true",
        help="""
        Runs a version check and exits.
        """
    )
    general.add_argument(
        "--locale",
        type=str,
        metavar="LOCALE",
        help="""
        The preferred locale setting, for selecting the preferred subtitle and
        audio language.

        The locale is formatted as [language_code]_[country_code], eg. en_US or
        es_ES.

        Default is system locale.
        """
    )
    general.add_argument(
        "--twitch-oauth-authenticate",
        action="store_true",
        help="""
        Open a web browser where you can grant Streamlink access to your Twitch
        account which creates a token for use with --twitch-oauth-token.
        """
    )

    player = parser.add_argument_group("Player options")
    player.add_argument(
        "-p", "--player",
        metavar="COMMAND",
        default=find_default_player(),
        help="""
        Player to feed stream data to. By default, VLC will be used if it can be
        found in its default location.

        This is a shell-like syntax to support using a specific player:

          %(prog)s --player=vlc <url> [stream]

        Absolute or relative paths can also be passed via this option in the
        event the player's executable can not be resolved:

          %(prog)s --player=/path/to/vlc <url> [stream]
          %(prog)s --player=./vlc-player/vlc <url> [stream]

        To use a player that is located in a path with spaces you must quote the
        parameter or its value:

          %(prog)s "--player=/path/with spaces/vlc" <url> [stream]
          %(prog)s --player "C:\\path\\with spaces\\mpc-hc64.exe" <url> [stream]

        Options may also be passed to the player. For example:

          %(prog)s --player "vlc --file-caching=5000" <url> [stream]

        As an alternative to this, see the --player-args parameter, which does
        not log any custom player arguments.
        """
    )
    player.add_argument(
        "-a", "--player-args",
        metavar="ARGUMENTS",
        default=DEFAULT_PLAYER_ARGUMENTS,
        help="""
        This option allows you to customize the default arguments which are put
        together with the value of --player to create a command to execute.
        Unlike the --player parameter, custom player arguments will not be logged.

        This value can contain formatting variables surrounded by curly braces,
        {{ and }}. If you need to include a brace character, it can be escaped
        by doubling, e.g. {{{{ and }}}}.

        Formatting variables available:

        {{filename}}
            This is the filename that the player will use. It's usually "-"
            (stdin), but can also be a URL or a file depending on the options
            used.

        It's usually enough to use --player instead of this unless you need to
        add arguments after the filename.

        Default is "{0}".

        Example:

          %(prog)s -p vlc -a "--play-and-exit {{filename}}" <url> [stream]

        """.format(DEFAULT_PLAYER_ARGUMENTS)
    )
    player.add_argument(
        "-v", "--verbose-player",
        action="store_true",
        help="""
        Allow the player to display its console output.
        """
    )
    player.add_argument(
        "-n", "--player-fifo", "--fifo",
        action="store_true",
        help="""
        Make the player read the stream through a named pipe instead of the
        stdin pipe.
        """
    )
    player.add_argument(
        "--player-http",
        action="store_true",
        help="""
        Make the player read the stream through HTTP instead of the stdin pipe.
        """
    )
    player.add_argument(
        "--player-continuous-http",
        action="store_true",
        help="""
        Make the player read the stream through HTTP, but unlike --player-http
        it will continuously try to open the stream if the player requests it.

        This makes it possible to handle stream disconnects if your player is
        capable of reconnecting to a HTTP stream. This is usually done by
        setting your player to a "repeat mode".
        """
    )
    player.add_argument(
        "--player-external-http",
        action="store_true",
        help="""
        Serve stream data through HTTP without running any player. This is
        useful to allow external devices like smartphones or streaming boxes to
        watch streams they wouldn't be able to otherwise.

        Behavior will be similar to the continuous HTTP option, but no player
        program will be started, and the server will listen on all available
        connections instead of just in the local (loopback) interface.

        The URLs that can be used to access the stream will be printed to the
        console, and the server can be interrupted using CTRL-C.
        """
    )
    player.add_argument(
        "--player-external-http-port",
        metavar="PORT",
        type=num(int, min=0, max=65535),
        default=0,
        help="""
        A fixed port to use for the external HTTP server if that mode is
        enabled. Omit or set to 0 to use a random high ( >1024) port.
        """
    )
    player.add_argument(
        "--player-passthrough",
        metavar="TYPES",
        type=comma_list_filter(STREAM_PASSTHROUGH),
        default=[],
        help="""
        A comma-delimited list of stream types to pass to the player as a URL to
        let it handle the transport of the stream instead.

        Stream types that can be converted into a playable URL are:

        - {0}

        Make sure your player can handle the stream type when using this.
        """.format("\n        - ".join(STREAM_PASSTHROUGH))
    )
    player.add_argument(
        "--player-no-close",
        action="store_true",
        help="""
        By default Streamlink will close the player when the stream
        ends. This is to avoid "dead" GUI players lingering after a
        stream ends.

        It does however have the side-effect of sometimes closing a
        player before it has played back all of its cached data.

        This option will instead let the player decide when to exit.
        """
    )
    player.add_argument(
        "-t", "--title",
        metavar="TITLE",
        help="""
        This option allows you to supply a title to be displayed in the
        title bar of the window that the video player is launched in.

        This value can contain formatting variables surrounded by curly braces,
        {{ and }}. If you need to include a brace character, it can be escaped
        by doubling, e.g. {{{{ and }}}}.

        This option is only supported for the following players: {0}.

        VLC specific information:
            VLC has certain codes you can use inside your title.
            These are accessible inside --title by using a backslash
            before the dollar sign VLC uses to denote a format character.

            e.g. to put the current date in your VLC window title,
            the string "\\$A" could be inserted inside your --title string.

            A full list of the format codes VLC uses is available here:
            https://wiki.videolan.org/Documentation:Format_String/

        mpv specific information:
            mpv has certain codes you can use inside your title.
            These are accessible inside --title by using a backslash
            before the dollar sign mpv uses to denote a format character.

            e.g. to put the current version of mpv running inside your
            mpv window title, the string "\\${{{{mpv-version}}}}" could be
            inserted inside your --title string.

            A full list of the format codes mpv uses is available here:
            https://mpv.io/manual/stable/#property-expansion

        Formatting variables available to use in --title:

        {{title}}
            If available, this is the title of the stream.
            Otherwise, it is the string "{1}"

        {{author}}
            If available, this is the author of the stream.
            Otherwise, it is the string "{2}"

        {{category}}
            If available, this is the category the stream has been placed into.

            - For Twitch, this is the game being played
            - For YouTube, it's the category e.g. Gaming, Sports, Music...

            Otherwise, it is the string "{3}"

        {{game}}
            This is just a synonym for {{category}} which may make more sense for
            gaming oriented platforms. "Game being played" is a way to categorize
            the stream, so it doesn't need its own separate handling.

        Examples:

            %(prog)s -p vlc --title "{{title}} -!- {{author}} -!- {{category}} \\$A" <url> [stream]
            %(prog)s -p mpv --title "{{title}} -- {{author}} -- {{category}} -- (\\${{{{mpv-version}}}})" <url> [stream]

        """.format(', '.join(sorted(SUPPORTED_PLAYERS.keys())),
                   DEFAULT_STREAM_METADATA['title'],
                   DEFAULT_STREAM_METADATA['author'],
                   DEFAULT_STREAM_METADATA['category'])
    )

    output = parser.add_argument_group("File output options")
    output.add_argument(
        "-o", "--output",
        metavar="FILENAME",
        help="""
        Write stream data to FILENAME instead of playing it.

        You will be prompted if the file already exists.
        """
    )
    output.add_argument(
        "-f", "--force",
        action="store_true",
        help="""
        When using -o or -r, always write to file even if it already exists.
        """
    )
    output.add_argument(
        "-O", "--stdout",
        action="store_true",
        help="""
        Write stream data to stdout instead of playing it.
        """
    )
    output.add_argument(
        "-r", "--record",
        metavar="FILENAME",
        help="""
        Open the stream in the player, while at the same time writing it to FILENAME.

        You will be prompted if the file already exists.
        """
    )
    output.add_argument(
        "-R", "--record-and-pipe",
        metavar="FILENAME",
        help="""
        Write stream data to stdout, while at the same time writing it to FILENAME.

        You will be prompted if the file already exists.
        """
    )

    stream = parser.add_argument_group("Stream options")
    stream.add_argument(
        "--url",
        dest="url_param",
        metavar="URL",
        help="""
        A URL to attempt to extract streams from.

        Usually, the protocol of http(s) URLs can be omitted (https://),
        depending on the implementation of the plugin being used.

        This is an alternative to setting the URL using a positional argument
        and can be useful if set in a config file.
        """
    )
    stream.add_argument(
        "--default-stream",
        type=comma_list,
        metavar="STREAM",
        help="""
        Stream to play.

        Use ``best`` or ``worst`` for selecting the highest or lowest available
        quality.

        Fallback streams can be specified by using a comma-separated list:

          "720p,480p,best"

        This is an alternative to setting the stream using a positional argument
        and can be useful if set in a config file.
        """
    )
    stream.add_argument(
        "--retry-streams",
        metavar="DELAY",
        type=num(float, min=0),
        help="""
        Retry fetching the list of available streams until streams are found
        while waiting DELAY second(s) between each attempt. If unset, only one
        attempt will be made to fetch the list of streams available.

        The number of fetch retry attempts can be capped with --retry-max.
        """
    )
    stream.add_argument(
        "--retry-max",
        metavar="COUNT",
        type=num(int, min=-1),
        help="""
        When using --retry-streams, stop retrying the fetch after COUNT retry
        attempt(s). Fetch will retry infinitely if COUNT is zero or unset.

        If --retry-max is set without setting --retry-streams, the delay between
        retries will default to 1 second.
        """
    )
    stream.add_argument(
        "--retry-open",
        metavar="ATTEMPTS",
        type=num(int, min=0),
        default=1,
        help="""
        After a successful fetch, try ATTEMPTS time(s) to open the stream until
        giving up.

        Default is 1.
        """
    )
    stream.add_argument(
        "--stream-types", "--stream-priority",
        metavar="TYPES",
        type=comma_list,
        help="""
        A comma-delimited list of stream types to allow.

        The order will be used to separate streams when there are multiple
        streams with the same name but different stream types. Any stream type
        not listed will be omitted from the available streams list.  A ``*`` can
        be used as a wildcard to match any other type of stream, eg. muxed-stream.

        Default is "rtmp,hls,hds,http,akamaihd,*".
        """
    )
    stream.add_argument(
        "--stream-sorting-excludes",
        metavar="STREAMS",
        type=comma_list,
        help="""
        Fine tune the ``best`` and ``worst`` stream name synonyms by excluding unwanted streams.

        If all of the available streams get excluded, ``best`` and ``worst`` will become
        inaccessible and new special stream synonyms ``best-unfiltered`` and ``worst-unfiltered``
        can be used as a fallback selection method.

        Uses a filter expression in the format:

          [operator]<value>

        Valid operators are ``>``, ``>=``, ``<`` and ``<=``. If no operator is specified then
        equality is tested.

        For example this will exclude streams ranked higher than "480p":

          ">480p"

        Multiple filters can be used by separating each expression with a comma.

        For example this will exclude streams from two quality types:

          ">480p,>medium"

        """
    )

    transport = parser.add_argument_group("Stream transport options")
    transport.add_argument(
        "--hds-live-edge",
        type=num(float, min=0),
        metavar="SECONDS",
        help="""
        The time live HDS streams will start from the edge of stream.

        Default is 10.0.
        """
    )
    transport.add_argument(
        "--hds-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each HDS segment before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hds-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download HDS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """
    )
    transport.add_argument(
        "--hds-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        HDS segment connect and read timeout.

        Default is 10.0.
        """
    )
    transport.add_argument(
        "--hds-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HDS streams.

        Default is 60.0.
        """
    )
    transport.add_argument(
        "--hls-live-edge",
        type=num(int, min=0),
        metavar="SEGMENTS",
        help="""
        How many segments from the end to start live HLS streams on.

        The lower the value the lower latency from the source you will be,
        but also increases the chance of buffering.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each HLS segment before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-playlist-reload-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to reload the HLS playlist before
        giving up.

        Default is 3.
        """
    )
    transport.add_argument(
        "--hls-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download HLS segments. Minimum value
        is 1 and maximum is 10.

        Default is 1.
        """
    )
    transport.add_argument(
        "--hls-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        HLS segment connect and read timeout.

        Default is 10.0.
        """)
    transport.add_argument(
        "--hls-segment-ignore-names",
        metavar="NAMES",
        type=comma_list,
        help="""
        A comma-delimited list of segment names that will not be fetched.

        Example: --hls-segment-ignore-names 000,001,002

        This will ignore every segment that ends with 000.ts, 001.ts and 002.ts

        Default is None.

        Note: The --hls-timeout must be increased, to a time that is longer than
        the ignored break.
        """
    )
    transport.add_argument(
        "--hls-segment-key-uri",
        metavar="URI",
        type=str,
        help="""
        URI to segment encryption key. If no URI is specified, the URI contained
        in the segments will be used.

        Example: --hls-segment-key-uri "https://example.com/hls/encryption_key"

        Default is None.
        """
    )
    transport.add_argument(
        "--hls-audio-select",
        type=comma_list,
        metavar="CODE",
        help="""
        Selects a specific audio source or sources, by language code or name,
        when multiple audio sources are available. Can be * to download all
        audio sources.

        Examples:

          --hls-audio-select "English,German"
          --hls-audio-select "en,de"
          --hls-audio-select "*"

        Note: This is only useful in special circumstances where the regular
        locale option fails, such as when multiple sources of the same language
        exists.
        """)
    transport.add_argument(
        "--hls-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HLS streams.

        Default is 60.0.
        """)
    transport.add_argument(
        "--hls-start-offset",
        type=hours_minutes_seconds,
        metavar="[HH:]MM:SS",
        default=None,
        help="""
        Amount of time to skip from the beginning of the stream. For live
        streams, this is a negative offset from the end of the stream (rewind).

        Default is 00:00:00.
        """)
    transport.add_argument(
        "--hls-duration",
        type=hours_minutes_seconds,
        metavar="[HH:]MM:SS",
        default=None,
        help="""
        Limit the playback duration, useful for watching segments of a stream.
        The actual duration may be slightly longer, as it is rounded to the
        nearest HLS segment.

        Default is unlimited.
        """)
    transport.add_argument(
        "--hls-live-restart",
        action="store_true",
        help="""
        Skip to the beginning of a live stream, or as far back as possible.
        """)
    transport.add_argument(
        "--http-stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from HTTP streams.

        Default is 60.0.
        """)
    transport.add_argument(
        "--ringbuffer-size",
        metavar="SIZE",
        type=filesize,
        help="""
        The maximum size of ringbuffer. Add a M or K suffix to specify mega or
        kilo bytes instead of bytes.

        The ringbuffer is used as a temporary storage between the stream and the
        player. This is to allows us to download the stream faster than the
        player wants to read it.

        The smaller the size, the higher chance of the player buffering if there
        are download speed dips and the higher size the more data we can use as
        a storage to catch up from speed dips.

        It also allows you to temporary pause as long as the ringbuffer doesn't
        get full since we continue to download the stream in the background.

        Default is "16M".

        Note: A smaller size is recommended on lower end systems (such as
        Raspberry Pi) when playing stream types that require some extra
        processing (such as HDS) to avoid unnecessary background processing.
        """)
    transport.add_argument(
        "--rtmp-proxy", "--rtmpdump-proxy",
        metavar="PROXY",
        help="""
        A SOCKS proxy that RTMP streams will use.

        Example: 127.0.0.1:9050
        """
    )
    transport.add_argument(
        "--rtmp-rtmpdump", "--rtmpdump",
        metavar="FILENAME",
        help="""
        RTMPDump is used to access RTMP streams. You can specify the
        location of the rtmpdump executable if it is not in your PATH.

        Example: "/usr/local/bin/rtmpdump"
        """
    )
    transport.add_argument(
        "--rtmp-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from RTMP streams.

        Default is 60.0.
        """
    )
    transport.add_argument(
        "--stream-segment-attempts",
        type=num(int, min=0),
        metavar="ATTEMPTS",
        help="""
        How many attempts should be done to download each segment before giving
        up.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 3.
        """
    )
    transport.add_argument(
        "--stream-segment-threads",
        type=num(int, max=10),
        metavar="THREADS",
        help="""
        The size of the thread pool used to download segments. Minimum value is
        1 and maximum is 10.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 1.
        """
    )
    transport.add_argument(
        "--stream-segment-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Segment connect and read timeout.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 10.0.
        """)
    transport.add_argument(
        "--stream-timeout",
        type=num(float, min=0),
        metavar="TIMEOUT",
        help="""
        Timeout for reading data from streams.

        This is generic option used by streams not covered by other options,
        such as stream protocols specific to plugins, e.g. UStream.

        Default is 60.0.
        """)
    transport.add_argument(
        "--stream-url",
        action="store_true",
        help="""
        If possible, translate the stream to a URL and print it.
        """
    )
    transport.add_argument(
        "--subprocess-cmdline", "--cmdline", "-c",
        action="store_true",
        help="""
        Print the command-line used internally to play the stream.

        This is only available on RTMP streams.
        """
    )
    transport.add_argument(
        "--subprocess-errorlog", "--errorlog", "-e",
        action="store_true",
        help="""
        Log possible errors from internal subprocesses to a temporary file. The
        file will be saved in your systems temporary directory.

        Useful when debugging rtmpdump related issues.
        """
    )
    transport.add_argument(
        "--subprocess-errorlog-path", "--errorlog-path",
        type=str,
        metavar="PATH",
        help="""
        Log the subprocess errorlog to a specific file rather than a temporary
        file. Takes precedence over subprocess-errorlog.

        Useful when debugging rtmpdump related issues.
        """
    )
    transport.add_argument(
        "--ffmpeg-ffmpeg",
        metavar="FILENAME",
        help="""
        FFMPEG is used to access or mux separate video and audio streams. You
        can specify the location of the ffmpeg executable if it is not in your
        PATH.

        Example: "/usr/local/bin/ffmpeg"
        """
    )
    transport.add_argument(
        "--ffmpeg-verbose",
        action="store_true",
        help="""
        Write the console output from ffmpeg to the console.
        """
    )
    transport.add_argument(
        "--ffmpeg-verbose-path",
        type=str,
        metavar="PATH",
        help="""
        Path to write the output from the ffmpeg console.
        """
    )
    transport.add_argument(
        "--ffmpeg-video-transcode",
        metavar="CODEC",
        help="""
        When muxing streams transcode the video to this CODEC.

        Default is "copy".

        Example: "h264"
        """
    )
    transport.add_argument(
        "--ffmpeg-audio-transcode",
        metavar="CODEC",
        help="""
        When muxing streams transcode the audio to this CODEC.

        Default is "copy".

        Example: "aac"
        """
    )

    http = parser.add_argument_group("HTTP options")
    http.add_argument(
        "--http-proxy",
        metavar="HTTP_PROXY",
        help="""
        A HTTP proxy to use for all HTTP requests.

        Example: "http://hostname:port/"
        """
    )
    http.add_argument(
        "--https-proxy",
        metavar="HTTPS_PROXY",
        help="""
        A HTTPS capable proxy to use for all HTTPS requests.

        Example: "https://hostname:port/"
        """
    )
    http.add_argument(
        "--http-cookie",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A cookie to add to each HTTP request.

        Can be repeated to add multiple cookies.
        """
    )
    http.add_argument(
        "--http-header",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A header to add to each HTTP request.

        Can be repeated to add multiple headers.
        """
    )
    http.add_argument(
        "--http-query-param",
        metavar="KEY=VALUE",
        type=keyvalue,
        action="append",
        help="""
        A query parameter to add to each HTTP request.

        Can be repeated to add multiple query parameters.
        """
    )
    http.add_argument(
        "--http-ignore-env",
        action="store_true",
        help="""
        Ignore HTTP settings set in the environment such as environment
        variables (HTTP_PROXY, etc) or ~/.netrc authentication.
        """
    )
    http.add_argument(
        "--http-no-ssl-verify",
        action="store_true",
        help="""
        Don't attempt to verify SSL certificates.

        Usually a bad idea, only use this if you know what you're doing.
        """
    )
    http.add_argument(
        "--http-disable-dh",
        action="store_true",
        help="""
        Disable Diffie Hellman key exchange

        Usually a bad idea, only use this if you know what you're doing.
        """
    )
    http.add_argument(
        "--http-ssl-cert",
        metavar="FILENAME",
        help="""
        SSL certificate to use.

        Expects a .pem file.
        """
    )
    http.add_argument(
        "--http-ssl-cert-crt-key",
        metavar=("CRT_FILENAME", "KEY_FILENAME"),
        nargs=2,
        help="""
        SSL certificate to use.

        Expects a .crt and a .key file.
        """
    )
    http.add_argument(
        "--http-timeout",
        metavar="TIMEOUT",
        type=num(float, min=0),
        help="""
        General timeout used by all HTTP requests except the ones covered by
        other options.

        Default is 20.0.
        """
    )

    # Deprecated options
    http.add_argument(
        "--http-cookies",
        metavar="COOKIES",
        help=argparse.SUPPRESS
    )
    http.add_argument(
        "--http-headers",
        metavar="HEADERS",
        help=argparse.SUPPRESS
    )
    http.add_argument(
        "--http-query-params",
        metavar="PARAMS",
        help=argparse.SUPPRESS
    )
    general.add_argument(
        "--no-version-check",
        action="store_true",
        help=argparse.SUPPRESS
    )
    return parser