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.

204 lines
8.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  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 ..compat import compat_str
  9. from ..utils import (
  10. check_executable,
  11. encodeFilename,
  12. get_exe_version,
  13. )
  14. def rtmpdump_version():
  15. return get_exe_version(
  16. 'rtmpdump', ['--help'], r'(?i)RTMPDump\s*v?([0-9a-zA-Z._-]+)')
  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. time_now = time.time()
  48. eta = self.calc_eta(start, time_now, 100 - resume_percent, percent - resume_percent)
  49. speed = self.calc_speed(start, time_now, 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. self._hook_progress({
  54. 'status': 'downloading',
  55. 'downloaded_bytes': downloaded_data_len,
  56. 'total_bytes_estimate': data_len,
  57. 'tmpfilename': tmpfilename,
  58. 'filename': filename,
  59. 'eta': eta,
  60. 'elapsed': time_now - start,
  61. 'speed': speed,
  62. })
  63. cursor_in_new_line = False
  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._hook_progress({
  72. 'downloaded_bytes': downloaded_data_len,
  73. 'tmpfilename': tmpfilename,
  74. 'filename': filename,
  75. 'status': 'downloading',
  76. 'elapsed': time_now - start,
  77. 'speed': speed,
  78. })
  79. cursor_in_new_line = False
  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. url = info_dict['url']
  90. player_url = info_dict.get('player_url', None)
  91. page_url = info_dict.get('page_url', None)
  92. app = info_dict.get('app', None)
  93. play_path = info_dict.get('play_path', None)
  94. tc_url = info_dict.get('tc_url', None)
  95. flash_version = info_dict.get('flash_version', None)
  96. live = info_dict.get('rtmp_live', False)
  97. conn = info_dict.get('rtmp_conn', None)
  98. protocol = info_dict.get('rtmp_protocol', None)
  99. real_time = info_dict.get('rtmp_real_time', False)
  100. no_resume = info_dict.get('no_resume', False)
  101. continue_dl = info_dict.get('continuedl', False)
  102. self.report_destination(filename)
  103. tmpfilename = self.temp_name(filename)
  104. test = self.params.get('test', False)
  105. # Check for rtmpdump first
  106. if not check_executable('rtmpdump', ['-h']):
  107. self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install it.')
  108. return False
  109. # Download using rtmpdump. rtmpdump returns exit code 2 when
  110. # the connection was interrumpted and resuming appears to be
  111. # possible. This is part of rtmpdump's normal usage, AFAIK.
  112. basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
  113. if player_url is not None:
  114. basic_args += ['--swfVfy', player_url]
  115. if page_url is not None:
  116. basic_args += ['--pageUrl', page_url]
  117. if app is not None:
  118. basic_args += ['--app', app]
  119. if play_path is not None:
  120. basic_args += ['--playpath', play_path]
  121. if tc_url is not None:
  122. basic_args += ['--tcUrl', url]
  123. if test:
  124. basic_args += ['--stop', '1']
  125. if flash_version is not None:
  126. basic_args += ['--flashVer', flash_version]
  127. if live:
  128. basic_args += ['--live']
  129. if isinstance(conn, list):
  130. for entry in conn:
  131. basic_args += ['--conn', entry]
  132. elif isinstance(conn, compat_str):
  133. basic_args += ['--conn', conn]
  134. if protocol is not None:
  135. basic_args += ['--protocol', protocol]
  136. if real_time:
  137. basic_args += ['--realtime']
  138. args = basic_args
  139. if not no_resume and continue_dl and not live:
  140. args += ['--resume']
  141. if not live and continue_dl:
  142. args += ['--skip', '1']
  143. if sys.platform == 'win32' and sys.version_info < (3, 0):
  144. # Windows subprocess module does not actually support Unicode
  145. # on Python 2.x
  146. # See http://stackoverflow.com/a/9951851/35070
  147. subprocess_encoding = sys.getfilesystemencoding()
  148. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  149. else:
  150. subprocess_encoding = None
  151. self._debug_cmd(args, subprocess_encoding, exe='rtmpdump')
  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