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.

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