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.

205 lines
8.5 KiB

10 years ago
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. 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. real_time = info_dict.get('rtmp_real_time', False)
  101. no_resume = info_dict.get('no_resume', False)
  102. continue_dl = info_dict.get('continuedl', False)
  103. self.report_destination(filename)
  104. tmpfilename = self.temp_name(filename)
  105. test = self.params.get('test', False)
  106. # Check for rtmpdump first
  107. if not check_executable('rtmpdump', ['-h']):
  108. self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install it.')
  109. return False
  110. # Download using rtmpdump. rtmpdump returns exit code 2 when
  111. # the connection was interrumpted and resuming appears to be
  112. # possible. This is part of rtmpdump's normal usage, AFAIK.
  113. basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
  114. if player_url is not None:
  115. basic_args += ['--swfVfy', player_url]
  116. if page_url is not None:
  117. basic_args += ['--pageUrl', page_url]
  118. if app is not None:
  119. basic_args += ['--app', app]
  120. if play_path is not None:
  121. basic_args += ['--playpath', play_path]
  122. if tc_url is not None:
  123. basic_args += ['--tcUrl', url]
  124. if test:
  125. basic_args += ['--stop', '1']
  126. if flash_version is not None:
  127. basic_args += ['--flashVer', flash_version]
  128. if live:
  129. basic_args += ['--live']
  130. if isinstance(conn, list):
  131. for entry in conn:
  132. basic_args += ['--conn', entry]
  133. elif isinstance(conn, compat_str):
  134. basic_args += ['--conn', conn]
  135. if protocol is not None:
  136. basic_args += ['--protocol', protocol]
  137. if real_time:
  138. basic_args += ['--realtime']
  139. args = basic_args
  140. if not no_resume and continue_dl and not live:
  141. args += ['--resume']
  142. if not live and continue_dl:
  143. args += ['--skip', '1']
  144. if sys.platform == 'win32' and sys.version_info < (3, 0):
  145. # Windows subprocess module does not actually support Unicode
  146. # on Python 2.x
  147. # See http://stackoverflow.com/a/9951851/35070
  148. subprocess_encoding = sys.getfilesystemencoding()
  149. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  150. else:
  151. subprocess_encoding = None
  152. self._debug_cmd(args, subprocess_encoding, exe='rtmpdump')
  153. RD_SUCCESS = 0
  154. RD_FAILED = 1
  155. RD_INCOMPLETE = 2
  156. RD_NO_CONNECT = 3
  157. retval = run_rtmpdump(args)
  158. if retval == RD_NO_CONNECT:
  159. self.report_error('[rtmpdump] Could not connect to RTMP server.')
  160. return False
  161. while (retval == RD_INCOMPLETE or retval == RD_FAILED) and not test and not live:
  162. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  163. self.to_screen('[rtmpdump] %s bytes' % prevsize)
  164. time.sleep(5.0) # This seems to be needed
  165. retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == RD_FAILED])
  166. cursize = os.path.getsize(encodeFilename(tmpfilename))
  167. if prevsize == cursize and retval == RD_FAILED:
  168. break
  169. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  170. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  171. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  172. retval = RD_SUCCESS
  173. break
  174. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  175. fsize = os.path.getsize(encodeFilename(tmpfilename))
  176. self.to_screen('[rtmpdump] %s bytes' % fsize)
  177. self.try_rename(tmpfilename, filename)
  178. self._hook_progress({
  179. 'downloaded_bytes': fsize,
  180. 'total_bytes': fsize,
  181. 'filename': filename,
  182. 'status': 'finished',
  183. })
  184. return True
  185. else:
  186. self.to_stderr('\n')
  187. self.report_error('rtmpdump exited with code %d' % retval)
  188. return False