U
    g=                    @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZ	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZddlmZ ddlmZ ddlmZm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z( ddl)m*Z* dd	l+m,Z,m-Z- dd
l.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZE ddlFmGZH ddlFmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT ddlUmVZW ddlXmYZYmZZZm[Z[m\Z\m]Z] ddl^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZ ddlmZmZmZmZmZ edkrd dlZdd ZG dd dZdS )    N   )Cache)urllib)compat_os_nameurllib_req_to_req)CookieLoadErrorLenientSimpleCookieload_cookies)FFmpegFDget_suitable_downloadershorten_protocol_name)rtmpdump_version)gen_extractor_classesget_info_extractor)UnsupportedURLIE)PhantomJSwrapper)format_text)HEADRequestRequestRequestDirector)_REQUEST_HANDLERS_RH_PREFERENCES)	HTTPErrorNoSupportingHandlersRequestErrorSSLErrornetwork_exceptions)ImpersonateRequestHandler)directories)_PLUGIN_CLASSES)EmbedThumbnailPPFFmpegFixupDuplicateMoovPPFFmpegFixupDurationPPFFmpegFixupM3u8PPFFmpegFixupM4aPPFFmpegFixupStretchedPPFFmpegFixupTimestampPPFFmpegMergerPPFFmpegPostProcessorFFmpegVideoConvertorPPMoveFilesAfterDownloadPPget_postprocessor)resolve_mapping)
REPOSITORY_get_system_deprecation_make_labelcurrent_git_headdetect_variant)XDEFAULT_OUTTMPLIDENTITYLINK_TEMPLATESMEDIA_EXTENSIONS
NO_DEFAULT	NUMBER_REOUTTMPL_TYPESPOSTPROCESS_WHENSTR_FORMAT_RE_TMPLSTR_FORMAT_TYPESContentTooShortError	DateRangeDownloadCancelledDownloadErrorEntryNotInPlaylistExistingVideoReachedExtractorErrorFormatSorterGeoRestrictedErrorISO3166UtilsLazyListMaxDownloadsReached	Namespace	PagedListPlaylistEntriesPopenPostProcessingErrorReExtractInfoRejectedVideoReachedSameFileErrorUnavailableVideoErrorUserNotLiveYoutubeDLErrorage_restrictedbug_reports_messagedate_from_strdeprecation_warningdetermine_extdetermine_protocolencode_compat_strencodeFilename
escapeHTMLexpand_pathextract_basic_authfilter_dictfloat_or_noneformat_bytesformat_decimal_suffixformat_fieldformatSecondsget_compatible_ext
get_domainint_or_none
iri_to_uriis_path_likejoin_nonemptylocked_filemake_archive_idmake_dirnumber_of_digits
orderedSetorderedSet_from_optionsparse_filesizepreferredencodingprepend_extensionremove_terminal_sequencesrender_tablereplace_extensionsanitize_filenamesanitize_pathsanitize_urlshell_quotestr_or_nonestrftime_or_nonesubtitles_filenamesupports_terminal_sequencessystem_identifierfilesize_from_tbrtimetuple_from_msecto_high_limit_pathtraverse_objtry_calltry_geturl_basenamevariadicwindows_enable_vt_modewrite_json_filewrite_string)_UnsafeExtensionError
_YDLLogger)HTTPHeaderDictclean_headersclean_proxiesstd_headers)CHANNELORIGINRELEASE_GIT_HEADVARIANT__version__ntc                    s   t   fdd}|S )Nc              
      sV   z | f||W S  t k
rP } z | d|jdtd  W 5 d }~X Y nX d S )NzThe extracted extension (zT) is unusual and will be skipped for safety reasons. If you believe this is an error,)r   report_error	extensionrT   )selfargskwargserrorfunc 4/tmp/pip-unpacked-wheel-q5ljy6pj/yt_dlp/YoutubeDL.pywrapper   s    z._catch_unsafe_extension_error.<locals>.wrapper	functoolswrapsr   r   r   r   r   _catch_unsafe_extension_error   s    	r   c                7   @   s  e Zd ZdZdddddddd	d
dddddddddddddddddddhZddd d!d"d#d$ddd%d&d'ddd(ddd	dd)d*d
dd+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJh7ZdKdLdMdNdOdPZeej	ej
dQheejdRZd[dUdVZdWdX ZdYdZ Zd[d\ Zd]d^ Zd\d`daZdbdc Zddde Zdfdg Zdhdi Zd]dkdlZd^dmdnZd_dodpZd`dqdrZdsdt Zdudv Zdwdx Zdydz Zd{d| Zd}d~ Z dd Z!dd Z"daddZ#e$dddddddddd	Z%dbdjdddZ&dd Z'dd Z(dd Z)dcddZ*ddddZ+dd Z,dd Z-ddddZ.dd Z/dd Z0dedSdddZ1dd Z2dd Z3dfddZ4e5dd Z6e5dd Z7e8dd Z9e5dd Z:dgddZ;dd Z<e=dSdSdddZ>dhdSdjdddZ?diddÄZ@e5ddń ZAdjddǄZBddɄ ZCi fdd˄ZDdTd̜dd΄ZEdkddЄZFeCdd҄ ZGddԄ ZHdlddքZIdd؄ ZJe5dmddڄZKdd܄ ZLeCddބ ZMdd ZNdd ZOdd ZPdd ZQdd ZRdnddZSdd ZTdd ZUdd ZVdoddZWdd ZXdd ZYdpddZZdd Z[dd Z\dqddZ]drdd Z^dTdddZ_e=dd Z`dd Zadd	 Zbd
d Zce5dsddZde5dtddZei dSdddZfe5dd Zgdd ZhdSdddZiduddZjdvddZkdd  Zld!d" Zmd#d$ Zne5dwd&d'Zod(d) Zpd*d+ Zqd,d- Zrd.d/ Zsd0d1 Ztd2d3 Zud4d5 Zvd6d7 Zwd8d9 Zxdxd;d<Zyd=d> Zze{j|d?d@ Z}e{j|dAdB Z~edCdD ZdEdF ZdGdH ZdIdJ ZdydKdLZe{j|dMdN ZdOdP ZdQdR ZdzdSdTZdUdV ZdWdX Zd{dYdZZdSS (|  	YoutubeDLaYe  YoutubeDL class.

    YoutubeDL objects are the ones responsible of downloading the
    actual video file and writing it to disk if the user has requested
    it, among some other tasks. In most cases there should be one per
    program. As, given a video URL, the downloader doesn't know how to
    extract all the needed information, task that InfoExtractors do, it
    has to pass the URL to one of them.

    For this, YoutubeDL objects have a method that allows
    InfoExtractors to be registered in a given order. When it is passed
    a URL, the YoutubeDL object handles it to the first InfoExtractor it
    finds that reports being able to handle it. The InfoExtractor extracts
    all the information about the video or videos the URL refers to, and
    YoutubeDL process the extracted information, possibly using a File
    Downloader to download the video.

    YoutubeDL objects accept a lot of parameters. In order not to saturate
    the object constructor with arguments, it receives a dictionary of
    options instead. These options are available through the params
    attribute for the InfoExtractors to use. The YoutubeDL also
    registers itself as the downloader in charge for the InfoExtractors
    that are added to it, so this is a "mutual registration".

    Available options:

    username:          Username for authentication purposes.
    password:          Password for authentication purposes.
    videopassword:     Password for accessing a video.
    ap_mso:            Adobe Pass multiple-system operator identifier.
    ap_username:       Multiple-system operator account username.
    ap_password:       Multiple-system operator account password.
    usenetrc:          Use netrc for authentication instead.
    netrc_location:    Location of the netrc file. Defaults to ~/.netrc.
    netrc_cmd:         Use a shell command to get credentials
    verbose:           Print additional info to stdout.
    quiet:             Do not print messages to stdout.
    no_warnings:       Do not print out anything for warnings.
    forceprint:        A dict with keys WHEN mapped to a list of templates to
                       print to stdout. The allowed keys are video or any of the
                       items in utils.POSTPROCESS_WHEN.
                       For compatibility, a single list is also accepted
    print_to_file:     A dict with keys WHEN (same as forceprint) mapped to
                       a list of tuples with (template, filename)
    forcejson:         Force printing info_dict as JSON.
    dump_single_json:  Force printing the info_dict of the whole playlist
                       (or video) as a single JSON line.
    force_write_download_archive: Force writing download archive regardless
                       of 'skip_download' or 'simulate'.
    simulate:          Do not download the video files. If unset (or None),
                       simulate only if listsubtitles, listformats or list_thumbnails is used
    format:            Video format code. see "FORMAT SELECTION" for more details.
                       You can also pass a function. The function takes 'ctx' as
                       argument and returns the formats to download.
                       See "build_format_selector" for an implementation
    allow_unplayable_formats:   Allow unplayable formats to be extracted and downloaded.
    ignore_no_formats_error: Ignore "No video formats" error. Usefull for
                       extracting metadata even if the video is not actually
                       available for download (experimental)
    format_sort:       A list of fields by which to sort the video formats.
                       See "Sorting Formats" for more details.
    format_sort_force: Force the given format_sort. see "Sorting Formats"
                       for more details.
    prefer_free_formats: Whether to prefer video formats with free containers
                       over non-free ones of the same quality.
    allow_multiple_video_streams:   Allow multiple video streams to be merged
                       into a single file
    allow_multiple_audio_streams:   Allow multiple audio streams to be merged
                       into a single file
    check_formats      Whether to test if the formats are downloadable.
                       Can be True (check all), False (check none),
                       'selected' (check selected formats),
                       or None (check only if requested by extractor)
    paths:             Dictionary of output paths. The allowed keys are 'home'
                       'temp' and the keys of OUTTMPL_TYPES (in utils/_utils.py)
    outtmpl:           Dictionary of templates for output names. Allowed keys
                       are 'default' and the keys of OUTTMPL_TYPES (in utils/_utils.py).
                       For compatibility with youtube-dl, a single string can also be used
    outtmpl_na_placeholder: Placeholder for unavailable meta fields.
    restrictfilenames: Do not allow "&" and spaces in file names
    trim_file_name:    Limit length of filename (extension excluded)
    windowsfilenames:  Force the filenames to be windows compatible
    ignoreerrors:      Do not stop on download/postprocessing errors.
                       Can be 'only_download' to ignore only download errors.
                       Default is 'only_download' for CLI, but False for API
    skip_playlist_after_errors: Number of allowed failures until the rest of
                       the playlist is skipped
    allowed_extractors:  List of regexes to match against extractor names that are allowed
    overwrites:        Overwrite all video and metadata files if True,
                       overwrite only non-video files if None
                       and don't overwrite any file if False
    playlist_items:    Specific indices of playlist to download.
    playlistrandom:    Download playlist items in random order.
    lazy_playlist:     Process playlist entries as they are received.
    matchtitle:        Download only matching titles.
    rejecttitle:       Reject downloads for matching titles.
    logger:            Log messages to a logging.Logger instance.
    logtostderr:       Print everything to stderr instead of stdout.
    consoletitle:      Display progress in the console window's titlebar.
    writedescription:  Write the video description to a .description file
    writeinfojson:     Write the video description to a .info.json file
    clean_infojson:    Remove internal metadata from the infojson
    getcomments:       Extract video comments. This will not be written to disk
                       unless writeinfojson is also given
    writeannotations:  Write the video annotations to a .annotations.xml file
    writethumbnail:    Write the thumbnail image to a file
    allow_playlist_files: Whether to write playlists' description, infojson etc
                       also to disk when using the 'write*' options
    write_all_thumbnails:  Write all thumbnail formats to files
    writelink:         Write an internet shortcut file, depending on the
                       current platform (.url/.webloc/.desktop)
    writeurllink:      Write a Windows internet shortcut file (.url)
    writewebloclink:   Write a macOS internet shortcut file (.webloc)
    writedesktoplink:  Write a Linux internet shortcut file (.desktop)
    writesubtitles:    Write the video subtitles to a file
    writeautomaticsub: Write the automatically generated subtitles to a file
    listsubtitles:     Lists all available subtitles for the video
    subtitlesformat:   The format code for subtitles
    subtitleslangs:    List of languages of the subtitles to download (can be regex).
                       The list may contain "all" to refer to all the available
                       subtitles. The language can be prefixed with a "-" to
                       exclude it from the requested languages, e.g. ['all', '-live_chat']
    keepvideo:         Keep the video file after post-processing
    daterange:         A utils.DateRange object, download only if the upload_date is in the range.
    skip_download:     Skip the actual download of the video file
    cachedir:          Location of the cache files in the filesystem.
                       False to disable filesystem cache.
    noplaylist:        Download single video instead of a playlist if in doubt.
    age_limit:         An integer representing the user's age in years.
                       Unsuitable videos for the given age are skipped.
    min_views:         An integer representing the minimum view count the video
                       must have in order to not be skipped.
                       Videos without view count information are always
                       downloaded. None for no limit.
    max_views:         An integer representing the maximum view count.
                       Videos that are more popular than that are not
                       downloaded.
                       Videos without view count information are always
                       downloaded. None for no limit.
    download_archive:  A set, or the name of a file where all downloads are recorded.
                       Videos already present in the file are not downloaded again.
    break_on_existing: Stop the download process after attempting to download a
                       file that is in the archive.
    break_per_url:     Whether break_on_reject and break_on_existing
                       should act on each input URL as opposed to for the entire queue
    cookiefile:        File name or text stream from where cookies should be read and dumped to
    cookiesfrombrowser:  A tuple containing the name of the browser, the profile
                       name/path from where cookies are loaded, the name of the keyring,
                       and the container name, e.g. ('chrome', ) or
                       ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta')
    legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
                       support RFC 5746 secure renegotiation
    nocheckcertificate:  Do not verify SSL certificates
    client_certificate:  Path to client certificate file in PEM format. May include the private key
    client_certificate_key:  Path to private key file for client certificate
    client_certificate_password:  Password for client certificate private key, if encrypted.
                        If not provided and the key is encrypted, yt-dlp will ask interactively
    prefer_insecure:   Use HTTP instead of HTTPS to retrieve information.
                       (Only supported by some extractors)
    enable_file_urls:  Enable file:// URLs. This is disabled by default for security reasons.
    http_headers:      A dictionary of custom headers to be used for all requests
    proxy:             URL of the proxy server to use
    geo_verification_proxy:  URL of the proxy to use for IP address verification
                       on geo-restricted sites.
    socket_timeout:    Time to wait for unresponsive hosts, in seconds
    bidi_workaround:   Work around buggy terminals without bidirectional text
                       support, using fridibi
    debug_printtraffic:Print out sent and received HTTP traffic
    default_search:    Prepend this string if an input url is not valid.
                       'auto' for elaborate guessing
    encoding:          Use this encoding instead of the system-specified.
    extract_flat:      Whether to resolve and process url_results further
                       * False:     Always process. Default for API
                       * True:      Never process
                       * 'in_playlist': Do not process inside playlist/multi_video
                       * 'discard': Always process, but don't return the result
                                    from inside playlist/multi_video
                       * 'discard_in_playlist': Same as "discard", but only for
                                    playlists (not multi_video). Default for CLI
    wait_for_video:    If given, wait for scheduled streams to become available.
                       The value should be a tuple containing the range
                       (min_secs, max_secs) to wait between retries
    postprocessors:    A list of dictionaries, each with an entry
                       * key:  The name of the postprocessor. See
                               yt_dlp/postprocessor/__init__.py for a list.
                       * when: When to run the postprocessor. Allowed values are
                               the entries of utils.POSTPROCESS_WHEN
                               Assumed to be 'post_process' if not given
    progress_hooks:    A list of functions that get called on download
                       progress, with a dictionary with the entries
                       * status: One of "downloading", "error", or "finished".
                                 Check this first and ignore unknown values.
                       * info_dict: The extracted info_dict

                       If status is one of "downloading", or "finished", the
                       following properties may also be present:
                       * filename: The final filename (always present)
                       * tmpfilename: The filename we're currently writing to
                       * downloaded_bytes: Bytes on disk
                       * total_bytes: Size of the whole file, None if unknown
                       * total_bytes_estimate: Guess of the eventual file size,
                                               None if unavailable.
                       * elapsed: The number of seconds since download started.
                       * eta: The estimated time in seconds, None if unknown
                       * speed: The download speed in bytes/second, None if
                                unknown
                       * fragment_index: The counter of the currently
                                         downloaded video fragment.
                       * fragment_count: The number of fragments (= individual
                                         files that will be merged)

                       Progress hooks are guaranteed to be called at least once
                       (with status "finished") if the download is successful.
    postprocessor_hooks:  A list of functions that get called on postprocessing
                       progress, with a dictionary with the entries
                       * status: One of "started", "processing", or "finished".
                                 Check this first and ignore unknown values.
                       * postprocessor: Name of the postprocessor
                       * info_dict: The extracted info_dict

                       Progress hooks are guaranteed to be called at least twice
                       (with status "started" and "finished") if the processing is successful.
    merge_output_format: "/" separated list of extensions to use when merging formats.
    final_ext:         Expected final extension; used to detect when the file was
                       already downloaded and converted
    fixup:             Automatically correct known faults of the file.
                       One of:
                       - "never": do nothing
                       - "warn": only emit a warning
                       - "detect_or_warn": check whether we can do anything
                                           about it, warn otherwise (default)
    source_address:    Client-side IP address to bind to.
    impersonate:       Client to impersonate for requests.
                       An ImpersonateTarget (from yt_dlp.networking.impersonate)
    sleep_interval_requests: Number of seconds to sleep between requests
                       during extraction
    sleep_interval:    Number of seconds to sleep before each download when
                       used alone or a lower bound of a range for randomized
                       sleep before each download (minimum possible number
                       of seconds to sleep) when used along with
                       max_sleep_interval.
    max_sleep_interval:Upper bound of a range for randomized sleep before each
                       download (maximum possible number of seconds to sleep).
                       Must only be used along with sleep_interval.
                       Actual sleep time will be a random float from range
                       [sleep_interval; max_sleep_interval].
    sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
    listformats:       Print an overview of available video formats and exit.
    list_thumbnails:   Print a table of all thumbnails and exit.
    match_filter:      A function that gets called for every video with the signature
                       (info_dict, *, incomplete: bool) -> Optional[str]
                       For backward compatibility with youtube-dl, the signature
                       (info_dict) -> Optional[str] is also allowed.
                       - If it returns a message, the video is ignored.
                       - If it returns None, the video is downloaded.
                       - If it returns utils.NO_DEFAULT, the user is interactively
                         asked whether to download the video.
                       - Raise utils.DownloadCancelled(msg) to abort remaining
                         downloads when a video is rejected.
                       match_filter_func in utils/_utils.py is one example for this.
    color:             A Dictionary with output stream names as keys
                       and their respective color policy as values.
                       Can also just be a single color policy,
                       in which case it applies to all outputs.
                       Valid stream names are 'stdout' and 'stderr'.
                       Valid color policies are one of 'always', 'auto',
                       'no_color', 'never', 'auto-tty' or 'no_color-tty'.
    geo_bypass:        Bypass geographic restriction via faking X-Forwarded-For
                       HTTP header
    geo_bypass_country:
                       Two-letter ISO 3166-2 country code that will be used for
                       explicit geographic restriction bypassing via faking
                       X-Forwarded-For HTTP header
    geo_bypass_ip_block:
                       IP range in CIDR notation that will be used similarly to
                       geo_bypass_country
    external_downloader: A dictionary of protocol keys and the executable of the
                       external downloader to use for it. The allowed protocols
                       are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
                       Set the value to 'native' to use the native downloader
    compat_opts:       Compatibility options. See "Differences in default behavior".
                       The following options do not work when used through the API:
                       filename, abort-on-error, multistreams, no-live-chat,
                       format-sort, no-clean-infojson, no-playlist-metafiles,
                       no-keep-subs, no-attach-info-json, allow-unsafe-ext.
                       Refer __init__.py for their implementation
    progress_template: Dictionary of templates for progress outputs.
                       Allowed keys are 'download', 'postprocess',
                       'download-title' (console title) and 'postprocess-title'.
                       The template is mapped on a dictionary with keys 'progress' and 'info'
    retry_sleep_functions: Dictionary of functions that takes the number of attempts
                       as argument and returns the time to sleep in seconds.
                       Allowed keys are 'http', 'fragment', 'file_access'
    download_ranges:   A callback function that gets called for every video with
                       the signature (info_dict, ydl) -> Iterable[Section].
                       Only the returned sections will be downloaded.
                       Each Section is a dict with the following keys:
                       * start_time: Start time of the section in seconds
                       * end_time: End time of the section in seconds
                       * title: Section title (Optional)
                       * index: Section number (Optional)
    force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts
    noprogress:        Do not print the progress bar
    live_from_start:   Whether to download livestreams videos from the start

    The following parameters are not used by YoutubeDL itself, they are used by
    the downloader (see yt_dlp/downloader/common.py):
    nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
    max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries,
    continuedl, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
    external_downloader_args, concurrent_fragment_downloads, progress_delta.

    The following options are used by the post processors:
    ffmpeg_location:   Location of the ffmpeg/avconv binary; either the path
                       to the binary or its containing directory.
    postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
                       and a list of additional command-line arguments for the
                       postprocessor/executable. The dict can also have "PP+EXE" keys
                       which are used when the given exe is used by the given PP.
                       Use 'default' as the name for arguments to passed to all PP
                       For compatibility with youtube-dl, a single list of args
                       can also be used

    The following options are used by the extractors:
    extractor_retries: Number of times to retry for known errors (default: 3)
    dynamic_mpd:       Whether to process dynamic DASH manifests (default: True)
    hls_split_discontinuity: Split HLS playlists into different formats at
                       discontinuities such as ad breaks (default: False)
    extractor_args:    A dictionary of arguments to be passed to the extractors.
                       See "EXTRACTOR ARGUMENTS" for details.
                       E.g. {'youtube': {'skip': ['dash', 'hls']}}
    mark_watched:      Mark videos watched (even with --simulate). Only for YouTube

    The following options are deprecated and may be removed in the future:

    break_on_reject:   Stop the download process when encountering a video that
                       has been filtered out.
                       - `raise DownloadCancelled(msg)` in match_filter instead
    force_generic_extractor: Force downloader to use the generic extractor
                       - Use allowed_extractors = ['generic', 'default']
    playliststart:     - Use playlist_items
                       Playlist item to start at.
    playlistend:       - Use playlist_items
                       Playlist item to end at.
    playlistreverse:   - Use playlist_items
                       Download playlist items in reverse order.
    forceurl:          - Use forceprint
                       Force printing final URL.
    forcetitle:        - Use forceprint
                       Force printing title.
    forceid:           - Use forceprint
                       Force printing ID.
    forcethumbnail:    - Use forceprint
                       Force printing thumbnail URL.
    forcedescription:  - Use forceprint
                       Force printing description.
    forcefilename:     - Use forceprint
                       Force printing final filename.
    forceduration:     - Use forceprint
                       Force printing duration.
    allsubtitles:      - Use subtitleslangs = ['all']
                       Downloads all the subtitles of the video
                       (requires writesubtitles or writeautomaticsub)
    include_ads:       - Doesn't work
                       Download ads as well
    call_home:         - Not implemented
                       Boolean, true if we are allowed to contact the
                       yt-dlp servers for debugging.
    post_hooks:        - Register a custom postprocessor
                       A list of functions that get called as the final step
                       for each video file, after all postprocessors have been
                       called. The filename will be passed as the only argument.
    hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}.
                       Use the native HLS downloader instead of ffmpeg/avconv
                       if True, otherwise use ffmpeg/avconv if False, otherwise
                       use downloader suggested by extractor if None.
    prefer_ffmpeg:     - avconv support is deprecated
                       If False, use avconv instead of ffmpeg if both are available,
                       otherwise prefer ffmpeg.
    youtube_include_dash_manifest: - Use extractor_args
                       If True (default), DASH manifests and related
                       data will be downloaded and processed by extractor.
                       You can reduce network I/O by disabling it if you don't
                       care about DASH. (only for youtube)
    youtube_include_hls_manifest: - Use extractor_args
                       If True (default), HLS manifests and related
                       data will be downloaded and processed by extractor.
                       You can reduce network I/O by disabling it if you don't
                       care about HLS. (only for youtube)
    no_color:          Same as `color='no_color'`
    no_overwrites:     Same as `overwrites=False`
    widthheightasraudio_channelsfpstbrabrvbrfilesizefilesize_approx	timestamprelease_timestampduration
view_countZ
like_countZdislike_countZrepost_countZaverage_ratingZcomment_count	age_limit
start_timeend_timeZchapter_numberZseason_numberZepisode_numberZtrack_numberZdisc_numberrelease_yearurlmanifest_urlZmanifest_stream_numberextformat	format_idformat_noteaspect_ratio
resolutiondynamic_rangeacodecvcodec	containerZrowscolumnsZ
player_urlprotocolZfragment_base_urlZ	fragmentsis_from_startis_dash_periodsZrequest_data
preferencelanguageZlanguage_preferenceZqualityZsource_preferencecookieshttp_headersstretched_ratioZ	no_resumehas_drmZextra_param_to_segment_urlZextra_param_to_key_urlZhls_aesZdownloader_optionspage_urlZapp	play_pathZtc_urlZflash_versionZ	rtmp_liveZ	rtmp_connZrtmp_protocolZrtmp_real_timeZalbum_artistsZartistsZ	composersZcreatorsZgenres)Zalbum_artistZartistZcomposerZcreatorZgenreZ3gp)audiovideostoryboardsNTc              
      s  |dkri }|_ i _i _dd tD _t _d_g _g _	g _
d_d_d_d_t _t_g _j drtjntj}t|tjj drtjn|tdkrdnttttjtjfdd	_z
t  W n4 tk
r } zd
|  W 5 d}~X Y nX j drZj ddk	rPj  dg !d dj d< t"#dd$ dkt%t"#d  fddtf fddjj&D _'t( }|rȈ)|*dd j dr+d,dj-j. d,dj-j/ d j ddrzddl0}|1 \}}t23 j4}	|	dkrDg n
d t5|	g}
t6j7|jj8d!}zt9d[|
f|_:W n( t;k
r   t9d\|
f|_:Y nX t"<|d&_=W n@ t;k
r } z |j>t>j?kr+d' n W 5 d}~X Y nX tj d(d)j d(< t@tAj d*j d*< Bj d* d+ j d* Cd+d |rd|d,krdD  fd-d.}|d/d0d1rj d2dkrj d/ j d2< |d3d4d5 |d6d7d8 |d9d:d; j dg D ]}+| q҈j d<g D ]})| qj d= }r2E|s2tFd>| d?d@j d( krLdj dA< dBj kr~j dCdk	r~j dC  j dB< n4j dBdkrj CdBd nj dB  j dC< j dDdkrtGj dEj dFj dGfrdHj dD< j  dIi  j  dJi  tH|dI tIs4dK|dI ij dI< |rBJ  tjKdLkrtL dMkrj dNds+dO dj dN< M  j dPdQkrj dPn(tNj dP rj dP nOj dP _PjQjRjSdR}|T D ](\}}j |g D ]}|| qqj dSg D ]:}tI|}|CdTdU}jUtV|CdVf||dW q$fdXdY}|j dZ_WdS )]zCreate a FileDownloader object with the given options.
        @param auto_init    Whether to load the default extractors and print header (if verbose).
                            Set to 'no_verbose_header' to not print the header
        Nc                 S   s   i | ]
}|g qS r   r   .0kr   r   r   
<dictcomp>s  s      z&YoutubeDL.__init__.<locals>.<dictcomp>Tr   Zlogtostderrquietr   )outr   screenconsolezFailed to enable VT mode: no_colorcolor	_warningsz/Overwriting params from "color" with "no_color"TERM dumbZNO_COLORc                    s   t jdt jdi|  }tjd|d fthtfp0d}|dkrn }|drR|d}rjt	| rj|rfdS dS d	S |d
ks~t
|dd	d||S )Nstdoutstderrr   auto)r   zauto-ttyzno_color-ttyttyr   TF)alwaysneverr   )r   r   )sysr   r   r   paramsstranyendswith
startswithr}   AssertionErrorget)streamstream_namepolicyr   )base_no_colorr   term_allow_colorr   r   process_color_policy  s    

z0YoutubeDL.__init__.<locals>.process_color_policyc                    s"   i | ]\}}|d kr| |qS )r   r   )r   namer   )r   r   r   r     s     
z
                    allow_unplayable_formatszYou have asked for Z
UNPLAYABLEz formats to be listed/downloaded. This is a developer option intended for debugging. 
         If you experience any issues while using this option, zDO NOTz open a bug reportZbidi_workaroundFz-w)stdinr   r   bidivfribidi-cUTF-8rbzCould not find fribidi executable, ignoring --bidi-workaround. Make sure that  fribidi  is an executable file in one of the directories in your $PATH.compat_optsr   r   CookieZno_verbose_headerc                    s.    j | d k	r* | d| d dS dS )Nz is deprecated. Use z insteadTF)r   r   report_warning)paramoptionZ
suggestionr   r   r   check_deprecated  s    z,YoutubeDL.__init__.<locals>.check_deprecatedZcn_verification_proxyz--cn-verification-proxyz--geo-verification-proxyZgeo_verification_proxy
autonumberz--auto-numberz%-o "%(autonumber)s-%(title)s.%(ext)s"Zusetitlez--titlez-o "%(title)s-%(id)s.%(ext)s"Zuseidz--idz-o "%(id)s.%(ext)s"Z_deprecation_warningsimpersonateImpersonate target "z" is not available. Use --list-impersonate-targets to see available targets. You may be missing dependencies required to support this target.zlist-formatslistformats_table
overwritesZnooverwritessimulatelist_thumbnailslistformatslistsubtitles	list_only
forceprintprint_to_filer   win32)asciizANSI_X3.4-1968restrictfilenameszAssuming --restrict-filenames since file system encoding cannot encode all characters. Set the LC_ALL environment variable to fix this.r   )N-)Z
post_hooksZprogress_hooksZpostprocessor_hooksZpostprocessorswhenpost_processkey)r  c              
      s   t  }| dkr|S t| s| S  d|  z6t| ddd}|D ]}||  qDW 5 Q R X W n0 tk
r } z|jtjkr W 5 d}~X Y nX |S )z(Preload the archive, if any is specifiedNzLoading archive file rutf-8encoding)	setrh   write_debugrj   addstripOSErrorerrnoENOENT)fnarchivearchive_filelineZioer  r   r   preload_download_archive+  s    z4YoutubeDL.__init__.<locals>.preload_download_archivedownload_archive)r   )r   r   r   )Xr   _ies_ies_instancesr9   _ppsr  _printed_messagesZ_first_webpage_request_post_hooks_progress_hooks_postprocessor_hooks_download_retcode_num_downloads_num_videos_playlist_level_playlist_urlsr   cache_YoutubeDL__header_cookiesr   r   r   r   rH   r   nextfilterr}   
_out_filesr   	Exceptionr  
setdefaultappendosgetenvlowerboolitems__allow_colorsr.   deprecated_featurereplacer  _format_errStylesEMPHASISERRORptyopenptyshutilget_terminal_sizer   r   
subprocessPIPEr   rK   _output_processr"  fdopen_output_channelr#  r$  r   r   _load_cookiespopprint_debug_header_impersonate_target_availablerR   r   
isinstancedictadd_default_info_extractorsplatformgetfilesystemencoding_parse_outtmplcallablebuild_format_selectorformat_selectoradd_post_hookadd_progress_hookadd_postprocessor_hookitemsadd_post_processorr+   r&  )r   r   Z	auto_initr   eZsystem_deprecationrK  ZmasterZslaver   Z
width_argsZ	sp_kwargsZoser  msgZimpersonate_targethooksoptr%  phZ
pp_def_rawZpp_defr  r)  r   )r   r   r   r   r   __init__i  s   
 
"

(









zYoutubeDL.__init__c                    sb   dd t  D r^dgfddt  D  dg  fddD  }| dt|  d S )Nc                 S   s    g | ]\}}t d |r|qS )z^-[0-9A-Za-z_-]{10}$)rematchr   iar   r   r   
<listcomp>A  s   z.YoutubeDL.warn_if_short_id.<locals>.<listcomp>zyt-dlpc                    s   g | ]\}}| kr|qS r   r   rn  )idxsr   r   rq  G  s      z--c                    s   g | ]} | qS r   r   )r   ro  )argvr   r   rq  H  s     zRLong argument string detected. Use -- to separate parameters and URLs, like this:
)	enumerater  ry   )r   rs  Zcorrect_argvr   )rs  rr  r   warn_if_short_id?  s    zYoutubeDL.warn_if_short_idc                 C   s4   |  }|| j|< t|ts0|| j|< ||  dS )z3Add an InfoExtractor object to the end of the list.N)ie_keyr+  rX  typer,  set_downloader)r   ierv  r   r   r   add_info_extractorN  s
    


zYoutubeDL.add_info_extractorc                 C   s,   | j |}|dkr(t| }| | |S )z
        Get an instance of an IE with name ie_key, it will try to get one from
        the _ies list, if there's no instance it will create a new one and add
        it to the extractor list.
        N)r,  r   r   rz  )r   rv  ry  r   r   r   r   V  s
    

zYoutubeDL.get_info_extractorc              
   C   s   dd t  D }t |d< z6t| jddgt|dd | D dd	d
}W n4 tjk
r } zt	d|j
 W 5 d}~X Y nX |D ]}| ||  q| dt| d dS )zZ
        Add the InfoExtractors returned by gen_extractors to the end of the list
        c                 S   s   i | ]}|j  |qS r   )IE_NAMErA  )r   ry  r   r   r   r   f  s      z9YoutubeDL.add_default_info_extractors.<locals>.<dictcomp>endallowed_extractorsdefaultc                 S   s   g | ]\}}|j r|qS r   )Z_ENABLED)r   r   ry  r   r   r   rq  l  s      z9YoutubeDL.add_default_info_extractors.<locals>.<listcomp>)allr~  TZ	use_regexz$Wrong regex for allowed_extractors: NzLoaded z extractors)r   r   ro   r   r   listrd  rl  r   
ValueErrorpatternrz  r  len)r   Zall_iesZie_namesrf  r   r   r   r   rZ  b  s    

"z%YoutubeDL.add_default_info_extractorsr  c                 C   s4   |t kstd| | j| | ||  dS )z3Add a PostProcessor object to the end of the chain.zInvalid when=N)r9   r   r-  r>  rx  )r   ppr  r   r   r   re  t  s    zYoutubeDL.add_post_processorc                 C   s   | j | dS )zAdd the post hookN)r/  r>  r   rj  r   r   r   ra  z  s    zYoutubeDL.add_post_hookc                 C   s   | j | dS )zAdd the download progress hookN)r0  r>  r  r   r   r   rb  ~  s    zYoutubeDL.add_progress_hookc                 C   s4   | j | | j D ]}|D ]}|| qqdS )z$Add the postprocessing progress hookN)r1  r>  r-  valuesrb  )r   rj  Zppsr  r   r   r   rc    s    z YoutubeDL.add_postprocessor_hookc                    s   t  ds|S t  dstt|ts*t|dd } jj|d    jj	  d
 fddt|D }|d td  S )NrS  rQ  r   r   r   c                 3   s   | ]} j   V  qd S N)rS  readlinedecode)r   _r  r   r   	<genexpr>  s   z-YoutubeDL._bidi_workaround.<locals>.<genexpr>)hasattrr   rX  r   countrQ  r   writeencodeflushjoinranger  )r   message
line_countresr   r  r   _bidi_workaround  s    
zYoutubeDL._bidi_workaroundFc                 C   s8   |r|| j krd S | j | t||| jdd d S )Nr  )r   r  )r.  r   r   r   r   )r   r  r   	only_oncer   r   r   _write_string  s
    
zYoutubeDL._write_stringc                 C   sD   |dk	r|  d |dk	r$|  d | | | d| jj dS )zPrint message to stdoutNz]"YoutubeDL.to_stdout" no longer accepts the argument quiet. Use "YoutubeDL.to_screen" insteadFz`"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. Use "YoutubeDL.to_screen" insteadr   )rV   r  r  r;  r   )r   r  skip_eolr   r   r   r   	to_stdout  s
    

zYoutubeDL.to_stdoutc                 C   sx   | j dr | j d | dS |dkr6| j drJn|rJ| j dsJdS | jd| ||rbdnd| jj|d dS )	z,Print message to screen if not in quiet modeloggerNr   verbose{}{}r   r   r  )r   r   debugr  r   r  r;  r   )r   r  r  r   r  r   r   r   	to_screen  s    & zYoutubeDL.to_screenc                 C   sP   t |tst| jdr,| jd | n | j| | d| jj|d dS )zPrint message to stderrr  r   r  N)	rX  r   r   r   r   r   r  r  r;  r   r  r  r   r   r   	to_stderr  s    zYoutubeDL.to_stderrc                 C   s(   t dks| jjsd S | || jj d S )Nr   )r   r;  r   r  )r   coder   r   r   _send_console_code  s    zYoutubeDL._send_console_codec                 C   sZ   | j ddsd S t|}tdkrDtjj rVtjjt	| n| 
d| d d S )NconsoletitleFr   z]0;)r   r   rs   r   ctypeswindllkernel32ZGetConsoleWindowZSetConsoleTitleW	c_wchar_pr  r   r  r   r   r   to_console_title  s    zYoutubeDL.to_console_titlec                 C   s*   | j dr| j drd S | d d S )Nr  r  z[22;0tr   r   r  r  r   r   r   save_console_title  s    zYoutubeDL.save_console_titlec                 C   s*   | j dr| j drd S | d d S )Nr  r  z[23;0tr  r  r   r   r   restore_console_title  s    zYoutubeDL.restore_console_titlec                 C   s   |    | S r  )r  r  r   r   r   	__enter__  s    zYoutubeDL.__enter__c                 C   s   | j dd k	r| j  d S )N
cookiefile)r   r   	cookiejarsaver  r   r   r   save_cookies  s    zYoutubeDL.save_cookiesc                 G   s   |    |   d S r  )r  close)r   r   r   r   r   __exit__  s    zYoutubeDL.__exit__c                 C   s$   |    d| jkr | j  | `d S )N_request_director)r  __dict__r  r  r  r   r   r   r    s    

zYoutubeDL.closec                 C   s(  |dk	r|  | | jdr|dkrt d rd}tt d drxt d jd rx|dtjt d j 7 }|t	t
 7 }ntt }d|}|r|  | |sdS | jdst d rtt d drt d jd rt d j}nt }t||d| _dS )a  Determine action to take when a download problem appears.

        Depending on if the downloader has been configured to ignore
        download errors or not, this method may throw an exception or
        not when errors are found, after printing the message.

        @param tb          If given, is additional traceback information
        @param is_error    Whether to raise error according to ignorerrors
        Nr  r   r   r   exc_infoignoreerrors)r  r   r   r   r  r  r  	tracebackformat_exceptionrY   
format_excformat_listextract_stackr?   r2  )r   r  tbis_errorZtb_datar  r   r   r   trouble  s*    

$

6
zYoutubeDL.troubleZyellowz
light blueZgreenZblueZredz	light redzlight black)	HEADERSrI  FILENAMEIDDELIMrJ  
BAD_FORMATWARNINGSUPPRESStest_encodingc          	      C   st   t |}|rR|}| jdp*t|dd p*d}||d|}|d k	rR||krR|}|dkrdt||S |d krp|S |S )Nr  r  ignoreT)r   r   r   getattrr  r  r   )	r   handleZallow_colorstextffallbackr  Zoriginal_textr  r   r   r   _format_text  s    zYoutubeDL._format_textc                 O   s   | j | jj| jjf||S r  )r  r;  r   rD  r   r   r   r   r   r   _format_out   s    zYoutubeDL._format_outc                 O   s   | j | jj| jjf||S r  )r  r;  r   rD  r  r   r   r   _format_screen#  s    zYoutubeDL._format_screenc                 O   s   | j | jj| jjf||S r  )r  r;  r   rD  r  r   r   r   rG  &  s    zYoutubeDL._format_errc                 C   sX   | j ddk	r"| j d | n2| j dr2dS | | d| jj d| | dS )z
        Print the message to stderr, it will be prefixed with 'WARNING:'
        If stderr is a tty file the 'WARNING:' will be colored
        r  NZno_warningszWARNING: )r   r   warningr  rG  rH  r  r  r   r   r   r  )  s
    zYoutubeDL.report_warningr   )
stacklevelc                C   s   t ||d | jdd d S )Nr   F)r  printerr  )rV   r   )r   r  r  r   r   r   rV   5  s       zYoutubeDL.deprecation_warningc                 C   sL   | j dd k	r&| j d d|  | | d| jj d| d d S )Nr  zDeprecated Feature: zDeprecated Feature:r  T)r   r   r  r  rG  rH  rJ  r  r   r   r   rE  9  s    zYoutubeDL.deprecated_featurec                 O   s,   | j | d| jj d| f|| dS )z
        Do the same as trouble, but prefixes the message with 'ERROR:', colored
        in red if stderr is a tty file.
        zERROR:r  N)r  rG  rH  rJ  )r   r  r   r   r   r   r   r   >  s    zYoutubeDL.report_errorc                 C   sJ   | j ddsdS d| }| j dr:| j d | n| || dS )z,Log debug message or Print message to stderrr  FN[debug] r  )r   r   r  r  r  r   r   r   r  E  s    
zYoutubeDL.write_debugc                 C   s:   z|  d| d W n tk
r4   |  d Y nX dS )z.Report file has already been fully downloaded.[download] z has already been downloadedz/[download] The file has already been downloadedNr  UnicodeEncodeErrorr   	file_namer   r   r   report_file_already_downloadedO  s    z(YoutubeDL.report_file_already_downloadedc                 C   s8   z|  d|  W n tk
r2   |  d Y nX dS )z*Report that existing file will be deleted.zDeleting existing file zDeleting existing fileNr  r  r   r   r   report_file_deleteV  s    zYoutubeDL.report_file_deleterg  c                C   sh   | d}| j dt| }}|p.|r,dp.d}|s8|sZt||d |d |pR|pR|dn
| | d S )N_has_drmignore_no_formats_errorzThis video is DRM protectedzNo video formats found!id	extractor)video_idry  expected)r   r   rB  rB   r  )r   infoZforcedrg  r   Zignoredr  r   r   r   raise_no_formats]  s    

zYoutubeDL.raise_no_formatsc                 C   s   |  d |   | jd S )NzN"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future versionouttmpl)rV   r]  r   r  r   r   r   parse_outtmplg  s    
zYoutubeDL.parse_outtmplc                    sd   t | jdrdd | jdi  t tsBd i | jd<    fddt D  d S )Nr  c                 S   s   |  dd ddS )N - r  r  rF  xr   r   r   <lambda>o      z*YoutubeDL._parse_outtmpl.<locals>.<lambda>r  r~  c                    s(   i | ] \}}  |d kr||qS r  r   r   r   vr  sanitizer   r   r   t  s       z,YoutubeDL._parse_outtmpl.<locals>.<dictcomp>)	r3   r   r   r=  rX  rY  updater2   rd  r  r   r  r   r]  l  s    
zYoutubeDL._parse_outtmplr   c                 C   sp   | j di }t|ts tdtjt|dd	 |rPt||d	 nd|pXd}t
|| j ddS )Npathsz&"paths" parameter must be a dictionaryhomer   Zwindowsfilenames)force)r   r   rX  rY  r   r?  pathr  r\   r!  rw   )r   dir_typefilenamer  r  r   r   r   get_output_pathv  s    zYoutubeDL.get_output_pathc                 C   sJ   d tjtjdd}| dd| ddd| d} t| |dS )Nr       r   z%%%z$$$)r  randomchoicesstringascii_lettersrF  r\   )r  sepr   r   r   _outtmpl_expandpath  s    $zYoutubeDL._outtmpl_expandpathc                 C   s   t tdddd | S )z2 Escape any remaining strings like %s, %abc% etc. r   z	(?![%( ])c                 S   s   |  drdnd|  d S )Nhas_keyr   r  r   groupmobjr   r   r   r    r  z*YoutubeDL.escape_outtmpl.<locals>.<lambda>)rl  subr:   r   r  r   r   r   escape_outtmpl  s
    
zYoutubeDL.escape_outtmplc              
   C   sj   t tdddd | |}z| |tt  W dS  t	k
rd } z| W Y S d}~X Y nX dS )z" @return None or Exception object [^)]*z
[ljhqBUDS]c                 S   s   |  dd d  dS )Nr   sr  r  r   r   r   r    r  z,YoutubeDL.validate_outtmpl.<locals>.<lambda>N)
rl  r  r:   r   r
  r  collectionsdefaultdictintr  )clsr  errr   r   r   validate_outtmpl  s    
zYoutubeDL.validate_outtmplc                 C   s$   t | } | dd  | dd  | S )N__postprocessors__pending_error)rY  rU  	info_dictr   r   r   _copy_infodict  s    zYoutubeDL._copy_infodictc           	   
      s   dtt  dddk	rDtd r>dndndd< tjddd j d	< jd
< ddkrj	ddd< t
dpdt
dpdjdpddi ttddt d}tjtjtjddddi }d|d| dd }d| dt d d!d"ttj td#| d$  d% d&d' fd(d)fd*d+
jd,d-jd.ffd/d0		trĈn	td1d2 G d3d4 d4tj}|  	
f
d5d6}|||fS )7a	   Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
        @param sanitize    Whether to sanitize the output as a filename.
                           For backward compatibility, a function can also be passed
        epochr   Nr  :duration_stringZautonumber_startr   r  Zvideo_autonumberr   r~  __last_playlist_indexr   	n_entriesZautonumber_size   )playlist_indexplaylist_autonumberr  r  [z	ljhqBUDS])+r  *z*(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})numz	(?:-?\d+)z2\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*z\w*(?:\.z)*)innerfieldz(?:z|-?)z(?:{})|z8(?xs)
            (?P<negate>-)?
            (?P<fields>z)
            (?P<maths>(?:z)*)
            (?:>(?P<strf_format>.+?))?
            (?P<remaining>
                (?P<alternate>(?<!\\),[^|&)]+)?
                (?:&(?P<replacement>.*?))?
                (?:\|(?P<default>.*?))?
            )$c                 S   s@   | dkrdS d| kr(t tt| d S t| d k	r<t| S | S )Nr"  .)slicemaprf   splitr  )r/  r   r   r   _from_user_input  s    z3YoutubeDL.prepare_outtmpl.<locals>._from_user_inputc                    s   dd t d| D } dD ]}| r| | s| | qt| D ]b\}}|ds^ || |< q>|ds|td| d|   fd	d
|dd dD | |< q>t| ddS )Nc                 S   s0   g | ](}| d r|gn|dD ]}|q"qS ){.r   r4  )r   r  r  r   r   r   rq    s     zIYoutubeDL.prepare_outtmpl.<locals>._traverse_infodict.<locals>.<listcomp>z\.({.+?})\.?)r   r  r6  }zNo closing brace for z in c              	      s"   i | ]}|t t |d qS )r7  )r  r3  r4  r   )r5  r   r   r     s      zIYoutubeDL.prepare_outtmpl.<locals>._traverse_infodict.<locals>.<dictcomp>r   r  r   T)Ztraverse_string)rl  r4  rU  rt  r   r   r   r   )fieldsro  r  )r5  r  r   r   _traverse_infodict  s    
&z5YoutubeDL.prepare_outtmpl.<locals>._traverse_infodictc              	      s8  | d }| d r,t |}|d k	r,|d9 }| d }|r t |}d }|r t|rX n|d}|t|d  }|d kr| }qF|d dkr|dd  dfn|df\}}t |}|d krt |}z|||| }W n ttfk
r   Y d S X d }qF| d r t|| d d	d
}r4|dkr4d }|S )Nr:  negater  Zmathsr   r  r   Zstrf_formatz\,r   r   )	r_   rl  rm  r  r  	TypeErrorZeroDivisionErrorr{   rF  )ZmdictvalueZ
offset_keyoperatoritemZ
multiplieroffset)MATH_FIELD_REMATH_FUNCTIONSMATH_OPERATORS_REr;  r  r   r   	get_value  sD    
(
z,YoutubeDL.prepare_outtmpl.<locals>.get_valueZouttmpl_na_placeholderZNAr  c                    s0   t t||d jd kr(ttd| ntdS )Nzfilename-sanitizationr   z(^|[_.])id(\.|$))
restrictedZis_id)rv   r   r   rB  rl  searchr6   )r  r?  rG  r  r   r   filename_sanitizer!  s
    
z5YoutubeDL.prepare_outtmpl.<locals>.filename_sanitizerc                 S   s   t | ttfrt| S t| S r  )rX  r  rF   r  reprobjr   r   r   _dumpjson_default*  s    z4YoutubeDL.prepare_outtmpl.<locals>._dumpjson_defaultc                   @   s   e Zd Zdd ZdS )z8YoutubeDL.prepare_outtmpl.<locals>._ReplacementFormatterc                 S   s    |  r|d dfS tdd S )Nr   r  zUnsupported field)isdigitr  )r   
field_namer   r   r   r   r   	get_field0  s    zBYoutubeDL.prepare_outtmpl.<locals>._ReplacementFormatter.get_fieldN)__name__
__module____qualname__rP  r   r   r   r   _ReplacementFormatter/  s   rT  c                    s*  |  ds|  dS |  d}t |}d d df\}}}}|r| }|d d k	r^|d n|}|}|d |d  }}|d kr|d rt |d	 d
d  }q>qq>d ||fkrz||}W n tk
r   d  }}Y nX |  d}|dkr"|kr"t|tr"d| dd}|  dp0d}|d d  d}	|d kr\|d }}n>|d dkrd|krxdnd}
|
t	t
t|t
tfd|	 }}n|d dkrtj|d|krdnd d|kd|	 }}n|d dkrtt
||	 }}n|d dkrDt	t
d|kr&t|n|g}t|dd|	 }}nV|d dkrd|	  t
|  }|d d!d }}n|d d"krtd#d|krd$ndd|krd%nd&||	 }}n|d d%kr |d d ddd }}t||rd| d'nd(d|krd)nd*d+}nz|d d,krH||d|kd-|	 }}nR|d d.krp|rjt
|d }n|	}n*|d d/krt|}|d kr|d }}r|d d0krt||	 }}n|d d1krt||	 }}|d d2kr	||}d3|dd4|  d}||< d5j|||  d6d7S )8Nr  r   r  r   r~  r:  replacementZ	alternate	remainingr   r   r  0d
conversionr  l#r   , )Zallowed_typesj   r+  )r~  indentensure_asciihqT)shellBr  r  r  UzNF{}{}KDCzf%sz%d%si     )ZfactorS)rG  crsar  rp  Zcsraz{} {}z% z{prefix}%({key}){fmt}prefix)r  fmtrm  )r  rl  rm  	groupdictr   r  rX  r  r  r3  r   r   bytesjsondumpsr[   ry   r  r  unicodedata	normalizerF  ra   r_   rJ  r  )Z
outer_mobjr  r  r?  rU  r~  Z
last_fieldrn  flagsZstr_fmtdelimZnum_fmt)
INTERNAL_FORMAT_RE	TMPL_DICTrM  field_size_compat_maprI  rF  nareplacement_formatterr  	sanitizerr   r   
create_key7  s    



 
&  
&


z-YoutubeDL.prepare_outtmpl.<locals>.create_key)r=  r  timer   r   rc   r   r3  r4  format_resolutionrm   rl  compiler:   r   r;   float__add____sub____mul__r7   r  r3  escapekeysr^  rB  r  	Formatterr  )	r   r  r  r  ZEXTERNAL_FORMAT_REZFIELD_INNER_REZFIELD_RErT  r}  r   )rw  rC  rD  rE  rx  rM  r5  r;  ry  rI  rF  r  rz  r{  r  r|  r   r   prepare_outtmpl  s\    
 


	'PzYoutubeDL.prepare_outtmplc                 O   s&   | j ||f||\}}| || S r  )r  r  )r   r  r  r   r   r   r   r   evaluate_outtmpl  s    zYoutubeDL.evaluate_outtmpl)r  	tmpl_typec             
   C   sh  d ||fkst d|d kr<| jd |p,d| jd d }z| |}| ||d}|s`W d S |dkr| jd|d }}|r|r||kr|d| rt|||}n"|rt| }|rt|||d}| jd	d
}|r|dd^}	}t	|	d | f|ddi}|W S  t
k
rb }
 z.| dt|
 d tt  d  W Y d S d }
~
X Y nX d S )Nz,outtmpl and tmpl_type are mutually exclusiver  r~  Tr   temp	final_extr   r7  trim_file_nameF   rv  zError in output template: z (encoding: r0  )r   r   r   r
  r  r   ru   r8   rsplitri   r  r   r   rJ  rq   )r   r  r  r  r  r  r   Z	force_extr  Zno_extr  r   r   r   _prepare_filename  s0     
 $zYoutubeDL._prepare_filename)r  warnc                C   s   |r|rt dd}| j|||d}|s4|dkr4dS |rx| jdsFn2|dkr^| jdd	d
 ntj|rx| jdd	d
 |dks|s|S | ||S )zGenerate the output filenamez+outtmpl and dir_type are mutually exclusiveN)r  r  r  r   r  r  z/--paths is ignored when an outputting to stdoutTr  zE--paths is ignored since an absolute path is given in output template)	r   r  r   r   r  r?  r  isabsr   )r   r  r  r  r  r  r   r   r   prepare_filename  s     zYoutubeDL.prepare_filenamec           	   
      s:  dj d krdn
dd s2 dks2tdddd fd	d
}rdtddjj dtddjj	 ddf}dt
 }}nNz
| }W n8 tk
r } z|jdt|  }}}W 5 d}~X Y nX dt }}|dk	r6|s d|  j |dr6| |S )z-Returns None if the file should be downloadedzplaylist-match-filterr   r   _typez,Only video result can be considered completetitler  entryc               
      s   dkrd S  dkr*t fdds*d S dkrd } jdd}|rpt|| tjspd|  d	 | d S jd
d}|rt|| tjrd|  d | d S d}|d k	rjdt }||krt|  d| S d}|d k	rVjd}|d k	r(||k r(d||f S jd}|d k	rV||krVd||f S t	djdr|d dS jd}|d krd S d }	z>z|d}
W n( t
k
r   rd n|}
Y nX W n> tk
r } z|jtk	r |j| }
}	W 5 d }~X Y nX |
tkrjj}td| djj  }|dkrjd S |dkr"|	rt|	d d S q"|
S )NplaylistZmulti_videor   url_transparentc                      s     d  d S )Nrv  r   )r   Zis_single_videor   r  r   r   r   r    r  z>YoutubeDL._match_entry.<locals>.check_filter.<locals>.<lambda>r  
matchtitleF"z" title did not match pattern "rejecttitlez " title matched reject pattern "upload_dateZ	daterangez upload date is not in range r   	min_viewszBSkipping %s, because it has not reached minimum view count (%d/%d)	max_viewszCSkipping %s, because it has exceeded the maximum view count (%d/%d)r   z
Skipping "z" because it is age restrictedmatch_filter
incompletez
Download "z
"? (Y/n): >   r   ynz	Skipping )r   r   r   rl  rH  
IGNORECASEr=   rU   	isoformatrS   r=  r>   rg  r6   r  r  rH  r  inputrI  rA  r!  rw  )r  r  r  dateZ
date_ranger   r  r  r  Z	cancelledretr  r  Zreplyr  r  r  r   Zvideo_titler   r   check_filter  sr    






 

z,YoutubeDL._match_entry.<locals>.check_filterr   %s: r  z(has already been recorded in the archivebreak_on_existingr  NZbreak_on_rejectr  F)r   r   r   in_download_archiver  rb   r  rH  r  rI  rA   r>   rg  rw  rN   r  )	r   r  r  Zsilentr  reasonZ	break_optZ	break_errrf  r   r  r   _match_entry  s,    @

(

zYoutubeDL._match_entryc                 C   s"   |  D ]\}}| || qdS )z=Set the keys from extra_info in info dict if they are missingN)rd  r=  )r  
extra_infor  r?  r   r   r   add_extra_info  s    zYoutubeDL.add_extra_infoc                 C   s(  |dkri }|s|rd}|r:|| j kr4|| j | ini }n| j }| D ]\}}	|	|s\qH|	 sn| d |	|}
|
dk	r| |
|dr| d| |
| j	j
 d | jddrt q$| || ||||  S | jd	dd
gfk}| jdt|dd d| |rdndd dS )a  
        Extract and return the information dictionary of the URL

        Arguments:
        @param url          URL to extract

        Keyword arguments:
        @param download     Whether to download videos
        @param process      Whether to resolve all unresolved references (URLs, playlist items).
                            Must be True for download to work
        @param ie_key       Use only the extractor with this key

        @param extra_info   Dictionary containing the extra values to add to the info (For internal use only)
        @force_generic_extractor  Force using the generic extractor (Deprecated; use ie_key='Generic')
        NGenericz^The program functionality for this site has been marked as broken, and will probably not work.)r  rv  r  z*: has already been recorded in the archiver  Fr}  r~  zNo suitable extractor (%s)z found for URL r  )r+  rd  suitableworkingr  get_temp_idr  r  r  rH  r  r   r   rA   _YoutubeDL__extract_infor   r   rb   )r   r   downloadrv  r  processforce_generic_extractorZiesr  ry  Ztemp_idZextractors_restrictedr   r   r   extract_info"  s.    


zYoutubeDL.extract_infoc                    s   t   fdd}|S )Nc                    s|  z | f||W S  t ttjtjfk
r6    Y qx tk
r } z>|jr^| | d n| d | 	| d W Y q W 5 d }~X Y n t
k
r } z@|j}|jr|ddttj|j7 }|d7 }| | W 5 d }~X Y n tk
r" } z| t||  W 5 d }~X Y nP tk
rp } z0| jdr^| jt|tt d n W 5 d }~X Y nX qxq d S )Nz; Re-extracting dataz
This video is available in {}.r\  zL
You might want to use a VPN or a proxy server (with --proxy) to workaround.r  r  )r   r>   rF   
IndexErrorrI   rM   r  r  r  r  rD   rg  Z	countriesr   r  r3  rE   Z
short2fullr   rB   r   Zformat_tracebackr<  r   r   rY   r  r  )r   r   r   rf  rg  r   r   r   r   U  s2    

$z8YoutubeDL._handle_extraction_exceptions.<locals>.wrapperr   r   r   r   r   _handle_extraction_exceptionsT  s    z'YoutubeDL._handle_extraction_exceptionsc           	   
      s  j dr0|dddks0|ds0|dr4d S dd }d  fd	d
}j d\}}t|dd }|d kr|ddkrt|r|rt||n|p|d}d n|r|pddkrʈd tt|pd|pd|pt	d}
d|| d t | }zZ|t  }|dkr8|d tddd|d||jj  td qW nd tk
r   |d tdddY n< tk
r } zt|ts
d  W 5 d }~X Y nX d S )Nwait_for_videor  r   formatsr   c                 S   s   dt | d d d  S )Nz%02d:%02d:%02dri  r  )r   )Zdurr   r   r   r  z  r  z+YoutubeDL._wait_for_video.<locals>.<lambda>r   c                    sR   |  d}j ds4| dt t|    d }n r<d S j|dd |  d S )Nr   
noprogressr  r  T)r  )r   r   r  r  )rg  Zfull_msgZlast_msgr   r   r   progress}  s    
z+YoutubeDL._wait_for_video.<locals>.progressc                 S   s   | d t    S )Nr   )r~  r  r   r   r   r    r  live_statusZis_upcomingr   z"Release time of video is not knownz=Video should already be available according to extracted infoinfz[wait] Waiting for z - Press Ctrl+C to try nowz[wait] Wait period endedT)r  z*[wait] Remaining time until next attempt: r   z[wait] Interrupted by user)r   r   r   roundr  uniformr  minmaxr  r  r~  rM   r  rH  rI  sleepKeyboardInterruptBaseExceptionrX  )	r   	ie_resultZ
format_durr  Zmin_waitZmax_waitZdiffZ	wait_tillrf  r   r  r   _wait_for_videot  sF    
"
 

zYoutubeDL._wait_for_video	autoscopec                C   s  t | D ]}|r*t| r*td|dp6d}|d}|dkrNd}tj|dp`d|j|j	dd|d	d	|d
p~dt
|d
|dpd|dddi }|r| j| q|d	kr| d | j| q|r| jdtdd d	d | ||g q| jdddd qdS )an  Loads cookies from a `Cookie` header

        This tries to work around the security vulnerability of passing cookies to every domain.
        See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj

        @param data         The Cookie header as string to load the cookies from
        @param autoscope    If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains
                            If `True`, save cookies for later to be stored in the jar with a limited scope
                            If a URL, save cookies in the jar with the domain of the URL
        zInvalid syntax in Cookie Headerdomainr   expiresNversionr   FTr  securezPassing cookies as a header is a potential security risk; they will be scoped to the domain of the downloaded urls. Please consider loading cookies from a file or browser instead.zmThe extractor result contains an unscoped cookie as an HTTP header. If you are using yt-dlp with an input URLr   )beforer  zEUnscoped cookies are not allowed; please specify some sort of scopingr  r  )r   r  r   r  r   httpr  r  r  r?  rB  
set_cookierE  r8  r>  r  rT   _apply_header_cookiesr   )r   datar  cookier  ZexpiryZprepared_cookier   r   r   rT    sT    
              zYoutubeDL._load_cookiesc                 C   sL   t j|}|jsdS ttj|p$| jD ]}d|j |_| j	| q(dS )a'  Applies stray header cookies to the provided url

        This loads header cookies and scopes them to the domain provided in `url`.
        While this is not ideal, it helps reduce the risk of them being sent
        to an unintended destination while mostly maintaining compatibility.
        Nr7  )
r   parseurlparsehostnamer3  copyr8  r  r  r  )r   r   r   parsedr  r   r   r   r    s    zYoutubeDL._apply_header_cookiesc              
   C   s   |  | z||}W nF tk
r^ } z(|rL| jdrD| | |    W 5 d }~X Y nX |d kr| d|j dt   d S t	|t
rd|d}|dr|d|d  | ||| |r| | | |||S |S d S )Nr  z
Extractor z returned nothingcompat_list)r  entriesoriginal_url)r  extractrQ   r   r   r  r  r{  rT   rX  r  r=  add_default_extra_infoprocess_ie_result)r   r   ry  r  r  r  r  rf  r   r   r   Z__extract_info  s.    




zYoutubeDL.__extract_infoc                 C   sf   |d k	r|  |||d |d}|rB|  |t|t|d |d k	rb|  ||j| d d S )N)webpage_urlr  r  )webpage_url_basenamewebpage_url_domain)r  extractor_key)r  r   r   re   r{  rv  )r   r  ry  r   r  r   r   r   r    s     
z YoutubeDL.add_default_extra_infoc              	      s  dkri  dd}|dkr6td j dr:dndd	d<  d
rj d
sjd
d
 ij dd}|dkrdks|dkr6 }t dj}|r̈ ds|d |d< ||d  | 	|\}}
|d | | j ddr2| S |dkrڈ jd pli  d}	|	rt|	tr|	g}	dd t|	 dd|	 fdd|	D d< S |dkr jd  ddS |dkrjd  dddd}
|
s2|
S dddh dsf ddkrfdd d!hO |
 }|tfd"d# | ddkrd|d< j|d$S |d%kr` d&}|r|jkrd' d(p d dS  jd)7  _j| 
d  zW S  jd)8  _js\j  X n`|d*kr d+ d  fd,d-  fd.dd/ D d/< S t!d0| dS )1z
        Take the result of the ie(may be modified) and resolve all unresolved
        references (URLs, playlist items).

        It will also download the videos if 'download'.
        Returns the resolved ie_result.
        Nr  r   r  r   Zprefer_insecurer  https)schemer  extract_flatFZin_playlistr  Trv  r  force_write_download_archiver  additional_urlsz)[info] {}: {} additional URL(s) requestedzAdditional URLs: "{}"", "c              	      s&   g | ]}j | jd dqS )r  )r  r  )r  r   r   )r   r   )r  r  r   r   r   rq  :  s     
z/YoutubeDL.process_ie_result.<locals>.<listcomp>Zadditional_entries)rv  r  r  )rv  r  r  r  section_endsection_startr  r  c                    s   |d k	o|  kS r  r   r   r  )exempted_fieldsr   r   r  Z  r  z-YoutubeDL.process_ie_result.<locals>.<lambda>r  r  r  r  z3[download] Skipping already downloaded playlist: {}r  r   r  zCExtractor {} returned a compat_list result. It needs to be updated.c              	      s8    |  d  d t d t d  d d | S )Nr  r  r  )r  r  r  r  r  )r  r   re   )r  )r  r   r   r   _fixup  s    

z+YoutubeDL.process_ie_result.<locals>._fixupc                    s   g | ]}  |qS r   r  )r   r  )r  r  r  r   r   r   rq    s   r  zInvalid result type: )"r   rx   r   r  r   r   r  r  r  pre_process_fill_common_fields_YoutubeDL__forced_printings_raise_pending_errorsrecord_download_archiveprocess_video_resultrX  r   r  r   r  r  r  r  r  r^   r  r6  r5  r   _sanitize_thumbnailsclear_YoutubeDL__process_playlistr  r<  )r   r  r  r  Zresult_typer  	info_copyry  r  r  r  Z
new_resultr  r   )r  r  r  r  r  r   r   r    s    
 







 
   
  



	
zYoutubeDL.process_ie_resultc                 C   s   t || jS r  )rl   r   )r   r  r   r   r   _ensure_dir_exists  s    zYoutubeDL._ensure_dir_existsc              
   K   s   |  d|  dp|  d|  d|  d|  d|  d|  d|  dd|}|r\|S |  d	r|| d	 t| d	 t| d	 d
 |dt|  dpd| d | d dS )Nplaylist_countr  r  ZuploaderZuploader_idZchannelZ
channel_id)r
  r  Zplaylist_idZplaylist_titleZplaylist_uploaderZplaylist_uploader_idZplaylist_channelZplaylist_channel_idr  )r  r  r  r   requested_entries)r   r   r  r  )r(  r%  r  r  )r   r  r   re   r  )r  strictr   r  r   r   r   _playlist_infodict  s2    	


zYoutubeDL._playlist_infodictc                    sl   d dkst | j dd}|dp*d}| j|dddk	rBdS | d	 d  d
|  t|  }t| dd}| jd}|rg d }}	d\ d<  d< n4t	| }}t
|}	tt| pg g f\ d<  d<  ds|  d< | j t|	d}
t |
}d}| jdd}|r:| jdr:|   |r| jds| d | |d}|dkrrdS | d | |ddkrdS | d | |d |r| jds| jdr
| jddd n0| jdr|  n| jdr
t| | d d  d | d!|	 d"t dd#  | jd$d%k}| jd$d&krf d dk}|rv| d' d(}| jd)ptd*}t|D ]:\}\}}|r|||f |sĐq d+|d+< |sd,| jd- kr d | }t||t|	||d. d/}| j|dddk	r8|tf||< q| d0|  |d. | j!j" d1|  |	| j!j#  | $||t||d. d2|
}|s|d.7 }||kr| %d3| d4| d5  q|r||f||< qd6d7 |D  d< d8d7 |D  d<  d t& fd9d:kr 'd |dkrL| jd; | |ddd<dkrLdS | (d  | d=|   S )>z"Process each entry in the playlistr  r  T)r  r  z
<Untitled>r  Nz[download] Downloading r  )lazyZlazy_playlistzN/A)NNr  r  r
  )r&  FZallow_playlist_filesr  r  Zpl_infojsonZpl_descriptionZpl_thumbnailZplaylistreverseZplaylistrandomzGplaylistreverse and playlistrandom are not supported with lazy_playlistr  r*  r  z] Playlist z: Downloading z itemsz of %sr  discardZdiscard_in_playlistz>The information of all playlist entries will be held in memoryr   Zskip_playlist_after_errorsr  __x_forwarded_for_ipzplaylist-indexr   r   )r&  r(  r)  z[download] Downloading item z of )r(  r)  z,Skipping the remaining entries in playlist "z" since z items failed extractionc                 S   s   g | ]\}}|t k	r|qS r   r6   )r   r  rf  r   r   r   rq    s      z0YoutubeDL.__process_playlist.<locals>.<listcomp>c                 S   s   g | ]\}}|t k	r|qS r   r  )r   ro  rf  r   r   r   rq    s      c                      s   t td d d S )Nr   r
  )r  r  r   r  r   r   r    r  z.YoutubeDL.__process_playlist.<locals>.<lambda>zupdated playlist)	overwritez*[download] Finished downloading playlist: ))r   r  r   r  r  rJ   rn   Zget_requested_itemsr   r  r  tuplezipZget_full_countrf   r  ChainMapr  _write_info_jsonr  _write_description_write_thumbnailsr  reverser  shufflerb   r  r  rt  r>  r6   r  rH  r  rI  "_YoutubeDL__process_iterable_entryr   r   rU  run_all_pps)r   r  r  Zcommon_infor  Zall_entriesr  r  Zresolved_entriesr&  extraZie_copy_infojson_writtenZwrite_playlist_filesZkeep_resolved_entriesZfailuresZmax_failuresro  r(  r  Z
entry_copyZentry_resultr   r  r   Z__process_playlist  s    

 

  




.

*

 
 zYoutubeDL.__process_playlistc                 C   s   | j |||dS )Nr  r  )r   r  r  r  r   r   r   Z__process_iterable_entry'  s
      z"YoutubeDL.__process_iterable_entryc              
      s  t jt jt jt jt jt jd}td	d
ttj| }||rztd W nZ tk
r   td  dkrtdd   dkrtd	d|Y nX |d st jd	d
 dd
 dd
 dd
 d}td	d
ttj| }||rddkrFtd ntddd |d drfdd
nstd| fdd}|S )zG Returns a function to filter the formats according to the filter_spec )<z<=>z>==z!=z(?x)\s*
            (?P<key>[\w.-]+)\s*
            (?P<op>{})(?P<none_inclusive>\s*\?)?\s*
            (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
            r1  r?  Nrd  z/Invalid value {!r} in format specification {!r}opc                 S   s
   |  |S r  r   attrr?  r   r   r   r  M  r  z0YoutubeDL._build_format_filter.<locals>.<lambda>c                 S   s
   |  |S r  )r   r%  r   r   r   r  N  r  c                 S   s   || kS r  r   r%  r   r   r   r  O  r  c                 S   s   | | d k	S r  )rH  r%  r   r   r   r  P  r  )r"  z^=z$=z*=~=a"  (?x)\s*
                (?P<key>[a-zA-Z0-9._-]+)\s*
                (?P<negation>!\s*)?(?P<op>{})\s*(?P<none_inclusive>\?\s*)?
                (?P<quote>["'])?
                (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
                (?(quote)(?P=quote))\s*
                r'  z
\\([\\"'])z\1Znegationc                    s    | | S r  r   r%  )str_opr   r   r  a  r  zInvalid filter specification c                    s,   |  d}|d kr"dS | S )Nr  Znone_inclusive)r   r  )r  Zactual_value)comparison_valuemr#  r   r   _filterh  s    
z/YoutubeDL._build_format_filter.<locals>._filter)r@  ltlegtgeeqnerl  r  r   r  r3  r  r  	fullmatchr  r  r  rp   r  SyntaxError)r   Zfilter_specZ	OPERATORSZoperator_rexZSTR_OPERATORSZstr_operator_rexr+  r   )r)  r*  r#  r(  r   _build_format_filter,  sb    
 

zYoutubeDL._build_format_filterc                 c   s6  |D ]*}| d}|d k	r(|r|V  q| d|d  | d}| | dsXqtjdd|pfd d}|  zBz| j|j|dd\}}W n" tttftk
r   d}Y nX W 5 tj	
|jrzt|j W n* tk
r   | d	|j d
 Y nX X ||d< |r|V  q| d|d  qd S )NZ	__workingz[info] Testing format {}r   r  /z.tmpF)suffixdeletedirz!Unable to delete temporary file "r  T)testz0[info] Unable to download format {}. Skipping...)r   r  r   r   r	  tempfileNamedTemporaryFiler  r?  r  existsr   remover"  r  dlr?   r  r   )r   r  r  r  r  	temp_filesuccessr  r   r   r   _check_formatso  s2    


zYoutubeDL._check_formatsc                 C   sB   t ||tdd |D tdd |D p8tdd |D dS )Nc                 s   s&   | ]}d | d| dfkV  qdS )noner   r   Nr  r   r  r   r   r   r    s     z,YoutubeDL._select_formats.<locals>.<genexpr>c                 s   s   | ]}| d dkV  qdS )r   rB  Nr  rC  r   r   r   r    s     c                 s   s   | ]}| d dkV  qdS )r   rB  Nr  rC  r   r   r   r    s     )r  has_merged_formatincomplete_formats)r  r   r  )r   r  selectorr   r   r   _select_formats  s    zYoutubeDL._select_formatsc                    s   j d d dkp(|do(j d }fdd}|sv| svd}|  fd	d
}|d|dkrvd j dpdj d k}|rdS |rdS dS )Nr  r~  r  is_livelive_from_startc                     s   t  } | jo|  S r  )r'   	available	can_merge)mergerr  r   r   rK    s    z1YoutubeDL._default_format_spec.<locals>.can_mergeTc                    s     | S r  )rG  r_  )specr  r   r   r   r    r  z0YoutubeDL._default_format_spec.<locals>.<lambda>zb/bv+bazbv*+ba/bzffmpeg not found. The downloaded format may not be the best available. Installing ffmpeg is strongly recommended: https://github.com/yt-dlp/yt-dlp#dependenciesallow_multiple_audio_streamszformat-specr   zbest/bestvideo+bestaudiozbestvideo+bestaudio/bestzbestvideo*+bestaudio/best)r   r   _get_formatsr  )r   r  Zprefer_bestrK  Zevaluate_formatscompatr   rN  r   _default_format_spec  s"    


zYoutubeDL._default_format_specc              	      sX  fddddddt ddd	d
g jddjddd
dd dd }d& 	fdd		
fddfddfdddtjtjddt	
td d }z&t|fd d!t|jD }W n* tjk
r0   d"d#tfY nX G d$d% d%}	t||}|S )'Nc                    s   d |  d|d  }t|S )Nz)Invalid format specification: {}
	{}
	{}^r  r   )r   r3  )notestartr  format_specr   r   syntax_error  s      
z5YoutubeDL.build_format_selector.<locals>.syntax_error	PICKFIRSTMERGESINGLEGROUPFormatSelectorrw  rF  filtersrO  FZallow_multiple_video_streamsr   r   c                 S   sF   g }| D ]8\}}}}}|t jkr6|dkr6d|  S || qd S )N]r   )tokenizeOPr  r>  )tokensZfilter_partstype_string__startr  r   r   r   _parse_filter  s
    z6YoutubeDL.build_format_selector.<locals>._parse_filterc                 s   s&  d}d\}}}}| D ]\}}}}	}
|t jkr|dkr|rNt j||||fV  d }||||	|
fV  | D ]4\}}}}	}
||||	|
fV  |t jkrb|dkrb qqbq|t jkr||kr|rt j||||fV  d }||||	|
fV  q|t jt jt jfkr|s |}|}|	}q||7 }q|r"t j||||fV  d S )N)r5  r+  r   (r0  )NNNNr*  r_  )r`  ra  NAMENUMBER)rb  ZALLOWED_OPSZlast_stringZ
last_startZlast_end	last_linerc  rd  rT  r|  r(  r   r   r   _remove_unused_ops  s2    
z;YoutubeDL.build_format_selector.<locals>._remove_unused_opsc                    s   g }d }| D ]\}}}}	}	|t tdd kr0qq|tjtjfkrN |g }q|tjkr|dkrx|sn|    qq|r|dkr|    qq|r|dkr|    qq|dkr|sʈd||| d }n|dkr|sd||}
| dd	} |
|fg }n|d
krF|s0 dg }| }|j| n|dkrz|r`d|| dd} |g }n^|dkr|sd||}| dd}|sd| ||fg }nd| d|q|tjkr qq|r|| |S )NENCODINGr0  )r5  r   r   z!"," must follow a format selectorr5  z!"/" must follow a format selectorT)inside_choicer*  bestrg  zUnexpected "(")inside_groupr+  zUnexpected "+")inside_mergezExpected a selectorzOperator not recognized: "r  )	r  r`  rh  ri  ra  restore_last_tokenr>  r]  	ENDMARKER)rb  rp  rm  ro  	selectorsZcurrent_selectorrc  rd  rT  r  Zfirst_choiceZsecond_choiceZformat_filterr  
selector_1
selector_2)r\  r[  rY  rX  rZ  rf  _parse_format_selectionrW  r   r   rv    sj    














z@YoutubeDL.build_format_selector.<locals>._parse_format_selectionc                    s  | \}}g    |d|f   |d|f d rDd sddd}t D ]~\}}|d|d  kr~dkrn n | qVd	D ]@}| s||d
 d dkr|| rʈ |  qVd||< qqVt dkr d
 S dd  D }dd  D }t|dkr|d
 nd }	t|dkr6|d
 nd }
tdd |D dd |D dd |D dd |D tfddpjdodd} fdd} d|dd|d|dt	t
 dt|dpd dt|dpd t|d d!pd t|d"d#d$d%	}|	r||	d&|	d'|	d(pJ|	|	d)|	d*|	d|	d#|	d+|	d,d-	 |
r||
d|
d$|
d.|
d/d0 |S )1Nrequested_formatsr   r   F)r   r   r   r   rB  r^  r   codecTr   c                 S   s   g | ]}| d dkr|qS )r   rB  r  r   fmt_infor   r   r   rq  4	  s      zCYoutubeDL.build_format_selector.<locals>._merge.<locals>.<listcomp>c                 S   s   g | ]}| d dkr|qS )r   rB  r  ry  r   r   r   rq  5	  s      c                 S   s   g | ]}| d qS )r   r  rC  r   r   r   rq  ;	  s     c                 S   s   g | ]}| d qS )r   r  rC  r   r   r   rq  <	  s     c                 S   s   g | ]}|d  qS r   r   rC  r   r   r   rq  =	  s     c                 S   s   g | ]}|d  qS r{  r   rC  r   r   r   rq  >	  s     c                      s    j d dS )Nmerge_output_formatr5  )r   r4  r   r  r   r   r  ?	  r  zAYoutubeDL.build_format_selector.<locals>._merge.<locals>.<lambda>Zprefer_free_formats)webmmkv)ZvcodecsZacodecsZvextsZaextspreferencesc                     s   t d  fddD S )Nc                 3   s   | ]}t |f  V  qd S r  )r   )r   rn  r  r   r   r  B	  s     zTYoutubeDL.build_format_selector.<locals>._merge.<locals>.<lambda>.<locals>.<genexpr>)r:  r  Zformats_infor  r   r  B	  r  r+  r   r   r   r   r   r   r   r   r   )	rw  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   )extendr   rt  rU  r  rd   r   r   r  r3  rX   rn   sumr  r  )Zformats_pairZformat_1Zformat_2Zget_no_morero  rz  Zaud_vidZ
video_fmtsZ
audio_fmtsZthe_only_videoZthe_only_audioZ
output_extfilteredZnew_dict)allow_multiple_streamsr   r  r   _merge	  sz    
$

z/YoutubeDL.build_format_selector.<locals>._mergec                 3   s    j ddkr$ | E d H  d S  j dd k	s@ j drN| E d H  d S | D ]2}|dsj|dr~ |gE d H  qR|V  qRd S )Ncheck_formatsselectedr   r   Z__needs_testing)r   r   rA  )r  r  r  r   r   rA  g	  s    

z7YoutubeDL.build_format_selector.<locals>._check_formatsc                    sl  t | tr,fdd| D fddS | jkrD| jn| jkrrfdd| jD fddn| jkrt| j\

fddn| jkrF| jpdd	kr·fd
dnxdkrfddn^d\td}|d k	rt|ddd|dd dk|dp>d gd ddd		|dd k	} on| r|rfddn&r	fddn|sdd ndd   fddnrj
d  kr܇fd!dnTj
d" krfd#dfd$dn*j
d% kr$fd&dnfd'dfd(dfd)d| jD fd*d+}|S ),Nc                    s   g | ]} |qS r   r   r   r  _build_selector_functionr   r   rq  x	  s     zUYoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.<listcomp>c                 3   s    D ]}|| E d H  qd S r  r   )ctxr  fsr   r   selector_functionz	  s    z\YoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.selector_functionc                    s   g | ]} |qS r   r   r  r  r   r   rq  	  s     c                    s&    D ]}t || }|r|  S qg S r  r  )r  r  Zpicked_formatsr  r   r   r  	  s
    
c                 3   s(   t | | D ]} |V  qd S r  )	itertoolsproduct)r  pair)r  rt  ru  r   r   r  	  s    rn  r  c                 3   s     | d d d d E d H  d S )Nr  r  r   )r  )rA  r   r   r  	  s    Zmergeallc                 3   sT   t  dd | d D }|s"d S |d }|dd d D ]}||f}q8|V  d S )Nc                 s   s.   | ]&}| d dks"| ddkr|V  qdS )r   rB  r   Nr  rC  r   r   r   r  	  s      zoYoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.selector_function.<locals>.<genexpr>r  r  r  )r  r  Zmerged_formatr  )rA  r  r   r   r  	  s    

)FNTr   zS(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$r  r   r$  Zbwr   brw  rp  r  )r  rp  modc                    s   |    ddkS Nrx  rB  r  r  )format_typer   r   r  	  r  zSYoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.<lambda>c                    s   |    ddkS r  r  r  )not_format_typer   r   r  	  r  c                 S   s   |  ddko|  ddkS Nr   rB  r   r  r  r   r   r   r  	  r  c                 S   s   dS NTr   r  r   r   r   r  	  r  c                    s$    | o"|  ddkp"|  ddkS r  r  r  )	_filter_fr   r   r  	  s   r   c                    s   |  d ko|  ddkS )Nr   r   rB  r  r  rU  r   r   r  	  r  r   c                    s*   |  d ko(|  ddko(|  ddkS Nr   r   rB  r   r  r  rU  r   r   r  	  r  c                    s   |  d ko|  ddkS )Nr   r   rB  r  r  rU  r   r   r  	  r  r   c                    s*   |  d ko(|  ddko(|  ddkS r  r  r  rU  r   r   r  	  r  c                    s   |  d kS )Nr   r  r  rU  r   r   r  	  r  c                 3   s   t | d }d k	r"t t|n|}|sdrJ| d rJt tdd |}nrd| d sdt t|}t |d d rvdnd }z|d  V  W n tjk
r   Y d S X d S )Nr  rE  c                 S   s   |  ddkp|  ddkS r  r  r  r   r   r   r  	  r  znYoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.selector_function.<locals>.<lambda>rD  r  r   )r  r:  rF   r  )r  r  matches)rA  filter_fformat_fallback
format_idxformat_reverseseperate_fallbackr   r   r  	  s    c                    s   g | ]}  |qS r   )r4  rC  r  r   r   rq  	  s     c                    s0   t | } D ]}tt||d |d< q|S )Nr  )rY  r  r:  )r  Zctx_copyr+  )r]  r  r   r   final_selector	  s    zYYoutubeDL.build_format_selector.<locals>._build_selector_function.<locals>.final_selector)rX  r  rw  rF  r3  rl  rm  rf   r  r   _format_selection_extsr]  )rF  r  Zformat_modifiedr  )r[  rY  rX  rZ  r  rA  r  r   )r  r  r]  r  r  r  rV  r  r  r  rt  ru  r  r  r   r  v	  sj    





zAYoutubeDL.build_format_selector.<locals>._build_selector_functionr   r  r  z\d[_\d]*z\g<0>c                 3   s$   | ]}|j |j d dV  qdS )r   )r  N)_replacer  rF  )r   token)rm  r   r   r  	  s   z2YoutubeDL.build_format_selector.<locals>.<genexpr>z/Missing closing/opening brackets or parenthesisr   c                   @   s0   e Zd Zdd Zdd Zdd ZeZdd Zd	S )
z6YoutubeDL.build_format_selector.<locals>.TokenIteratorc                 S   s   || _ d| _d S )Nr   )rb  counter)r   rb  r   r   r   rk  	  s    z?YoutubeDL.build_format_selector.<locals>.TokenIterator.__init__c                 S   s   | S r  r   r  r   r   r   __iter__	  s    z?YoutubeDL.build_format_selector.<locals>.TokenIterator.__iter__c                 S   s2   | j t| jkrt| j| j  }|  j d7  _ |S Nr   )r  r  rb  StopIteration)r   r?  r   r   r   __next__	  s
    z?YoutubeDL.build_format_selector.<locals>.TokenIterator.__next__c                 S   s   |  j d8  _ d S r  )r  r  r   r   r   rq   
  s    zIYoutubeDL.build_format_selector.<locals>.TokenIterator.restore_last_tokenN)rQ  rR  rS  rk  r  r  r9  rq  r   r   r   r   TokenIterator	  s
   r  )FFF)r  
namedtupler   r   r  r  r  r  r  ioBytesIOrl  r  r  r  r`  r  
TokenErrorr  iter)r   rV  rk  r   rb  r  Zparsed_selectorr   )r\  r[  rY  rX  rZ  r  rA  r  rf  rv  r  rV  rm  r   rW  r   r_    s4    :Jp
zYoutubeDL.build_format_selectorc                 C   sP  t | jd |d}t| |rN| j|d|d d | j|ddd |dd  | j|d }|r*t }g }|D ]}|	|j
\}}	||j d|	  |jr|d|j  |jr|d	|j  |jr|d
 |jr|d|j  |jr~|d|j  q~d||d< d|krL|d}
|
rL|
|d< |S )Nr   r  r   r  r   Fr"  zDomain=zPath=SecurezExpires=zVersion=z; zX-Forwarded-Forr  )r   r   r   r   rT  rU  r  Zget_cookies_for_urlr   value_encoder?  r>  r   r  r  r  r  r  r  )r   r  r	   r  r   encoderr  r  r  r?  Zx_forwarded_for_ipr   r   r   _calc_headers
  s:    


zYoutubeDL._calc_headersc                 C   s   |  d | j|S )NzN"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version)rV   r  get_cookie_header)r   r   r   r   r   _calc_cookies*
  s    
zYoutubeDL._calc_cookiesc                 C   s   |j dd d d S )Nc                 S   st   |  dd k	r|  dnd|  dd k	r2|  dnd|  dd k	rL|  dnd|  dd k	rf|  dnd|  dfS )Nr   r  r   r   r  r   r   r  )tr   r   r   r  /
  s    z,YoutubeDL._sort_thumbnails.<locals>.<lambda>r  )sort)r   
thumbnailsr   r   r   _sort_thumbnails.
  s    zYoutubeDL._sort_thumbnailsc                    s   | d}|d kr2| d}|r2d|ig |d< }|s:d S  fdd} | t|D ]^\}}| dd krzt||d< | dr| drd	|d |d f |d
< t|d |d< qX j ddkrt||d d d dd|d< n||d< d S )Nr  	thumbnailr   c                 3   s   | D ]}  d|d   z t|d  W nP tk
r } z2  d|d  d|d d| d W Y qW 5 d }~X Y nX |V  qd S )Nz[info] Testing thumbnail r  r   z&[info] Unable to connect to thumbnail z URL r  z. Skipping...)r  urlopenr   r   )r  r  r  r  r   r   check_thumbnails?
  s    &z8YoutubeDL._sanitize_thumbnails.<locals>.check_thumbnailsr  r   r   %dx%dr   r  Tr  r  )r   r  rt  r   rx   r   rF   )r   r  r  r  r  ro  r  r   r  r   r  6
  s$    



 zYoutubeDL._sanitize_thumbnailsc              
      s  |rZ  d } d< |sZ|dkr.| d n
| d  d dd d	 d
   d<   dd k	rxt d  d< dD ]b\}}  |d kr|  |d k	r|tttt	* t
j | t
jj}|d |< W 5 Q R X q|  dst ddd hf d< d}  d}|d krn|D ]0}	  |	dkr8q   |	rH|	} qRq t fdd|D rnd}|r| d< |D ]"}	  |	d kr||	k |	< q|dkrd d< dD ]L}
|r  |
 dd k	r  |
sd|
  |
 d f  |
< q| j D ]\}}| krR| krRd kr| d |d!|d" nH  | }rr|d# |< n(  | }rd#d$d |D  |< qd S )%Nr  Z	fulltitler   z4Extractor gave empty title. Creating a generic titlezDExtractor failed to obtain "title". Creating a generic title insteadr  r"  r  z video #r  r   r#  ))r   r  )r   release_date)Zmodified_timestampZmodified_datez%Y%m%dr   r  c                 S   s   t | d d S )Nr^  )r  r  r   r   r   r  q
  r  z/YoutubeDL._fill_common_fields.<locals>.<lambda>)rH  was_liver  Fc                 3   s   | ]}  |d kV  qdS )FNr  )r   r  r  r   r   r  |
  s     z0YoutubeDL._fill_common_fields.<locals>.<genexpr>Znot_liveZ	post_liveTr  )chapterZseasonZepisodeZ_numberz%s %d_versionzDo not return z when z is presentr\  c                 s   s   | ]}| d dV  qdS )r   u   ，Nr  )r   r  r   r   r   r  
  s     )r   r  r  rF  rc   
contextlibsuppressr  OverflowErrorr"  dtdatetimefromtimestamptimezoneutcstrftimer   r  
capitalize_deprecated_multivalue_fieldsrd  rV   r4  r  )r   r  finalr  Zts_keyZdate_keyr  Z	live_keysr  r  r/  Zold_keyZnew_key	old_value	new_valuer   r  r   r   V
  sZ    
"



("
zYoutubeDL._fill_common_fieldsc                 C   s"   | dd }|r| j|dd d S )Nr  Fr  )rU  r   )r   r  r  r   r   r   r  
  s    zYoutubeDL._raise_pending_errorsc                 C   s,   |  |}|jt| |dpg jd d S )N_format_sort_fieldsr  )rP  r  rC   r   Zcalculate_preference)r   r  r  r   r   r   sort_formats
  s
    
 zYoutubeDL.sort_formatsc           /   
      s   dddkst jd7  _dkr<tdd dn dsVtdd dfd	d
fddfdd}d |  dr dd k	rtd d  dd<  dpddkrdd rd  dpg }|r|d  dr|dddi d dd}tt	|f|||dd  |fdD ]d\}\}}}	| dd kr~| d|d< | ds|	 d|d< | dsRd| d|d< qRdkrd d< d d< 
  d}
 d}|
rt|
d< n|r|d  d! d<  d"d kr@dkr@d d"<  d#D ]v} |}|rN| D ]V\}}|D ]F}| d!rt|d! |d!< | d$d krvt|d!  |d$< qvqjqN d%} d&}d ||d'< }|pi gd d(d }|r |d)< td*d+ |D p6d d,< j d-sXd.d/ |D }|rtd0d+ |D rd, rd1nd2 d3   d4 ptj d5s؈d  d6tj d7 7  <  d4r|rfd8d/|D }r|sjd9d: fd;d<}tt||p2g }|sH |D ]h  d= |  t d!  d!<   d$d krt d!   d$<  d$ d>kr  d?d kr d$  d?<   d@d krt  d@<   dAd kr j d dB dA<   dCd kr(  dDdEkr(dF dC<   dGd krLt  fdHdI dG< dJjdK ksh  dLs  dMs  dNst!  dO d dN< j"t#$ dPdQ dR< qL dRrt%dR dR< dR dSd  dTkrdT= &| d)dU i }t|D ]P\}   d=s8t'| d=< nt()dVdW d=  d=< |* d= g +  qt,t-j.j/0  }| D ]\}}t1|dk}t|D ]\} |r| dX|  d=<  d=  d$ kr d= |krdY2 d=  d=<   dZd krd[j2 d=  t3 d\d]d^ dZ< qqj d_dPkr^t45|d d d  dPd`}|rr|d k	rz|da< 6\}j7j8dbd k	rS 9 6dc\}}j dddek}| oj:dXk}j dfr ; j dgr<d%kr*<d |dh <d |d& j disP|rZ= |rn> S j:}|rt?@djjAjBdk @dljAjB }z|rC|nd }W n> tDk
r }  zjE| dmdmdn W Y qtW 5 d } ~ X Y nX |d k	r(F}Gdo|  C|}H||}!|	r\|!	s\jEdpdmdmdn qt	q\qt|!	sj dq	stdrdPd d dsdp i g}!tIj dtdudI }"|!d  g  }#}$|r|#
r.|"
r.fdvdw}%|%dxt1|! dydzd+ |!D  |"i fk
r.|%dxt1|" d{d|d+ |"D  dm}&t-J|!|"D ]2\ }'K}(|(L   d
pjd d
p|tMd} })}*|)tN|' d|*|* }+|+tMd}k
s|+|)|* d k
rd }+|'
s|)
r|(L|)|' dd |+|' d|' d~d |$+|( zO|( W n tPk
r&   dP}&Y nX Q|( tI|( D ]$\},}- |,|-kr>|(|, q>|&
r> qt
q>dd |$D }.|.RdPdmdhstdP|.krdm|.krS |$d< Td|&rtPL|# S )Nr  r   r   r  z&Missing "id" field in extractor resultr  )ry  zExtractor failed to obtain "id"c              	      s"     d|  d| d| d d S )Nr  z" field is not z - forcing z+ conversion, there is an error in extractor)r  )r/  Z	field_notrY  r  r   r   report_force_conversion
  s    z?YoutubeDL.process_video_result.<locals>.report_force_conversionc                    s<   |  |}|d kst|tr d S  |dd t|| |< d S )Nza stringr  )r   rX  r   )r  Zstring_fieldr/  )r  r   r   sanitize_string_field
  s
    
z=YoutubeDL.process_video_result.<locals>.sanitize_string_fieldc                    sJ   j D ]>}| |}|d kst|ttfr,q |dd t|| |< qd S )Nnumericr  )_NUMERIC_FIELDSr   rX  r  r  rf   )r  Znumeric_fieldr/  )r  r   r   r   sanitize_numeric_fields
  s    

z?YoutubeDL.process_video_result.<locals>.sanitize_numeric_fieldsr  r     r   r   z<"duration" field is negative, there is an error in extractorchaptersr   )r   r   r   r  z<Untitled Chapter r!  r  r(  r  r  r  r   Z
display_id)	subtitlesautomatic_captionsr   r  r  requested_subtitlesZ__sort_fieldsr  c                 s   s$   | ]}| d o|d  dkV  qdS )r   maybeNr  rC  r   r   r   r  
  s    z1YoutubeDL.process_video_result.<locals>.<genexpr>r  r   c                 S   s&   g | ]}| d r|d  dkr|qS )r   r  r  rC  r   r   r   rq  
  s     
  z2YoutubeDL.process_video_result.<locals>.<listcomp>c                 s   s2   | ]*}| d | d  ko$dkn  V  qdS )r   r   rB  Nr  rC  r   r   r   r     s     z This video is DRM protected and r   zFonly images are available for download. Use --list-formats to see themrH  rI  r  z%Y-%m-%d %H:%Mc                    s"   g | ]}t |d  kr|qS )r   )rB  r   rC  )get_from_startr   r   rq  	  s      z--live-from-start is passed, but there are no formats that can be downloaded from the start. If you want to download from the current time, use --no-live-from-startr  c                    s4   |  d}|sd dS t|tr0 | d dS )Nr   zQ"url" field is missing or empty - skipping format, there is an error in extractorFT)r   r  rX  rp  )r  r   )r  r   r   r   is_wellformed  s    


z5YoutubeDL.process_video_result.<locals>.is_wellformedr   )ZaacZopusZmp3ZflacZvorbisr   r   r   r$  r   r   rB  SDRr   c                      s   t  d  d  dS )Nr   r   r  )r  r   )rn  r   r   r  0  r  z0YoutubeDL.process_video_result.<locals>.<lambda>zmanifest-filesize-approxr   r   r   r   r   T)r	   r   r  r  )r  r  z[\s,/+\[\]()]r  r  f{}r   z{id} - {res}{note}r   r  )r  r  rS  r  r  r  r  Zafter_filterr  r  r  r  zautomatic captionsr  z
Enter format selector z,(Press ENTER for default, or Ctrl+C to quit)r  Fr  zDefault format spec: z!Requested format is not availabler  zURequested format is not available. Use --list-formats for a list of available formats)r  r  ry  Zdownload_rangesc                  W   s   i gS r  r   )r  r   r   r   r    r  c               	      s.    d d  dddd | D   d S )N[info] r  r  r  c                 s   s   | ]}d  t|V  qdS )r\  N)r  r   r   r*  r   r   r   r    s     zDYoutubeDL.process_video_result.<locals>.to_screen.<locals>.<genexpr>)r  r  r  r  r   r   r    s    z1YoutubeDL.process_video_result.<locals>.to_screenzDownloading z format(s):c                 s   s   | ]}|d  V  qdS )r   Nr   rC  r   r   r   r    s     z time ranges:c                 s   s(   | ] }|d  dd|d dV  qdS )r   z.1fr  r   Nr   )r   rk  r   r   r   r    s     r  index)r  r  Zsection_titleZsection_numberc                 S   s   h | ]}| d dqS )__write_download_archiveFr  rC  r   r   r   	<setcomp>  s     z1YoutubeDL.process_video_result.<locals>.<setcomp>r  requested_downloadsZafter_video)Ur   r   r4  rB   r  rU  r  insertrt  r  r  rx   r   rd  rW   rA  process_subtitlesrP  r   r   r  r  rB  r  r  nowr  r  r  r:  rX   r  r   r   r  r  r  r   r  r   rl  r  r=  r>  r  r  chainr  r  r  r   rb   rF   rA  r  r  _format_fieldspost_extractr`  r  list_subtitleslist_formatsr  r  r  rH  rI  r_  r3  r   rR  r  rG  r  r  r   r  r  r  process_inforG   r  issubsetr  r  )/r   r  r  r  r  Zdummy_chapteridxprevcurrentZnext_r  r  Zcc_kindccr  subtitleZsubtitle_formatr  r  r  Zfield_preferencer  Zformats_dictro  Zcommon_extsr   Zambiguous_formatsZambigious_idr  Zinteractive_format_selectionr`  Z
req_formatr  Zformats_to_downloadZrequested_rangesZbest_formatZdownloaded_formatsr  Zmax_downloads_reachedr  new_inforB  r   r   r  valZwrite_archiver   )rn  r  r  r  r  r   r   r  
  s   


  





 

  

 


 
 




  




  


& 





zYoutubeDL.process_video_resultc              
      sX  i g  }}|r0| j dr0|| t| }|rb| j drb| D ]\}}||krH|||< qH|r~| j ds| j dsdS t| }| j ddr|}	n| j ddr
zt| j dd|idd	}	W n6 tjk
r }
 zt	d
|
j
 W 5 d}
~
X Y nX nTttd|kr dgng tdd |d|kr>dgng tdd |||dd }	|	r| d| dd|	  | j dd}|r|dng }i }|	D ]}||}|dkr| | d|  q|D ]H  dkr|d } qHtt fdd|}|r|d } qHq|d }| d|||d  |||< q|S )z/Select the requested subtitles and their formatwritesubtitleswriteautomaticsubNZallsubtitlesFZsubtitleslangsr  Tr  zWrong regex for subtitlelangs: enc                 S   s
   |  dS Nr   r$  r  r   r   r   r    r  z-YoutubeDL.process_subtitles.<locals>.<lambda>c                 S   s
   |  dS r  r$  r  r   r   r   r    r  r   r  z: Downloading subtitles: r\  Zsubtitlesformatrn  r5  z subtitles not available for r  c                    s   | d  kS )Nr   r   r  r{  r   r   r    r  zsNo subtitle format found matching "{}" for language {}, using {}. Use --list-subs for a list of available subtitlesr   )r   r   r  r  r  rd  ro   rl  r   r  r  rF   r  r  r:  r  r  r4  r  r  r   )r   r  Znormal_subtitlesr  Zavailable_subsZnormal_sub_langslangZcap_infoZall_sub_langsZrequested_langsrf  Zformats_queryZformats_preferencesubsr  r  r  r   r{  r   r    s    





  
$ 



  zYoutubeDL.process_subtitlesc           	   
   C   s  |d krd S |  }|d| | |dd k	rRddd |d D |d< n"|drt|d |dd	 |d< | ||d
< | ||d< | |d|d|d< | |d|d|d< dd }| jd |g D ]}| 	| 
||| q| jd |g D ]v\}}| j||d}||}| d|d|  | |rt|ddd	d}|| 
||tj  W 5 Q R X q|S )Nr  rw  r   c                 s   s"   | ]}|d  | dd V  qdS )r   r   r   Nr  rC  r   r   r   r  "  s     z(YoutubeDL._forceprint.<locals>.<genexpr>urlsr   r   r   Zformats_tableZthumbnails_tabler  r  Zsubtitles_tabler  Zautomatic_captions_tablec                 S   sv   t d| }|s| S d}| dr2d|  d } }| drN| d d d } }d	t|j|d
rh| gn| dS )Nz+([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?z%({})sr6  r7  z%({})jr"  r  z{0} = %({0})#jr   rY  r   )	rl  r2  r   r   r  r3  r   r  r4  )tmplr  rn  r   r   r   format_tmpl*  s    

z*YoutubeDL._forceprint.<locals>.format_tmplr  r  r  [info] Writing  to: rp  r  r  newline)r  r=  r  r   r  render_formats_tablerender_thumbnails_tablerender_subtitles_tabler   r  r  r  r	  openr  r?  linesep)	r   r  r  r  r  r  Z	file_tmplr  r  r   r   r   _forceprint  s.    
&zYoutubeDL._forceprintc                    s   j ds,j d ds,j d dr6| |rB||d< d|d fdd	}|d	 |d
 |dd |ddd |ddd |d j drƈdd k	rƈtd  |d j drt| d S )NZ	forcejsonr  r   r  r  Fc                    sF   |d kr| }j d|  rB| d k	s4|sB sB|  d S )Nr  )r   r   r  )r/  Zactual_fieldoptionalr  r  r   r   r   print_fieldL  s    z1YoutubeDL.__forced_printings.<locals>.print_fieldr  r  r   r  r  T)r  descriptionZforcedurationr   r   )NF)	r   r   r  r  r  rc   rq  rr  sanitize_info)r   r  r  r  r  r   r  r   Z__forced_printingsC  s*    

zYoutubeDL.__forced_printingsc              
   C   s   | ds| |d |rR| j d}| j dp6| }d|||dddddd	}n| j}t|||dkd| |}|s| jD ]}	||	 qzd	d
d | dg p|gD }
| d|j d|
 d | 	|}| dd kr| 
||d< ||||S )Nr   Tr  r   F)	r9  r   r  r  ZnopartZskip_unavailable_fragmentsZkeep_fragmentsr  Z_no_ytdl_filer  r  r  c                 s   s:   | ]2}|d   dr*|d  dd d n|d  V  qdS )r   zdata:r   r   z,<data>Nr8  rC  r   r   r   r  x  s   zYoutubeDL.dl.<locals>.<genexpr>rw  z	Invoking z downloader on "r  r   )r   r  r   r   r0  rb  r  r  FD_NAMEr   r  r  )r   r   r  r  r9  r  r   r   fdrj  r  r  r   r   r   r>  `  s8    



zYoutubeDL.dldefault_overwritec                C   sR   t ttjjt|}|r0| jd|s0|d S |D ]}| | t	| q4d S )Nr  r   )
r  r:  r?  r  r<  rn   r   r   r  r=  )r   	filepathsr  Zexisting_filesfiler   r   r   existing_file  s    
zYoutubeDL.existing_filec           "   
      s	   dddkst}dkr4dkr4d d< dk	rNdd< dS  fdd	}d\}}||  jd
7  _jdd d< }d}i }j|dkd fdd}	j drj dd< |	  dS |dkrdS 	t
|sdS 	t
|s,dS dddkrLdS |}
|
dkrfdS |t|
 d|d}|dkrdS |t| d}d|}|r|d< |d< n|dkrdS d}j ddrd}|r	t
|s"dS j ddsPtjt
|rPd n dshd nz>d |  tt
|d!d"d#}|d  W 5 Q R X W nH ttfk
r   d Y n& tk
r   d$|  Y dS X fd%d& j d'j d(j d)d*}j d+r^tjd,kr@d-ntjd.rRd/nd0}d||< t fd1d2|  D r~dS d3|\}}|| j d4r|d5< tj!tj"t
|d6< |d7< |#t$d j dd< n%d8g  zfd9d:}d;\} d<s: d0rt&j|d=kd>t'krd?jd@ kr dAs dBrt'( rdCndD}| dE W dS  dFdk	rd j dGdkrd dHkr dIrtdJd2 j)dK D rdLd< dM d ffdNdO	}||}||}|||}ddP< t*t+tdF dF< t,}g }|dk	r-| n؈r t'krdF ng D ]<}t.||d dQ/|dR d  |d5< }|0| qdS1dTd2 dF D d0< 2|\}}|dP< nFj dUr:dV n@|j(szdW}j dXsj| dY W dS | dZ |d=krt'3jrd[n|j(rd\nd]}d^| d_ |}dF D ]}t}|dF= || |d=kr6t.|||d dQ/|dR |d }	|s$ W dS ||d5< |0| 2||\}}dP pR|dP< |o`|}q|r|j(rj dUsd8 0| |d`< ddP< n|D ]}d||< qnB|||}|dks||kr2|\}}|dP< n
-| |p|}tj!tj"t
|d6< W n t4k
r\ } zda|  W Y dS d}~X Y np tk
r } zt5|W 5 d}~X Y nF t6k
r } z&db|j7 dc|j8 dd W Y dS d}~X Y nX 9 |	r|d=k	rfdedf} |   z|:|| W n: t;k
	rL } zdg|  W Y dS d}~X Y nX zj<D ]}!|!d5  	qVW n: t=k
	r } zdh|  W Y dS d}~X Y nX dd< |k	stj d	rdd< |	  dS )iz;Process a single resolved IE result. (Modifies it in-place)r  r   r   r   Nr  r  c                    s"   |  krd S      |  d S r  )r  r  )r  r  r   r   replace_info_dict  s    z1YoutubeDL.process_info.<locals>.replace_info_dictr   T)r  	_filenamer  r  c                      s"    j t jdpdkrtd S )Nmax_downloadsr  )r3  r  r   r   rG   r   r  r   r   check_max_downloads  s    z3YoutubeDL.process_info.<locals>.check_max_downloadsr  r  r  r  Zinfojsoninfojson_filenameZ__infojson_filenameZwriteannotationsF
annotationr  z,[info] Video annotations are already presentannotationsz"There are no annotations to write.z%[info] Writing video annotations to: wr  r  zCannot write annotations file: c              	      s@  t  d t}|s,d d  d dS t d|  d}t|sXdS jddrt	j
t|rd	|  d
 dS zd|  d|  ttt|dd| dkrdnddB}d|i}| dkr|d t| d   |d< |t|  |  W 5 Q R X W n( tk
r:   d|  Y dS X dS )Nr  z?Cannot write internet shortcut file because the actual URL of "z" is unknownTlinkr   Fr  z[info] Internet shortcut (.z) is already presentz#[info] Writing internet shortcut (.z) to: r%  r  r   z
r   r	  desktopr   r  zCannot write internet shortcut )r   rg   r  ru   r  r   r	  rZ   r   r?  r  r<  r  r  r   r  r  r4   r"  r   )	link_typer   ZlinkfnZlinkfileZtemplate_varsr  r   r   _write_link_file  s4     z0YoutubeDL.process_info.<locals>._write_link_fileZwriteurllinkZwritewebloclinkZwritedesktoplink)r   weblocr'  Z	writelinkdarwinr*  linuxr'  r   c                 3   s    | ]\}}|o | V  qd S r  r   )r   r(  Zshould_write)r)  r   r   r    s   z)YoutubeDL.process_info.<locals>.<genexpr>Z	before_dlZskip_downloadfilepathZ
__finaldir__files_to_mover  c                     s\    d  fdd}jtjtt|| |  dd}|rXtj|d dd  d< |S )Nr   c                    s   t | jdp  S )Nr  )ru   r   r   )r  )r   r   r   r   r  )  r  zEYoutubeDL.process_info.<locals>.existing_video_file.<locals>.<lambda>Fr  r   )	r   r  r  r  r  r3  r?  r  splitext)r  Z	convertedr  r  r{  r   existing_video_file'  s    
z3YoutubeDL.process_info.<locals>.existing_video_filer  r   r  r  zno-direct-merger   r  r  z*This format cannot be partially downloadedzOYou have requested downloading the video partially, but ffmpeg is not installedz
. Abortingrw  r|  r}  r  c                 s   s   | ]}t |tkV  qd S r  )rw  r    r   r  r   r   r   r  A  s     r  r~  z<webm doesn't support embedding a thumbnail, mkv will be usedc                    sR   | dkr| S t j| d dd  }| fkr@t j| d n| }| d| S )Nr  r   r   r7  )r?  r  r/  )r  r   Zfilename_real_extZfilename_wo_ext)new_extold_extr   r   correct_extG  s    
z+YoutubeDL.process_info.<locals>.correct_ext__real_downloadr  r   r   c                 s   s   | ]}|d  V  qdS )r   Nr   rC  r   r   r   r  d  s     r   zYou have requested merging of multiple formats while also allowing unplayable formats to be downloaded. The formats won't be merged to prevent data corruption.zJYou have requested merging of multiple formats but ffmpeg is not installedr  z". Aborting due to --abort-on-errorz. The formats won't be mergedz$using a downloader other than ffmpegz:but the formats are incompatible for simultaneous downloadzbut ffmpeg is not installedz:You have requested downloading multiple formats to stdout z2. The formats will be streamed one after the otherZ__files_to_mergezunable to download video data: zcontent too short (expected z bytes and served r0  c                     s  d j d} d | dkr$d S | dkr2d n"| dkrT| dksFtdsTd	  fd
d}d}||dkd| t dkrtj nd }|r|jnd }ddptfddjd D }|sr|tkodkoddkdt	 ||dkr(j d pBdoBj dd kdt
 ||dkojdpjddt ||d kd!t ||d kd"t d S )#NTfixupr  )r  r   r  r  )Zdetect_or_warnNr5  Fc                    sd    r| sd S  dkr,  d|  d S |}|jrJd | n  d| d d S )Nr  r  r  z*. Install ffmpeg to fix this automatically)r  rJ  r>  )Zcndnrg  r  r  )do_fixupr  r   vidr   r   ffmpeg_fixup  s    z;YoutubeDL.process_info.<locals>.fixup.<locals>.ffmpeg_fixupr   )r   NzNon-uniform pixel ratio r   r   rw  c                 3   s0   | ](}t |to&t |jd   dfkV  qdS )r   N)rX  r)   resolve_recode_mappingmappingr1  r{  r   r   r    s   
z8YoutubeDL.process_info.<locals>.fixup.<locals>.<genexpr>r  Zm4ar   Zm4a_dashz:writing DASH m4a. Only some players support this containerZ	hlsnativeZhls_use_mpegtsrH  z=Possible MPEG-TS in MP4 container or malformed AAC timestampsZdashsegmentsr   zPossible duplicate MOOV atomsZweb_socket_fragmentzMalformed timestamps detectedzMalformed duration detected)r   r   r   r%   r   r  r   r-  r
   r$   r#   r!   r&   r"   )Zfixup_policyr9  r   
downloaderZpostprocessed_by_ffmpeg)r  r  r   )r7  r   r8  r   r6    sR    


 z%YoutubeDL.process_info.<locals>.fixupzPostprocessing: zpost hooks: )>r   r   r  r  r  r3  r  r  r   r	  rZ   r  _write_subtitlesr  rY  r  r  r?  r  r<  r  r  r  r  KeyErrorr=  r"  r   r   r[  r   r   rd  dirnameabspathrun_ppr*   r=  r   r
   rJ  r-  r  r3  r'   r  rr   r   r>  r  r>  Zcan_merge_formatsr   rP   r<   r  
downloadedr  r  rL   r/  r<  )"r   r  Zoriginal_infodictr  r  r  Zfull_filenameZtemp_filenamefiles_to_mover!  Z	sub_filesZthumb_filesinfofnr  ZannofnZannofileZwrite_linksr(  r0  r@  rg  r4  Zdl_filenamerL  rB  r  fnameZreal_downloadr  Zpartial_successr  r  r6  rj  r   )r)  r  r  r2  r3  r   r   r    s   



   



"



	

 



 





 
8
zYoutubeDL.process_infoc                    s   t   fdd}|S )Nc               
      s   z | |}W n t k
r$    Y n tk
rN } z| W 5 d }~X Y nt tk
r } z(d|  jds| d_W 5 d }~X Y n0X jddr| 	t
| d S )Nr  Zbreak_per_urlr   Zdump_single_jsonF)r   rP   r   r>   r  r   r   r3  r  r  rq  rr  r  )r   r   r  rf  r   r   r   r   r     s    
z-YoutubeDL.__download_wrapper.<locals>.wrapperr   )r   r   r   r   rF  r   Z__download_wrapper  s    zYoutubeDL.__download_wrapperc                 C   sx   t |}| jd d }t|dkrJ|dkrJd|krJ| jddkrJt||D ]"}| | j|| jddd	 qN| jS )
zDownload a given list of URLs.r  r~  r   r  r  r   r  F)r  )r   r   r  r   rO   _YoutubeDL__download_wrapperr  r2  )r   Zurl_listr  r   r   r   r   r    s     
 zYoutubeDL.downloadc                    s  t tj|gdtdd(} fddttd|D }W 5 Q R X |D ]}z 	 j
|dd W qP tttfk
r } zNt|ts d	 |d
}|d kr  d| d|   |g W 5 d }~X Y qP tk
r
 } z | W 5 d }~X Y qPX qP jS )Nr  r  )modeZopenhookc              	      s"   g | ]}  | jd dqS )clean_infojsonT)r  r   r   )r   r  r  r   r   rq  "  s   z5YoutubeDL.download_with_info_file.<locals>.<listcomp>r   Tr  r  r  zThe info failed to download: z; trying with URL )r  closing	fileinputZ	FileInputZhook_encodedr   rq  loadsr  rG  r  r?   r@   rM   rX  r  r   r  r  rB   r   r2  )r   Zinfo_filenamer  Zinfosr  rf  r  r   r  r   download_with_info_file  s.     



z!YoutubeDL.download_with_info_filec                    sp   | dkr| S |  dtt  |  dd |  dtt ttd |rRdd nd	d  fd
d  | S )z. Sanitize the infodict for converting to json Nr!  r  r   r  )r  r0   Zrelease_git_head
repositoryc                 S   s   |d kp|  dp| dkS )N__>   r-  r  r  r  r  r  r  r  r)  rw  r"  r$  r  r   r   r   r  B  r  z)YoutubeDL.sanitize_info.<locals>.<lambda>c                 S   s   dS )NFr   r  r   r   r   r  H  r  c                    sl   t | tr" fdd|  D S t | ttttfrBtt | S | d ks\t | tt	t
tfr`| S t| S d S )Nc                    s$   i | ]\}}||s| |qS r   r   r  	filter_fnrejectr   r   r   L  s     
  z>YoutubeDL.sanitize_info.<locals>.filter_fn.<locals>.<dictcomp>)rX  rY  rd  r  r  r  rF   r3  r   r  r  rB  rJ  rK  rP  r   r   rQ  J  s    
z*YoutubeDL.sanitize_info.<locals>.filter_fn)r=  r  r~  r   r0   r   r   )r  Zremove_private_keysr   rP  r   r  3  s    

zYoutubeDL.sanitize_infoc                 C   s   t | |S )z3 Alias of sanitize_info for backward compatibility )r   r  )r  Zactually_filterr   r   r   filter_requested_infoV  s    zYoutubeDL.filter_requested_infor  rg  c             	   G   sx   t td |D ]d}|r$| ||  zt| W n$ tk
rV   | d|  Y nX ||dg kr|d |= qd S )NzUnable to delete file r.  )r  r:  r  r?  r=  r"  r  r   )r   r  rg  files_to_deleter  r   r   r   _delete_downloaded_files[  s    z"YoutubeDL._delete_downloaded_filesc                    s    fdd  | pi  d S )Nc                    sP   |  ddkr0|  di D ]} |p&i  qd S | dd p>t}| |  d S )Nr  r  r  Z__post_extractor)r   rU  rY  r  )r  Z
video_dictZpost_extractoractual_post_extractr   r   rX  h  s    z3YoutubeDL.post_extract.<locals>.actual_post_extractr   r  r   rW  r   r  f  s    	zYoutubeDL.post_extractc              
   C   s   g }d|kri |d< z| |\}}W nJ tk
rp } z,| jddkr^| | | W Y S  W 5 d }~X Y nX |sz|S | jddr|D ]}|d |d qn| j||dd |S )	Nr.  r  TZ	keepvideoFr   z+Deleting original file %s (pass -k to keep)rT  )runrL   r   r   r   r=  rV  )r   r  ZinfodictrU  rf  r  r   r   r   rA  s  s*    
  zYoutubeDL.run_ppadditional_ppsc                C   s<   |dkr|  || |pg | j|  D ]}| ||}q&|S )Nr   )r  r-  rA  )r   r  r  r[  r  r   r   r   r    s
    zYoutubeDL.run_all_ppsr  c              
   C   s|   t |}|pi |d< z| ||}W nF tk
rj } z(d| }|d| | j|dd W 5 d }~X Y nX ||dd fS )Nr.  zPreprocessing: r  F)r  )rY  r  rL   r=  r   rU  )r   Zie_infor  rC  r  r  rg  r   r   r   r    s    
 zYoutubeDL.pre_processc                 C   sL   ||d< |pi |d< | j d||dd}| t| |}|d= |  d|S )z-Run all the postprocessors on the given file.r-  r.  r  r  rZ  Z
after_move)r  r   rA  r*   )r   r  r  rC  r   r   r   r    s    zYoutubeDL.post_processc                 C   sx   | d}|sd S | dp$| d}|d krnt| d}|sDd S | j D ]\}}||rN|} qnqNd S t||S )Nr  r  rv  r   )r   rz   r+  rd  r  rk   )r   r  r  r  r   rv  ry  r   r   r   _make_archive_id  s    

zYoutubeDL._make_archive_idc                    s@    j s
dS  |g}||dp&g  t fdd|D S )NFZ_old_archive_idsc                 3   s   | ]}| j kV  qd S r  )r&  )r   Zid_r  r   r   r    s     z0YoutubeDL.in_download_archive.<locals>.<genexpr>)r&  r\  r  r   r   )r   r  Zvid_idsr   r  r   r    s
    zYoutubeDL.in_download_archivec              	   C   sz   | j d}|d krd S | |}|s*t| d|  t|rjt|ddd}||d  W 5 Q R X | j	| d S )Nr*  zAdding to archive: rp  r  r  r   )
r   r   r\  r   r  rh   rj   r  r&  r   )r   r  r%  Zvid_idr'  r   r   r   r    s    
z!YoutubeDL.record_download_archiveunknownc                 C   s   |  ddkr |  ddkr dS |  dd k	r6| d S |  dr^|  dr^d| d | d f S |  drvd	| d S |  drd
| d  S |S )Nr   rB  r   
audio onlyr   r   r   r  z{}pz%dx?)r   r   )r   r~  r   r   r   r    s    

zYoutubeDL.format_resolutionc                    s(    j dddk	r$ fdd|D S |S )Nr
  TFc                    s   g | ]}  | jjqS r   )r  rH  r  )r   headerr  r   r   rq    s     z2YoutubeDL._list_format_headers.<locals>.<listcomp>)r   r   )r   headersr   r  r   _list_format_headers  s    zYoutubeDL._list_format_headersc                 C   s  d}| ddkr|d7 }| drB|r0|d7 }|d|d 7 }| dd k	rh|r\|d7 }||d 7 }| d	d k	r|r|d
7 }|d|d	  7 }| dd k	r|r|d
7 }|d|d 7 }| dd k	r| ddkr|r|d
7 }||d 7 }| dd k	r8|d7 }n(| dd k	r8| dd k	r8|d7 }| dd k	rX|d|d  7 }| dd k	r|rv|d
7 }|d|d 7 }| dd k	r|r|d
7 }|d dkr|d7 }n|d|d  7 }n&| dd k	r|r|d
7 }|d7 }| dd k	r|d|d  7 }| dd k	r6|d|d  7 }| dd k	rf|rT|d
7 }|t|d 7 }n2| dd k	r|r|d
7 }|dt|d  7 }|S ) Nr   r   Zf4fZf4mz(unsupported)r   r  z[{}]r   r   r\  z%4dkr   z{} containerr   rB  r   @r   zvideo@r   z{}fpsr   
video onlyz%-5sr   z@%3dkr   z (%5dHz)r   r   ~)r   r   r`   )r   Zfdictr  r   r   r   _format_note  st    

 
zYoutubeDL._format_notec                 C   s:   | dd kr2| dr.| dddkr.|gS g S |d S )Nr  r   r  r   r  r   r  r   r   r   rP    s
    zYoutubeDL._get_formatsc                    s    }|sd S jdddkrLfdd|D }tdddd	g|d
dS fddjdjjddd  fdd|D }dddddd ddd dddddd }t||djd!jjd"ddd#S )$Nr
  TFc                    sB   g | ]:}| d pddkrt|dt|d | |gqS )r   r   r   r   )r   rb   r  rf  rC  r  r   r   rq  )  s    z2YoutubeDL.render_formats_table.<locals>.<listcomp>zformat coder   r   rS  r   )Z	extra_gapc                    s   |dkst | |}|sdS |dkr>d|dd d S |dkrX| ddkrXdS |dkrr| ddkrrd	S  |dkrd
nd jjS )N)r   r   r]  rB  r7  r^  r   r   imagesr   r^  rd  )r   r   r  r4  r  rH  r  )r  r/  rx  r  r   r   simplified_codec2  s    
z8YoutubeDL.render_formats_table.<locals>.simplified_codecu   │r1  r  c                    s  g | ]}| d dks$|d  dkrt|djjt|dt|jddt|ddtd	t|d
dddddt|dd t|ddtd	pt|ddtd	ptt	| d dddjj
td	t|ddtd	t| dd |dt|ddtd	|dt|ddtd	t|ddtd	tt|d d!t| dd"krPd#jjnd| d$d%krrd&jjn| d$rd'jjndt|d(t|d)d| dfdd*d+d,d+gqS )-r   Nrh  r   r   )r^  ri  )r   r  r   z	%dr   r   r  )Nr  )r  HDRr   r   z	%sr   z 	%sr   u   ≈	%sr   r   z~	%sz	%dkr   r   r   r   r   r   r   z[%s]rb  ZUNSUPPORTEDr   r  z	Maybe DRMZDRMr   r   r\  rv  r  )r   r  rb   rH  r  r  r  rF  r`   r   r  r   ra   ri   r  r  rC  rv  r  r   rj  r   r   rq  B  sH     
 " r  ZEXTZ
RESOLUTIONz	FPSrk  ZCHz		FILESIZEz	TBRPROTOZVCODECz	VBRZACODECz	ABRz	ASRz	MORE INFOu   ─r  )
hide_emptyrv  )rP  r   r   rt   r  rH  r  ra  )r   r  r  tableZheader_liner   rm  r   r  $  sL    

                 zYoutubeDL.render_formats_tablec                 C   s:   t |dpg }|sd S t| dddddd |D S )Nr  r  ZWidthZHeightURLc                 S   s6   g | ].}| d | dpd| dp(d|d gqS )r  r   r]  r   r   r  )r   r  r   r   r   rq  m  s     z5YoutubeDL.render_thumbnails_table.<locals>.<listcomp>)r  r   rt   ra  )r   r  r  r   r   r   r  g  s    z!YoutubeDL.render_thumbnails_tablec                    s:   dd  |sd S t | ddd fdd| D dd	S )
Nc                 S   s\   t dd t|D  \}}tt|dkrF|d dkr:g n
|d d }| d|d|gS )Nc                 s   s$   | ]}|d  | dpdfV  qdS )r   r   r]  Nr  rC  r   r   r   r  q  s     zAYoutubeDL.render_subtitles_table.<locals>._row.<locals>.<genexpr>r   r   r]  r\  )r  reversedr  r  r  )r  r  extsnamesr   r   r   _rowp  s    z.YoutubeDL.render_subtitles_table.<locals>._rowZLanguageNameZFormatsc                    s   g | ]\}} ||qS r   r   )r   r  r  ru  r   r   rq  z  s     z4YoutubeDL.render_subtitles_table.<locals>.<listcomp>T)ro  )rt   ra  rd  )r   r  r  r   rw  r   r  o  s    z YoutubeDL.render_subtitles_tablec                 G   sJ   || }|s$|  | d|  d S |  d| d| d | | d S )Nz has no z[info] Available z for r"  )r  r  )r   r  r   r   r   rp  r   r   r   Z__list_table}  s    zYoutubeDL.__list_tablec                 C   s   |  |d d| j| d S )Nr  r  )_YoutubeDL__list_tabler  rg  r   r   r   r    s    zYoutubeDL.list_formatsc                 C   s   |  |d d| j| d S )Nr  r  )rx  r  rg  r   r   r   r    s    zYoutubeDL.list_thumbnailsr  c                 C   s   |  ||| j|| d S r  )rx  r  )r   r  r  r   r   r   r   r    s    zYoutubeDL.list_subtitlesc              
      s  j dsd S ddlm} ddlm} ddlm}m} dd  dt	
 t  d	 fd
djjD }j drfdd}|| n td| dd d fdd}t }tdkr|d7 }t}|ttdd  dtttdd ptttr"dtd d  dnd|dkr2dn
d| d|rFdn |tkrTd nd!j d"|j  d#d$ |s|d%j   |st!j"d&r|d' n|d( j d) r|d*d	j d)  t# r|d+t#   |t$  t%&\}	}
d,d- |
' D }
|
r:|	d.  d/d0t(|
7  < t) |	d1< t*+ |	d2< d	d3d t(|	' D ppd4}|d5|  dd6l,m- dd7l.m/} |d8d	t(fd9d-|0 D pd4  |d:j1  |d;d	d<d j2j30 D   t!j"d=r|d> d S |t4d?' D ]d\}}d@dA |' D }|dBkr`|5dCd |' D  |sjq$|| dDd	t(|  q$t6 }|r|dE|  d S )FNr  r   )_IN_CLI)_LAZY_LOADER)r   _PLUGIN_OVERRIDESc                 S   s   t t| ddt| j d}g }tjdd dkrB|d t	| slddl
m} ||d	krfd
nd |r| dd| d}|S )Nr  z	missing (r0  r   r   r   r   )WINDOWS_VT_MODEFzNo VTzNo ANSI (r   )r   r  rw  rQ  r?  environr   rA  r>  r}   utilsr|  r  )r   r  Zadditional_infor|  r   r   r   get_encoding  s    
z2YoutubeDL.print_debug_header.<locals>.get_encodingz(Encodings: locale {}, fs {}, pref {}, {}r\  c                 3   s4   | ],\}}|d k	r|dkr| d | V  qd S )Nr   r  r   )r   r  r   )r  r   r   r    s    z/YoutubeDL.print_debug_header.<locals>.<genexpr>r  c                    s     d|  S )Nr  )r  r  )r  r   r   r    r  z.YoutubeDL.print_debug_header.<locals>.<lambda>r  r   r  c                    s     d|  dS )Nr  r   )r  r  r  r   r   r    r  )Npipr,  r5  r  z versionrc  r*  	   r_  r   r]  rg  r0  ZAPIzAPI:r7  r  rl  zparams: ZYTDLP_NO_LAZY_EXTRACTORSz,Lazy loading extractors is forcibly disabledz#Lazy loading extractors is disabledr   zCompatibility options: {}z
Git HEAD: c                 S   s   h | ]\}}|r|qS r   r   )r   r  r  r   r   r   r    s      z/YoutubeDL.print_debug_header.<locals>.<setcomp>Zffmpegz ({})r   ZrtmpdumpZ	phantomjsc                 s   s$   | ]\}}|r| d | V  qdS )r  Nr   )r   Zexer  r   r   r   r    s     rB  zexe versions: get_package_info)available_dependencieszOptional libraries: %sc                    s   h | ]}t  | qS r   )ri   r  r  r   r   r    s    zProxy map: zRequest Handlers: c                 s   s   | ]}|j V  qd S r  )RH_NAMEr   rhr   r   r   r    s     ZYTDLP_NO_PLUGINSzPlugins are forcibly disabled)	ExtractorzPost-Processorc                 S   s2   g | ]*\}}d  |j|j|kr"dnd| qS )r  r   z as )r   rQ  )r   r   klassr   r   r   rq    s
    z0YoutubeDL.print_debug_header.<locals>.<listcomp>r  c                 s   s4   | ],\}}|d  j dd  d|j dV  qdS )r  r+  r  r}  r0  N)r{  	partitionrQ  )r   parentpluginsr   r   r   r    s   z
 Plugins: zPlugin directories: )7r   r   r   ry  Zextractor.extractorsrz  r   r{  r   localegetpreferredencodingr   r\  r  r  r;  rC  r   r1   r   rw  ri   r-   
rpartitionr/   r   r   r  r   r   r   rR  rS  r?  r~  r0   r~   r(   Zget_versions_and_featuresrd  sortedr   r   r  Zcompat.compat_utilsr  Zdependenciesr  r  proxiesr  handlers
plugin_ppsr  plugin_directories)r   ry  rz  Z
plugin_iesZplugin_ie_overridesZencoding_strr  sourcer  Zexe_versionsZffmpeg_featuresZexe_strr  Zplugin_typer  Zdisplay_listZplugin_dirsr   )r  r  r  r   r   rV    s    	
*

 



&

 zYoutubeDL.print_debug_headerc                 C   sT   | j d}|dk	r*|dkr d}d|i}n&tj }d|krPd|krP|d |d< |S )zGlobal proxy configurationproxyNr   Z__noproxy__r  r  r  )r   r   r   request
getproxies)r   Z
opts_proxyr  r   r   r   r    s    

zYoutubeDL.proxiesc                 C   sr   zt | jd| jd| W S  tk
rl } z0|j}| jt|dt	d||j
d  W 5 d}~X Y nX dS )zGlobal cookiejar instancer  Zcookiesfrombrowserr   Nr  )r	   r   r   r   __context__r   r   r  r  r  __traceback__)r   r   causer   r   r   r    s    
 
 $zYoutubeDL.cookiejarc                 C   s(   |  d | jjd }|j| j| jdS )zS
        Get a urllib OpenerDirector from the Urllib handler (deprecated).
        z8YoutubeDL._opener is deprecated, use YoutubeDL.urlopen()Urllib)r  r  )rV   r  r  Z_get_instancer  r  )r   handlerr   r   r   _opener  s    
zYoutubeDL._openerc                 C   s   dd | j j D S )Nc                 S   s,   g | ]$}t |tr|jD ]}||jfqqS r   )rX  r   Zsupported_targetsr  )r   r  targetr   r   r   rq  "  s
   
 z@YoutubeDL._get_available_impersonate_targets.<locals>.<listcomp>)r  r  r  r  r   r   r   "_get_available_impersonate_targets   s    
z,YoutubeDL._get_available_impersonate_targetsc                    s   t  fdd| jj D S )Nc                 3   s"   | ]}t |tr| V  qd S r  )rX  r   Zis_supported_targetr  r  r   r   r  +  s   
z:YoutubeDL._impersonate_target_available.<locals>.<genexpr>)r   r  r  r  )r   r  r   r  r   rW  )  s    
z'YoutubeDL._impersonate_target_availablec              
   C   s  t |trt|}n t |tjjr4| d t|}t |tsBtt|j	\}}|r^||j
d< t||_	t|j|j
d t|j
 z| j|W S  tk
r } z|jD ]}|jr|jsq|jjdkrd|j krtd|d|d|j krd	| jjkrd
| jjkrtdqtd|j rLd| jjkrLtd|d|qtd|j rtd|jd  dq W 5 d}~X Y n` tk
r } z@dt|krtd|d|ndt|krtd|d| W 5 d}~X Y nX dS )z Start an HTTP download z{Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. Use yt_dlp.networking.common.Request instead.Authorization)r  r`  r  zunsupported url scheme: "file"zwfile:// URLs are disabled by default in yt-dlp for security reasons. Use --enable-file-urls to enable at your own risk.)r  zunsupported proxy type: "https"requestsZ	curl_cffiztTo use an HTTPS proxy for this request, one of the following dependencies needs to be installed: requests, curl_cffizunsupported url scheme: "wss?"Z
websocketszkThis request requires WebSocket support. Ensure one of the following dependencies are installed: websocketsz:unsupported (?:extensions: impersonate|impersonate target)r	  r  z" is not available. See --list-impersonate-targets for available targets. This request requires browser impersonation, however you may be missing dependencies required to support this target.NZ$UNSAFE_LEGACY_RENEGOTIATION_DISABLEDzGUNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connectZSSLV3_ALERT_HANDSHAKE_FAILUREztSSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. Try using --legacy-server-connect)rX  r   r   r   r  rV   r   r   r]   r   r`  rx   r   r  r   r  sendr   Zunsupported_errorsr  rg  RH_KEYrA  r   r  rl  rm  
extensionsr   )r   reqr   Zbasic_auth_headerrf  Zuer   r   r   r  0  s|    








zYoutubeDL.urlopenc                 C   s   t | }| jd  }| j }t| t|| t|| jdd}|D ]\}||f ||| j	|d| jd k| jd dt
| jddd	d
ddddddd qJ|j|pg  d| jd kr|jdd  |S )Nr   Zdebug_printtraffic)r  r  z
no-certifir   Znocheckcertificate)r  r`  r  r  Zprefer_system_certsverifysource_addresssocket_timeoutZlegacyserverconnectenable_file_urlsr  client_certificateclient_certificate_keyclient_certificate_password)r  r  r  )r  r  timeoutZlegacy_ssl_supportr  r  client_certzprefer-legacy-http-handlerc                 S   s   | j dkrdS dS )Nr  i  r   )r  )r  r  r   r   r   r    r  z2YoutubeDL.build_request_director.<locals>.<lambda>)r   r   r  r  r   r   r   r   add_handlerr  r   r  r  r   )r   r  r  r  r`  r  Zdirectorr  r   r   r   build_request_directorp  s@    


z YoutubeDL.build_request_directorc                 C   s   |  t tS r  )r  r   r  r   r  r   r   r   r    s    zYoutubeDL._request_directorc              
   C   sT   t |tr|S z||  W S  tk
rN } z|jd |_ W 5 d }~X Y nX d S )NzH. Check your system encoding configuration or use the --encoding option.)rX  rp  r  r  r  r  )r   r  r  r   r   r   r    s    
zYoutubeDL.encodec                 C   s   | j d}|d krt }|S )Nr  )r   r   rq   )r   r  r   r   r   r    s    zYoutubeDL.get_encodingc              	   C   s   |dkr| j dd}| j ds&dS |s@| d| d dS | |sNdS |sxtj|rx| d|  d	 d
S | d| d|  z"t	| 
|| j dd| W dS  tk
r   | d| d|  Y dS X dS )zb Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error Nr  TZwriteinfojsonFSkipping writing z	 infojsonr  z metadata is already presentr<  r  z metadata as JSON to: rI  Cannot write z metadata to JSON file )r   r   r  r	  r?  r  r<  r  r  r   r  r"  r   )r   labelr  rD  r  r   r   r   r    s&    
zYoutubeDL._write_info_jsonc              	   C   s  | j dsdS |s*| d| d dS | |s8dS | j ddsjtj|rj| d|  d	 n|d
dkr| d| d dS zF| d| d|  t	t
|ddd}||d
  W 5 Q R X W n. tk
r   | d| d|  Y dS X dS )zJ Write description and returns True = written, False = skip, None = error ZwritedescriptionFr  z descriptionNr  Tr  z description is already presentr  z[info] There's no z description to writer  z description to: r%  r  r  r  z description file )r   r   r  r	  r?  r  r<  r  r  r  rZ   r  r"  r   )r   r  r  ZdescfnZdescfiler   r   r   r    s(    
zYoutubeDL._write_descriptionc                 C   s:  g }| d}| j ds*| j ds*|S |s<| d |S | |d}|sZ| d |S | D ]\}}|d }t|||| d}	t|||| d}
| |
|	f}|r| d| d	| d
 ||d< |||
f qb| d|	  | ddk	rrzHt|	dddd}|	|d  W 5 Q R X |	|d< ||	|
f W qbW n* t
k
rp   | d|	  Y  dS X zD| }|d| d | j|	|dd |	|d< ||	|
f W qb ttt
tftk
r2 } zPd|d| }| j ddk	r| j ds| | t|| | W 5 d}~X Y qbX qb|S )z` Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if errorr  r  r  z9[info] There are no subtitles for the requested languagesr  z'[info] Skipping writing video subtitlesr   z[info] Video subtitle r7  z is already presentr-  z#[info] Writing video subtitles to: r  Nr%  r  r   r	  z"Cannot write video subtitles file r   T)r  z'Unable to download video subtitles for r  r  )r   r   r  r  rd  r|   r  r>  r  r  r"  r   r  r=  r>  r?   rB   r  r   r  )r   r  r  r  r  Zsub_filename_baseZsub_langZsub_infoZ
sub_formatZsub_filenameZsub_filename_finalZexisting_subZsubfileZsub_copyr  rg  r   r   r   r=    s\    




zYoutubeDL._write_subtitlesc                 C   sx  | j dd}g g  }}|s*| j ddrR|dp6g }|sR| d| d |S |o`t|dk}|dkrn|}|r|s| d	| d
 |S |r| |sdS tt|ddd D ]\}	}
|r|
d  dndt|
d d }| d|
d  }t	|||d}t	|||d}| 
||f}|rh| d|r>|n| d
  ||
d< |||f n| d| d zt| t|
d |
di d}| d| d|  tt|d}t|| W 5 Q R X |||f ||
d< W nt tk
rb } zTt|tr2|jdkr2| d|  d n| d| d |  ||	 W 5 d}~X Y nX |r|s qtq|S )!zf Write thumbnails to file and return list of (thumb_filename, final_thumb_filename); or None if error Zwrite_all_thumbnailsFZwritethumbnailr  z[info] There are no z thumbnails to downloadr   Nr  z
 thumbnailr  r  r7  r   r   Zjpgz thumbnail r   z[info] {} is already presentr-  z[info] Downloading z ...r   )r`  r  r  wbi  r  z does not existzUnable to download r  )r   r   r  r  r  r	  r  rt  rW   ru   r  r   r  r>  r  r   r  rZ   rM  copyfileobjr   rX  r   statusr  r  rU  )r   r  r  r  Zthumb_filename_baseZ	write_allr  r  multipler  r  Z	thumb_extZthumb_display_idZthumb_filenameZthumb_filename_finalZexisting_thumbZufZthumbfr  r   r   r   r    sV    
 $
zYoutubeDL._write_thumbnails)NT)r  )NF)FN)FNF)F)NNT)N)F)F)F)r   N)F)r   )FF)TNNTF)N)TN)F)F)T)T)NT)FF)F)T)r  N)N)r]  )r  )N)N)N)rQ  rR  rS  __doc__r  r  r  r  r5   Zcommon_audioZcommon_videor   r  rk  ru  rz  r   rZ  re  ra  rb  rc  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rH   rH  r  r  r  rG  r  rV   rE  r   r  r  r  r  r  r]  r   staticmethodr
  r  classmethodr  r   r  r  r   r  r  r  r  r  r  r  rT  r  r  r  r  r	  r  r  r  r4  rA  rG  rR  r_  r  r  r  r  r   r  r  r  r  r  r  r>  r  r  rG  r  rM  r  rS  rV  r  rA  r  r  r  r\  r  r  r  ra  rf  rP  r  r  r  rx  r  r  r  rV  r   cached_propertyr  r  propertyr  r  rW  r  r  r  r  r  r  r  r=  r  r   r   r   r   r      s                                                                        
 W
"


	



 `[
   
2 .*
 v
C  \$ ?  B<($
  l"	<Cm	@#
8r   )r  r  r  r  r  r#  rK  r   http.cookiejarr  r  r  rq  r  r@  r?  r  rl  rM  r  rO  r   r:  r~  r`  r  rs  r7  r   rQ  r   r   r   r   r   r   r	   r<  r
   r   r   Zdownloader.rtmpr   r  r   r   Zextractor.commonr   Zextractor.openloadr   Z
minicursesr   Z
networkingr   r   r   Znetworking.commonr   r   Znetworking.exceptionsr   r   r   r   r   Znetworking.impersonater   r  r   r  Zpostprocessorr   r  r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   Zpostprocessor.ffmpegr,   r:  r  r-   r.   r/   r0   r1   r  r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   Zutils._utilsr   r   Zutils.networkingr   r   r   r   r  r   r   r   r   r   r  r   r   r   r   r   r   <module>   sh   8 iZ
