Release 2024.07.16
[yt-dlp.git] / yt_dlp / downloader / rtmp.py
blobd7ffb3b34df5e0a4c5bd0a7a94bdf396685c1d5c
1 import os
2 import re
3 import subprocess
4 import time
6 from .common import FileDownloader
7 from ..utils import (
8 Popen,
9 check_executable,
10 encodeArgument,
11 encodeFilename,
12 get_exe_version,
16 def rtmpdump_version():
17 return get_exe_version(
18 'rtmpdump', ['--help'], r'(?i)RTMPDump\s*v?([0-9a-zA-Z._-]+)')
21 class RtmpFD(FileDownloader):
22 def real_download(self, filename, info_dict):
23 def run_rtmpdump(args):
24 start = time.time()
25 resume_percent = None
26 resume_downloaded_data_len = None
27 proc = Popen(args, stderr=subprocess.PIPE)
28 cursor_in_new_line = True
29 proc_stderr_closed = False
30 try:
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)
46 if mobj:
47 downloaded_data_len = int(float(mobj.group(1)) * 1024)
48 percent = float(mobj.group(2))
49 if not resume_percent:
50 resume_percent = percent
51 resume_downloaded_data_len = downloaded_data_len
52 time_now = time.time()
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)
58 self._hook_progress({
59 'status': 'downloading',
60 'downloaded_bytes': downloaded_data_len,
61 'total_bytes_estimate': data_len,
62 'tmpfilename': tmpfilename,
63 'filename': filename,
64 'eta': eta,
65 'elapsed': time_now - start,
66 'speed': speed,
67 }, info_dict)
68 cursor_in_new_line = False
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,
83 }, info_dict)
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)
90 if not cursor_in_new_line:
91 self.to_screen('')
92 return proc.wait()
93 except BaseException: # Including KeyboardInterrupt
94 proc.kill(timeout=None)
95 raise
97 url = info_dict['url']
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')
104 live = info_dict.get('rtmp_live', False)
105 conn = info_dict.get('rtmp_conn')
106 protocol = info_dict.get('rtmp_protocol')
107 real_time = info_dict.get('rtmp_real_time', False)
108 no_resume = info_dict.get('no_resume', False)
109 continue_dl = self.params.get('continuedl', True)
111 self.report_destination(filename)
112 tmpfilename = self.temp_name(filename)
113 test = self.params.get('test', False)
115 # Check for rtmpdump first
116 if not check_executable('rtmpdump', ['-h']):
117 self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install')
118 return False
120 # Download using rtmpdump. rtmpdump returns exit code 2 when
121 # the connection was interrupted and resuming appears to be
122 # possible. This is part of rtmpdump's normal usage, AFAIK.
123 basic_args = [
124 'rtmpdump', '--verbose', '-r', url,
125 '-o', tmpfilename]
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]
130 if app is not None:
131 basic_args += ['--app', app]
132 if play_path is not None:
133 basic_args += ['--playpath', play_path]
134 if tc_url is not None:
135 basic_args += ['--tcUrl', tc_url]
136 if test:
137 basic_args += ['--stop', '1']
138 if flash_version is not None:
139 basic_args += ['--flashVer', flash_version]
140 if live:
141 basic_args += ['--live']
142 if isinstance(conn, list):
143 for entry in conn:
144 basic_args += ['--conn', entry]
145 elif isinstance(conn, str):
146 basic_args += ['--conn', conn]
147 if protocol is not None:
148 basic_args += ['--protocol', protocol]
149 if real_time:
150 basic_args += ['--realtime']
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']
158 args = [encodeArgument(a) for a in args]
160 self._debug_cmd(args, exe='rtmpdump')
162 RD_SUCCESS = 0
163 RD_FAILED = 1
164 RD_INCOMPLETE = 2
165 RD_NO_CONNECT = 3
167 started = time.time()
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')
177 if retval == RD_NO_CONNECT:
178 self.report_error('[rtmpdump] Could not connect to RTMP server.')
179 return False
181 while retval in (RD_INCOMPLETE, RD_FAILED) and not test and not live:
182 prevsize = os.path.getsize(encodeFilename(tmpfilename))
183 self.to_screen(f'[rtmpdump] Downloaded {prevsize} bytes')
184 time.sleep(5.0) # This seems to be needed
185 args = [*basic_args, '--resume']
186 if retval == RD_FAILED:
187 args += ['--skip', '1']
188 args = [encodeArgument(a) for a in args]
189 retval = run_rtmpdump(args)
190 cursize = os.path.getsize(encodeFilename(tmpfilename))
191 if prevsize == cursize and retval == RD_FAILED:
192 break
193 # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
194 if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
195 self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
196 retval = RD_SUCCESS
197 break
198 if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
199 fsize = os.path.getsize(encodeFilename(tmpfilename))
200 self.to_screen(f'[rtmpdump] Downloaded {fsize} bytes')
201 self.try_rename(tmpfilename, filename)
202 self._hook_progress({
203 'downloaded_bytes': fsize,
204 'total_bytes': fsize,
205 'filename': filename,
206 'status': 'finished',
207 'elapsed': time.time() - started,
208 }, info_dict)
209 return True
210 else:
211 self.to_stderr('\n')
212 self.report_error('rtmpdump exited with code %d' % retval)
213 return False