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.

202 lines
8.4 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. 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. args = basic_args
  137. if not no_resume and continue_dl and not live:
  138. args += ['--resume']
  139. if not live and continue_dl:
  140. args += ['--skip', '1']
  141. if sys.platform == 'win32' and sys.version_info < (3, 0):
  142. # Windows subprocess module does not actually support Unicode
  143. # on Python 2.x
  144. # See http://stackoverflow.com/a/9951851/35070
  145. subprocess_encoding = sys.getfilesystemencoding()
  146. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  147. else:
  148. subprocess_encoding = None
  149. self._debug_cmd(args, subprocess_encoding, exe='rtmpdump')
  150. RD_SUCCESS = 0
  151. RD_FAILED = 1
  152. RD_INCOMPLETE = 2
  153. RD_NO_CONNECT = 3
  154. retval = run_rtmpdump(args)
  155. if retval == RD_NO_CONNECT:
  156. self.report_error('[rtmpdump] Could not connect to RTMP server.')
  157. return False
  158. while (retval == RD_INCOMPLETE or retval == RD_FAILED) and not test and not live:
  159. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  160. self.to_screen('[rtmpdump] %s bytes' % prevsize)
  161. time.sleep(5.0) # This seems to be needed
  162. retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == RD_FAILED])
  163. cursize = os.path.getsize(encodeFilename(tmpfilename))
  164. if prevsize == cursize and retval == RD_FAILED:
  165. break
  166. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  167. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  168. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  169. retval = RD_SUCCESS
  170. break
  171. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  172. fsize = os.path.getsize(encodeFilename(tmpfilename))
  173. self.to_screen('[rtmpdump] %s bytes' % fsize)
  174. self.try_rename(tmpfilename, filename)
  175. self._hook_progress({
  176. 'downloaded_bytes': fsize,
  177. 'total_bytes': fsize,
  178. 'filename': filename,
  179. 'status': 'finished',
  180. })
  181. return True
  182. else:
  183. self.to_stderr('\n')
  184. self.report_error('rtmpdump exited with code %d' % retval)
  185. return False