Repository: yt-dlp
Issue: [YouTube] API Can't download youtube video to buffer  when download_ranges option is specified
Labels: bug,triage,site:youtube,core:downloader

### DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

- [X] I understand that I will be **blocked** if I *intentionally* remove or skip any mandatory\* field

### Checklist

- [X] I'm reporting a bug unrelated to a specific site
- [X] I've verified that I have **updated yt-dlp to nightly or master** ([update instructions](https://github.com/yt-dlp/yt-dlp#update-channels))
- [X] I've checked that all provided URLs are playable in a browser with the same IP and same login details
- [X] I've checked that all URLs and arguments with special characters are [properly quoted or escaped](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#video-url-contains-an-ampersand--and-im-getting-some-strange-output-1-2839-or-v-is-not-recognized-as-an-internal-or-external-command)
- [X] I've searched [known issues](https://github.com/yt-dlp/yt-dlp/issues/3766) and the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues **including closed ones**. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)

### Provide a description that is worded well enough to be understood

**Issue:**
I am using the API to download a youtube video to a buffer in Python. I implemented the code described in this comment: https://github.com/yt-dlp/yt-dlp/issues/3298#issuecomment-1181754989 and it does work in downloading the requested video to the buffer.
However, if the `download_ranges` option is included to download a specific section, the video is not downloaded to the buffer but is instead (seemingly) written to stdout.

**To Reproduce:**
Run the below code snippet
```python
from yt_dlp import YoutubeDL
from yt_dlp.utils import download_range_func
from contextlib import redirect_stdout
from pathlib import Path
import io

youtube_id = "https://youtu.be/GDRyigWvUFg"
ctx = {
    'download_ranges': download_range_func([], [[10.0, 20.0]]),
    "outtmpl": {'default': "-"},
    'logtostderr': True,
    'verbose': True,
}

# Redirect stdout to the buffer and download video
buffer = io.BytesIO()
with redirect_stdout(buffer), YoutubeDL(ctx) as foo:
    foo.download([youtube_id])

# Buffer should have video contents, write contents of buffer to file for example
Path(f"output.mp4").write_bytes(buffer.getvalue())
```
**Expected behaviour:** 
File output.mp4 should contain the downloaded video (10s to 20s)

**Actual behaviour:** 
File output.mp4 is empty. Unformatted characters are written to stdout (seems to be downloaded video content) Refer to verbose output included below.

**Note: I trimmed the full output to remove most of the outputted unformatted characters as it made the log too long to fit within the comment. I created a shared file that contains the full output which can be viewed on OneDrive: https://1drv.ms/t/s!Amo9F01EvCh5iYsHgMzObR1dYARHWg?e=7OYTaV** 
The log still contains all other output from YoutubeDL. If this is against issue policy do advise, I am not sure how else to include the completed log


### Provide verbose output that clearly demonstrates the problem

- [X] Run **your** yt-dlp command with **-vU** flag added (`yt-dlp -vU <your command line>`)
- [X] If using API, add `'verbose': True` to `YoutubeDL` params instead
- [X] Copy the WHOLE output (starting with `[debug] Command-line config`) and insert it below

### Complete Verbose Output

```shell
[debug] Encodings: locale cp1252, fs utf-8, pref cp1252, out utf-8 (No VT), error utf-8 (No VT), screen utf-8 (No VT)
[debug] yt-dlp version stable@2024.08.06 from yt-dlp/yt-dlp [4d9231208] (pip) API
[debug] params: {'download_ranges': yt_dlp.utils.download_range_func([], [[10, 20]]), 'outtmpl': {'default': '-'}, 'logtostderr': True, 'verbose': True, 'compat_opts': set(), 'http_headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-us,en;q=0.5', 'Sec-Fetch-Mode': 'navigate'}}
[debug] Python 3.12.5 (CPython AMD64 64bit) - Windows-11-10.0.22631-SP0 (OpenSSL 3.0.13 30 Jan 2024)
[debug] exe versions: ffmpeg 2023-12-14-git-5256b2fbe6-full_build-www.gyan.dev (setts)
[debug] Optional libraries: Cryptodome-3.20.0, brotli-1.1.0, certifi-2024.08.30, mutagen-1.47.0, requests-2.32.3, sqlite3-3.45.3, urllib3-2.2.3, websockets-13.0.1
[debug] Proxy map: {}
[debug] Request Handlers: urllib, requests, websockets
[debug] Loaded 1830 extractors
[youtube] Extracting URL: https://youtu.be/GDRyigWvUFg
[youtube] GDRyigWvUFg: Downloading webpage
[youtube] GDRyigWvUFg: Downloading ios player API JSON
[youtube] GDRyigWvUFg: Downloading web creator player API JSON
[debug] Loading youtube-nsig.a9d81eca from cache
[debug] [youtube] Decrypted nsig THszRR11GeoIlwf05 => j-wELkA1X4F79g
[youtube] GDRyigWvUFg: Downloading m3u8 information
[debug] Sort order given by extractor: quality, res, fps, hdr:12, source, vcodec:vp9.2, channels, acodec, lang, proto
[debug] Formats sorted by: hasvid, ie_pref, quality, res, fps, hdr:12(7), source, vcodec:vp9.2(10), channels, acodec, lang, proto, size, br, asr, vext, aext, hasaud, id
[debug] Default format spec: best/bestvideo+bestaudio
[info] GDRyigWvUFg: Downloading 1 format(s): 18
[info] GDRyigWvUFg: Downloading 1 time ranges: 10.0-20.0
[debug] Invoking ffmpeg downloader on "https://rr2---sn-cxaaj5o5q5-tt1r.googlevideo.com/videoplayback?expire=1726916995&ei=I1XuZufgJfGSlu8Posex6A0&ip=70.54.96.253&id=o-AGtl-t_CNVjHxUyaKDK9T4WrVLpDOjhRDnaaMuC07ciI&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=CN&mm=31%2C26&mn=sn-cxaaj5o5q5-tt1r%2Csn-vgqsrnsd&ms=au%2Conr&mv=m&mvi=2&pl=24&initcwndbps=1926250&bui=AXLXGFSxPR6-NUy_yO-d18_euWCra8256sN3p77PZ1VVlKAYPK0sq74KSSV8JIfPOc3q9kLMToDPBEkO&spc=54MbxZcbqcGdv_0rWnUQqJ5RO1wn36ldilqLvgWEww7nLhISJfbb4Y0&vprv=1&svpuc=1&mime=video%2Fmp4&ns=KLWvIV8waBTNOnPQ8JdDqtsQ&rqh=1&gir=yes&clen=2202998&ratebypass=yes&dur=48.274&lmt=1723414544111661&mt=1726894855&fvip=1&fexp=51286683&c=WEB_CREATOR&sefc=1&txp=5538434&n=j-wELkA1X4F79g&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=AJfQdSswRQIgPGBkxoLeSFj9yjt3qPdCjCo2tWydQsHFAOi3GUjwAUoCIQC28MrXBSRd51LZqlurEPD3OmhbEzOWpyTWjbRBfQShog%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=ABPmVW0wRAIgHeDfDHo4Bq8WJj2RItQTO0D2aQf6WC2NEb_H0XQYgvECIAFEWHnV4I9krzuaS0yhgc88uqO0Mtnynzgdm7tTEG2Z"
[download] Destination: -
[debug] ffmpeg command line: ffmpeg -y -loglevel verbose -headers "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Sec-Fetch-Mode: navigate
" -ss 10 -t 10 -i "https://rr2---sn-cxaaj5o5q5-tt1r.googlevideo.com/videoplayback?expire=1726916995&ei=I1XuZufgJfGSlu8Posex6A0&ip=70.54.96.253&id=o-AGtl-t_CNVjHxUyaKDK9T4WrVLpDOjhRDnaaMuC07ciI&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=CN&mm=31%2C26&mn=sn-cxaaj5o5q5-tt1r%2Csn-vgqsrnsd&ms=au%2Conr&mv=m&mvi=2&pl=24&initcwndbps=1926250&bui=AXLXGFSxPR6-NUy_yO-d18_euWCra8256sN3p77PZ1VVlKAYPK0sq74KSSV8JIfPOc3q9kLMToDPBEkO&spc=54MbxZcbqcGdv_0rWnUQqJ5RO1wn36ldilqLvgWEww7nLhISJfbb4Y0&vprv=1&svpuc=1&mime=video%2Fmp4&ns=KLWvIV8waBTNOnPQ8JdDqtsQ&rqh=1&gir=yes&clen=2202998&ratebypass=yes&dur=48.274&lmt=1723414544111661&mt=1726894855&fvip=1&fexp=51286683&c=WEB_CREATOR&sefc=1&txp=5538434&n=j-wELkA1X4F79g&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=AJfQdSswRQIgPGBkxoLeSFj9yjt3qPdCjCo2tWydQsHFAOi3GUjwAUoCIQC28MrXBSRd51LZqlurEPD3OmhbEzOWpyTWjbRBfQShog%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=ABPmVW0wRAIgHeDfDHo4Bq8WJj2RItQTO0D2aQf6WC2NEb_H0XQYgvECIAFEWHnV4I9krzuaS0yhgc88uqO0Mtnynzgdm7tTEG2Z" -c copy -f mpegts -
ffmpeg version 2023-12-14-git-5256b2fbe6-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --pkg-config=pkgconf --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libaribcaption --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-libharfbuzz --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-dxva2 --enable-d3d11va --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libcodec2 --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      58. 33.100 / 58. 33.100
  libavcodec     60. 35.100 / 60. 35.100
  libavformat    60. 18.100 / 60. 18.100
  libavdevice    60.  4.100 / 60.  4.100
  libavfilter     9. 14.100 /  9. 14.100
  libswscale      7.  6.100 /  7.  6.100
  libswresample   4. 13.100 /  4. 13.100
  libpostproc    57.  4.100 / 57.  4.100
[tcp @ 000001b3dccd7b40] Starting connection attempt to 184.150.168.173 port 443
[tcp @ 000001b3dccd7b40] Successfully connected to 184.150.168.173 port 443
[mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd58c0] Reconfiguring buffers to size 510422
[h264 @ 000001b3dd532040] Reinit context to 640x368, pix_fmt: yuv420p
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'https://rr2---sn-cxaaj5o5q5-tt1r.googlevideo.com/videoplayback?expire=1726916995&ei=I1XuZufgJfGSlu8Posex6A0&ip=70.54.96.253&id=o-AGtl-t_CNVjHxUyaKDK9T4WrVLpDOjhRDnaaMuC07ciI&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=CN&mm=31%2C26&mn=sn-cxaaj5o5q5-tt1r%2Csn-vgqsrnsd&ms=au%2Conr&mv=m&mvi=2&pl=24&initcwndbps=1926250&bui=AXLXGFSxPR6-NUy_yO-d18_euWCra8256sN3p77PZ1VVlKAYPK0sq74KSSV8JIfPOc3q9kLMToDPBEkO&spc=54MbxZcbqcGdv_0rWnUQqJ5RO1wn36ldilqLvgWEww7nLhISJfbb4Y0&vprv=1&svpuc=1&mime=video%2Fmp4&ns=KLWvIV8waBTNOnPQ8JdDqtsQ&rqh=1&gir=yes&clen=2202998&ratebypass=yes&dur=48.274&lmt=1723414544111661&mt=1726894855&fvip=1&fexp=51286683&c=WEB_CREATOR&sefc=1&txp=5538434&n=j-wELkA1X4F79g&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=AJfQdSswRQIgPGBkxoLeSFj9yjt3qPdCjCo2tWydQsHFAOi3GUjwAUoCIQC28MrXBSRd51LZqlurEPD3OmhbEzOWpyTWjbRBfQShog%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=ABPmVW0wRAIgHeDfDHo4Bq8WJj2RItQTO0D2aQf6WC2NEb_H0XQYgvECIAFEWHnV4I9krzuaS0yhgc88uqO0Mtnynzgdm7tTEG2Z':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: isommp42
    encoder         : Google
  Duration: 00:00:48.27, start: 0.000000, bitrate: 365 kb/s
  Stream #0:0[0x1](und): Video: h264 (Main), 1 reference frame (avc1 / 0x31637661), yuv420p(tv, bt709, progressive, left), 640x360 (640x368) [SAR 1:1 DAR 16:9], 266 kb/s, 23.98 fps, 23.98 tbr, 24k tbn (default)
    Metadata:
      handler_name    : ISO Media file produced by Google Inc.
      vendor_id       : [0][0][0][0]
  Stream #0:1[0x2](eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 95 kb/s (default)
    Metadata:
      handler_name    : ISO Media file produced by Google Inc.
      vendor_id       : [0][0][0][0]
[out#0/mpegts @ 000001b3dd4b1280] No explicit maps, mapping streams automatically...
[vost#0:0/copy @ 000001b3dd678d40] Created video stream from input stream 0:0
[aost#0:1/copy @ 000001b3dd80a040] Created audio stream from input stream 0:1
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
[mpegts @ 000001b3dccd9f80] service 1 using PCR in pid=256, pcr_period=83ms
[mpegts @ 000001b3dccd9f80] muxrate VBR, sdt every 500 ms, pat/pmt every 100 ms
Output #0, mpegts, to 'pipe:':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: isommp42
    encoder         : Lavf60.18.100
  Stream #0:0(und): Video: h264 (Main), 1 reference frame (avc1 / 0x31637661), yuv420p(tv, bt709, progressive, left), 640x360 (0x0) [SAR 1:1 DAR 16:9], q=2-31, 266 kb/s, 23.98 fps, 23.98 tbr, 90k tbn (default)
    Metadata:
      handler_name    : ISO Media file produced by Google Inc.
      vendor_id       : [0][0][0][0]
  Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 95 kb/s (default)
    Metadata:
      handler_name    : ISO Media file produced by Google Inc.
      vendor_id       : [0][0][0][0]
[out#0/mpegts @ 000001b3dd4b1280] Starting thread...
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480] Starting thread...
Press [q] to stop, [?] for help
[tcp @ 000001b3dccdd680] Starting connection attempt to 184.150.168.173 port 443
[tcp @ 000001b3dccdd680] Successfully connected to 184.150.168.173 port 443
Automatically inserted bitstream filter 'h264_mp4toannexb'; args=''
 �   � *�������������������������������������������������������������������
 NOTE: Character output was trimmed so that log could fit within max comment size, refer to comment for full output
 ���J�[��6D��C� �ꃆN��W�ꖙ��Z l��i2����@��6��.���1(G9^ ���������������������������������������������������������������������������������������������A5t�L�o�Uܶ]�: @�b����=J==3˵�C���yWw�>cM�Ȓ�J�4Ţ,�kܖC����FI�6�<��액�^�-D*r\N]B`[vist#0:0/h264 @ 000001b3dccbc280] All consumers of this stream are done
[aist#0:1/aac @ 000001b3dd41b100] All consumers of this stream are done
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480] All consumers are done
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480] Terminating thread with return code 0 (success)
[out#0/mpegts @ 000001b3dd4b1280] All streams finished
[out#0/mpegts @ 000001b3dd4b1280] Terminating thread with return code 0 (success)
[AVIOContext @ 000001b3dd4bccc0] Statistics: 700676 bytes written, 0 seeks, 352 writeouts
[out#0/mpegts @ 000001b3dd4b1280] Output file #0 (pipe:):
[out#0/mpegts @ 000001b3dd4b1280]   Output stream #0:0 (video): 297 packets muxed (450928 bytes);
[out#0/mpegts @ 000001b3dd4b1280]   Output stream #0:1 (audio): 534 packets muxed (148363 bytes);
[out#0/mpegts @ 000001b3dd4b1280]   Total: 831 packets (599291 bytes) muxed
[out#0/mpegts @ 000001b3dd4b1280] video:440kB audio:145kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 16.917491%
size=     684kB time=N/A bitrate=N/A speed=N/A
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480] Input file #0 (https://rr2---sn-cxaaj5o5q5-tt1r.googlevideo.com/videoplayback?expire=1726916995&ei=I1XuZufgJfGSlu8Posex6A0&ip=70.54.96.253&id=o-AGtl-t_CNVjHxUyaKDK9T4WrVLpDOjhRDnaaMuC07ciI&itag=18&source=youtube&requiressl=yes&xpc=EgVo2aDSNQ%3D%3D&mh=CN&mm=31%2C26&mn=sn-cxaaj5o5q5-tt1r%2Csn-vgqsrnsd&ms=au%2Conr&mv=m&mvi=2&pl=24&initcwndbps=1926250&bui=AXLXGFSxPR6-NUy_yO-d18_euWCra8256sN3p77PZ1VVlKAYPK0sq74KSSV8JIfPOc3q9kLMToDPBEkO&spc=54MbxZcbqcGdv_0rWnUQqJ5RO1wn36ldilqLvgWEww7nLhISJfbb4Y0&vprv=1&svpuc=1&mime=video%2Fmp4&ns=KLWvIV8waBTNOnPQ8JdDqtsQ&rqh=1&gir=yes&clen=2202998&ratebypass=yes&dur=48.274&lmt=1723414544111661&mt=1726894855&fvip=1&fexp=51286683&c=WEB_CREATOR&sefc=1&txp=5538434&n=j-wELkA1X4F79g&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cxpc%2Cbui%2Cspc%2Cvprv%2Csvpuc%2Cmime%2Cns%2Crqh%2Cgir%2Cclen%2Cratebypass%2Cdur%2Clmt&sig=AJfQdSswRQIgPGBkxoLeSFj9yjt3qPdCjCo2tWydQsHFAOi3GUjwAUoCIQC28MrXBSRd51LZqlurEPD3OmhbEzOWpyTWjbRBfQShog%3D%3D&lsparams=mh%2Cmm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl%2Cinitcwndbps&lsig=ABPmVW0wRAIgHeDfDHo4Bq8WJj2RItQTO0D2aQf6WC2NEb_H0XQYgvECIAFEWHnV4I9krzuaS0yhgc88uqO0Mtnynzgdm7tTEG2Z):
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480]   Input stream #0:0 (video): 298 packets read (454143 bytes);
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480]   Input stream #0:1 (audio): 535 packets read (148632 bytes);
[in#0/mov,mp4,m4a,3gp,3g2,mj2 @ 000001b3dccd5480]   Total: 833 packets (602775 bytes) demuxed
[AVIOContext @ 000001b3dd41bd40] Statistics: 655360 bytes read, 1 seeks
[download] 100% in 00:00:00
```