You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

201 lines
8.5 KiB

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