]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/rtmp.py
[cleanup] Add more ruff rules (#10149)
[yt-dlp.git] / yt_dlp / downloader / rtmp.py
CommitLineData
3bc2ddcc
JMF
1import os
2import re
3import subprocess
3bc2ddcc
JMF
4import time
5
6from .common import FileDownloader
7from ..utils import (
f8271158 8 Popen,
7798fad5 9 check_executable,
9e105a85 10 encodeArgument,
f8271158 11 encodeFilename,
4c83c967 12 get_exe_version,
3bc2ddcc
JMF
13)
14
15
4c83c967
PH
16def rtmpdump_version():
17 return get_exe_version(
18 'rtmpdump', ['--help'], r'(?i)RTMPDump\s*v?([0-9a-zA-Z._-]+)')
19
20
3bc2ddcc
JMF
21class RtmpFD(FileDownloader):
22 def real_download(self, filename, info_dict):
23 def run_rtmpdump(args):
24 start = time.time()
9b0b6275
S
25 resume_percent = None
26 resume_downloaded_data_len = None
d3c93ec2 27 proc = Popen(args, stderr=subprocess.PIPE)
3bc2ddcc 28 cursor_in_new_line = True
9b0b6275
S
29 proc_stderr_closed = False
30 try:
ddd8486a
S
31 while not proc_stderr_closed:
32 # read line from stderr
33 line = ''
34 while True:
35 char = proc.stderr.read(1)
36 if not char:
37 proc_stderr_closed = True
38 break
39 if char in [b'\r', b'\n']:
40 break
41 line += char.decode('ascii', 'replace')
42 if not line:
43 # proc_stderr_closed is True
44 continue
45 mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
3bc2ddcc 46 if mobj:
2514d263 47 downloaded_data_len = int(float(mobj.group(1)) * 1024)
ddd8486a
S
48 percent = float(mobj.group(2))
49 if not resume_percent:
50 resume_percent = percent
51 resume_downloaded_data_len = downloaded_data_len
3bc2ddcc 52 time_now = time.time()
ddd8486a
S
53 eta = self.calc_eta(start, time_now, 100 - resume_percent, percent - resume_percent)
54 speed = self.calc_speed(start, time_now, downloaded_data_len - resume_downloaded_data_len)
55 data_len = None
56 if percent > 0:
57 data_len = int(downloaded_data_len * 100 / percent)
3bc2ddcc 58 self._hook_progress({
ddd8486a 59 'status': 'downloading',
3bc2ddcc 60 'downloaded_bytes': downloaded_data_len,
ddd8486a 61 'total_bytes_estimate': data_len,
3bc2ddcc
JMF
62 'tmpfilename': tmpfilename,
63 'filename': filename,
ddd8486a 64 'eta': eta,
5cda4eda 65 'elapsed': time_now - start,
3bc2ddcc 66 'speed': speed,
3ba7740d 67 }, info_dict)
5cda4eda 68 cursor_in_new_line = False
ddd8486a
S
69 else:
70 # no percent for live streams
71 mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
72 if mobj:
73 downloaded_data_len = int(float(mobj.group(1)) * 1024)
74 time_now = time.time()
75 speed = self.calc_speed(start, time_now, downloaded_data_len)
76 self._hook_progress({
77 'downloaded_bytes': downloaded_data_len,
78 'tmpfilename': tmpfilename,
79 'filename': filename,
80 'status': 'downloading',
81 'elapsed': time_now - start,
82 'speed': speed,
3ba7740d 83 }, info_dict)
ddd8486a
S
84 cursor_in_new_line = False
85 elif self.params.get('verbose', False):
86 if not cursor_in_new_line:
87 self.to_screen('')
88 cursor_in_new_line = True
89 self.to_screen('[rtmpdump] ' + line)
f5b1bca9 90 if not cursor_in_new_line:
91 self.to_screen('')
92 return proc.wait()
93 except BaseException: # Including KeyboardInterrupt
f0c9fb96 94 proc.kill(timeout=None)
f5b1bca9 95 raise
3bc2ddcc
JMF
96
97 url = info_dict['url']
d800609c
S
98 player_url = info_dict.get('player_url')
99 page_url = info_dict.get('page_url')
100 app = info_dict.get('app')
101 play_path = info_dict.get('play_path')
102 tc_url = info_dict.get('tc_url')
103 flash_version = info_dict.get('flash_version')
3bc2ddcc 104 live = info_dict.get('rtmp_live', False)
d800609c
S
105 conn = info_dict.get('rtmp_conn')
106 protocol = info_dict.get('rtmp_protocol')
7bb3ceb4 107 real_time = info_dict.get('rtmp_real_time', False)
7906d199 108 no_resume = info_dict.get('no_resume', False)
f101079a 109 continue_dl = self.params.get('continuedl', True)
3dee7826 110
3bc2ddcc
JMF
111 self.report_destination(filename)
112 tmpfilename = self.temp_name(filename)
113 test = self.params.get('test', False)
114
115 # Check for rtmpdump first
7798fad5 116 if not check_executable('rtmpdump', ['-h']):
beb4b92a 117 self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install')
3bc2ddcc
JMF
118 return False
119
120 # Download using rtmpdump. rtmpdump returns exit code 2 when
17cc1534 121 # the connection was interrupted and resuming appears to be
3bc2ddcc 122 # possible. This is part of rtmpdump's normal usage, AFAIK.
2a15a98a
PH
123 basic_args = [
124 'rtmpdump', '--verbose', '-r', url,
9e105a85 125 '-o', tmpfilename]
3bc2ddcc
JMF
126 if player_url is not None:
127 basic_args += ['--swfVfy', player_url]
128 if page_url is not None:
129 basic_args += ['--pageUrl', page_url]
082c6c86
S
130 if app is not None:
131 basic_args += ['--app', app]
3bc2ddcc
JMF
132 if play_path is not None:
133 basic_args += ['--playpath', play_path]
134 if tc_url is not None:
156fc83a 135 basic_args += ['--tcUrl', tc_url]
3bc2ddcc
JMF
136 if test:
137 basic_args += ['--stop', '1']
082c6c86
S
138 if flash_version is not None:
139 basic_args += ['--flashVer', flash_version]
3bc2ddcc
JMF
140 if live:
141 basic_args += ['--live']
eb451334
S
142 if isinstance(conn, list):
143 for entry in conn:
144 basic_args += ['--conn', entry]
14f25df2 145 elif isinstance(conn, str):
3bc2ddcc 146 basic_args += ['--conn', conn]
087ca2cb
JMF
147 if protocol is not None:
148 basic_args += ['--protocol', protocol]
0865f397
PH
149 if real_time:
150 basic_args += ['--realtime']
3dee7826
PH
151
152 args = basic_args
153 if not no_resume and continue_dl and not live:
154 args += ['--resume']
155 if not live and continue_dl:
156 args += ['--skip', '1']
3bc2ddcc 157
9e105a85 158 args = [encodeArgument(a) for a in args]
3bc2ddcc 159
9e105a85 160 self._debug_cmd(args, exe='rtmpdump')
3bc2ddcc 161
35241756
S
162 RD_SUCCESS = 0
163 RD_FAILED = 1
164 RD_INCOMPLETE = 2
52d6a9a6 165 RD_NO_CONNECT = 3
35241756 166
f16f4877
S
167 started = time.time()
168
ddd8486a
S
169 try:
170 retval = run_rtmpdump(args)
171 except KeyboardInterrupt:
172 if not info_dict.get('is_live'):
173 raise
174 retval = RD_SUCCESS
175 self.to_screen('\n[rtmpdump] Interrupted by user')
3bc2ddcc 176
52d6a9a6 177 if retval == RD_NO_CONNECT:
8dec03ec 178 self.report_error('[rtmpdump] Could not connect to RTMP server.')
52d6a9a6
S
179 return False
180
40fcba5e 181 while retval in (RD_INCOMPLETE, RD_FAILED) and not test and not live:
3bc2ddcc 182 prevsize = os.path.getsize(encodeFilename(tmpfilename))
add96eb9 183 self.to_screen(f'[rtmpdump] Downloaded {prevsize} bytes')
5f6a1245 184 time.sleep(5.0) # This seems to be needed
add96eb9 185 args = [*basic_args, '--resume']
9e105a85
S
186 if retval == RD_FAILED:
187 args += ['--skip', '1']
188 args = [encodeArgument(a) for a in args]
189 retval = run_rtmpdump(args)
3bc2ddcc 190 cursize = os.path.getsize(encodeFilename(tmpfilename))
35241756 191 if prevsize == cursize and retval == RD_FAILED:
3bc2ddcc 192 break
7af808a5 193 # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
35241756 194 if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
8dec03ec 195 self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
35241756 196 retval = RD_SUCCESS
3bc2ddcc 197 break
35241756 198 if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
3bc2ddcc 199 fsize = os.path.getsize(encodeFilename(tmpfilename))
add96eb9 200 self.to_screen(f'[rtmpdump] Downloaded {fsize} bytes')
3bc2ddcc
JMF
201 self.try_rename(tmpfilename, filename)
202 self._hook_progress({
203 'downloaded_bytes': fsize,
204 'total_bytes': fsize,
205 'filename': filename,
206 'status': 'finished',
f16f4877 207 'elapsed': time.time() - started,
3ba7740d 208 }, info_dict)
3bc2ddcc
JMF
209 return True
210 else:
8dec03ec
S
211 self.to_stderr('\n')
212 self.report_error('rtmpdump exited with code %d' % retval)
3bc2ddcc 213 return False