]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/downloader/rtmp.py
Merge branch 'rzhxeo-cinemassacre'
[youtube-dl] / youtube_dl / downloader / rtmp.py
1 from __future__ import unicode_literals
2
3 import os
4 import re
5 import subprocess
6 import sys
7 import time
8
9 from .common import FileDownloader
10 from ..utils import (
11     encodeFilename,
12     format_bytes,
13     compat_str,
14 )
15
16
17 class RtmpFD(FileDownloader):
18     def real_download(self, filename, info_dict):
19         def run_rtmpdump(args):
20             start = time.time()
21             resume_percent = None
22             resume_downloaded_data_len = None
23             proc = subprocess.Popen(args, stderr=subprocess.PIPE)
24             cursor_in_new_line = True
25             proc_stderr_closed = False
26             while not proc_stderr_closed:
27                 # read line from stderr
28                 line = ''
29                 while True:
30                     char = proc.stderr.read(1)
31                     if not char:
32                         proc_stderr_closed = True
33                         break
34                     if char in [b'\r', b'\n']:
35                         break
36                     line += char.decode('ascii', 'replace')
37                 if not line:
38                     # proc_stderr_closed is True
39                     continue
40                 mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
41                 if mobj:
42                     downloaded_data_len = int(float(mobj.group(1))*1024)
43                     percent = float(mobj.group(2))
44                     if not resume_percent:
45                         resume_percent = percent
46                         resume_downloaded_data_len = downloaded_data_len
47                     eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
48                     speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
49                     data_len = None
50                     if percent > 0:
51                         data_len = int(downloaded_data_len * 100 / percent)
52                     data_len_str = '~' + format_bytes(data_len)
53                     self.report_progress(percent, data_len_str, speed, eta)
54                     cursor_in_new_line = False
55                     self._hook_progress({
56                         'downloaded_bytes': downloaded_data_len,
57                         'total_bytes': data_len,
58                         'tmpfilename': tmpfilename,
59                         'filename': filename,
60                         'status': 'downloading',
61                         'eta': eta,
62                         'speed': speed,
63                     })
64                 else:
65                     # no percent for live streams
66                     mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
67                     if mobj:
68                         downloaded_data_len = int(float(mobj.group(1))*1024)
69                         time_now = time.time()
70                         speed = self.calc_speed(start, time_now, downloaded_data_len)
71                         self.report_progress_live_stream(downloaded_data_len, speed, time_now - start)
72                         cursor_in_new_line = False
73                         self._hook_progress({
74                             'downloaded_bytes': downloaded_data_len,
75                             'tmpfilename': tmpfilename,
76                             'filename': filename,
77                             'status': 'downloading',
78                             'speed': speed,
79                         })
80                     elif self.params.get('verbose', False):
81                         if not cursor_in_new_line:
82                             self.to_screen('')
83                         cursor_in_new_line = True
84                         self.to_screen('[rtmpdump] '+line)
85             proc.wait()
86             if not cursor_in_new_line:
87                 self.to_screen('')
88             return proc.returncode
89
90         url = info_dict['url']
91         player_url = info_dict.get('player_url', None)
92         page_url = info_dict.get('page_url', None)
93         app = info_dict.get('app', None)
94         play_path = info_dict.get('play_path', None)
95         tc_url = info_dict.get('tc_url', None)
96         flash_version = info_dict.get('flash_version', None)
97         live = info_dict.get('rtmp_live', False)
98         conn = info_dict.get('rtmp_conn', None)
99
100         self.report_destination(filename)
101         tmpfilename = self.temp_name(filename)
102         test = self.params.get('test', False)
103
104         # Check for rtmpdump first
105         try:
106             subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
107         except (OSError, IOError):
108             self.report_error('RTMP download detected but "rtmpdump" could not be run')
109             return False
110
111         # Download using rtmpdump. rtmpdump returns exit code 2 when
112         # the connection was interrumpted and resuming appears to be
113         # possible. This is part of rtmpdump's normal usage, AFAIK.
114         basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
115         if player_url is not None:
116             basic_args += ['--swfVfy', player_url]
117         if page_url is not None:
118             basic_args += ['--pageUrl', page_url]
119         if app is not None:
120             basic_args += ['--app', app]
121         if play_path is not None:
122             basic_args += ['--playpath', play_path]
123         if tc_url is not None:
124             basic_args += ['--tcUrl', url]
125         if test:
126             basic_args += ['--stop', '1']
127         if flash_version is not None:
128             basic_args += ['--flashVer', flash_version]
129         if live:
130             basic_args += ['--live']
131         if isinstance(conn, list):
132             for entry in conn:
133                 basic_args += ['--conn', entry]
134         elif isinstance(conn, compat_str):
135             basic_args += ['--conn', conn]
136         args = basic_args + [[], ['--resume', '--skip', '1']][not live and self.params.get('continuedl', False)]
137
138         if sys.platform == 'win32' and sys.version_info < (3, 0):
139             # Windows subprocess module does not actually support Unicode
140             # on Python 2.x
141             # See http://stackoverflow.com/a/9951851/35070
142             subprocess_encoding = sys.getfilesystemencoding()
143             args = [a.encode(subprocess_encoding, 'ignore') for a in args]
144         else:
145             subprocess_encoding = None
146
147         if self.params.get('verbose', False):
148             if subprocess_encoding:
149                 str_args = [
150                     a.decode(subprocess_encoding) if isinstance(a, bytes) else a
151                     for a in args]
152             else:
153                 str_args = args
154             try:
155                 import pipes
156                 shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
157             except ImportError:
158                 shell_quote = repr
159             self.to_screen('[debug] rtmpdump command line: ' + shell_quote(str_args))
160
161         RD_SUCCESS = 0
162         RD_FAILED = 1
163         RD_INCOMPLETE = 2
164         RD_NO_CONNECT = 3
165
166         retval = run_rtmpdump(args)
167
168         if retval == RD_NO_CONNECT:
169             self.report_error('[rtmpdump] Could not connect to RTMP server.')
170             return False
171
172         while (retval == RD_INCOMPLETE or retval == RD_FAILED) and not test and not live:
173             prevsize = os.path.getsize(encodeFilename(tmpfilename))
174             self.to_screen('[rtmpdump] %s bytes' % prevsize)
175             time.sleep(5.0) # This seems to be needed
176             retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == RD_FAILED])
177             cursize = os.path.getsize(encodeFilename(tmpfilename))
178             if prevsize == cursize and retval == RD_FAILED:
179                 break
180              # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
181             if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
182                 self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
183                 retval = RD_SUCCESS
184                 break
185         if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
186             fsize = os.path.getsize(encodeFilename(tmpfilename))
187             self.to_screen('[rtmpdump] %s bytes' % fsize)
188             self.try_rename(tmpfilename, filename)
189             self._hook_progress({
190                 'downloaded_bytes': fsize,
191                 'total_bytes': fsize,
192                 'filename': filename,
193                 'status': 'finished',
194             })
195             return True
196         else:
197             self.to_stderr('\n')
198             self.report_error('rtmpdump exited with code %d' % retval)
199             return False