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.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. encodeFilename,
  10. format_bytes,
  11. compat_str,
  12. )
  13. class RtmpFD(FileDownloader):
  14. def real_download(self, filename, info_dict):
  15. def run_rtmpdump(args):
  16. start = time.time()
  17. resume_percent = None
  18. resume_downloaded_data_len = None
  19. proc = subprocess.Popen(args, stderr=subprocess.PIPE)
  20. cursor_in_new_line = True
  21. proc_stderr_closed = False
  22. while not proc_stderr_closed:
  23. # read line from stderr
  24. line = ''
  25. while True:
  26. char = proc.stderr.read(1)
  27. if not char:
  28. proc_stderr_closed = True
  29. break
  30. if char in [b'\r', b'\n']:
  31. break
  32. line += char.decode('ascii', 'replace')
  33. if not line:
  34. # proc_stderr_closed is True
  35. continue
  36. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
  37. if mobj:
  38. downloaded_data_len = int(float(mobj.group(1))*1024)
  39. percent = float(mobj.group(2))
  40. if not resume_percent:
  41. resume_percent = percent
  42. resume_downloaded_data_len = downloaded_data_len
  43. eta = self.calc_eta(start, time.time(), 100-resume_percent, percent-resume_percent)
  44. speed = self.calc_speed(start, time.time(), downloaded_data_len-resume_downloaded_data_len)
  45. data_len = None
  46. if percent > 0:
  47. data_len = int(downloaded_data_len * 100 / percent)
  48. data_len_str = '~' + format_bytes(data_len)
  49. self.report_progress(percent, data_len_str, speed, eta)
  50. cursor_in_new_line = False
  51. self._hook_progress({
  52. 'downloaded_bytes': downloaded_data_len,
  53. 'total_bytes': data_len,
  54. 'tmpfilename': tmpfilename,
  55. 'filename': filename,
  56. 'status': 'downloading',
  57. 'eta': eta,
  58. 'speed': speed,
  59. })
  60. else:
  61. # no percent for live streams
  62. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
  63. if mobj:
  64. downloaded_data_len = int(float(mobj.group(1))*1024)
  65. time_now = time.time()
  66. speed = self.calc_speed(start, time_now, downloaded_data_len)
  67. self.report_progress_live_stream(downloaded_data_len, speed, time_now - start)
  68. cursor_in_new_line = False
  69. self._hook_progress({
  70. 'downloaded_bytes': downloaded_data_len,
  71. 'tmpfilename': tmpfilename,
  72. 'filename': filename,
  73. 'status': 'downloading',
  74. 'speed': speed,
  75. })
  76. elif self.params.get('verbose', False):
  77. if not cursor_in_new_line:
  78. self.to_screen('')
  79. cursor_in_new_line = True
  80. self.to_screen('[rtmpdump] '+line)
  81. proc.wait()
  82. if not cursor_in_new_line:
  83. self.to_screen('')
  84. return proc.returncode
  85. url = info_dict['url']
  86. player_url = info_dict.get('player_url', None)
  87. page_url = info_dict.get('page_url', None)
  88. app = info_dict.get('app', None)
  89. play_path = info_dict.get('play_path', None)
  90. tc_url = info_dict.get('tc_url', None)
  91. flash_version = info_dict.get('flash_version', None)
  92. live = info_dict.get('rtmp_live', False)
  93. conn = info_dict.get('rtmp_conn', None)
  94. protocol = info_dict.get('rtmp_protocol', None)
  95. self.report_destination(filename)
  96. tmpfilename = self.temp_name(filename)
  97. test = self.params.get('test', False)
  98. # Check for rtmpdump first
  99. try:
  100. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  101. except (OSError, IOError):
  102. self.report_error('RTMP download detected but "rtmpdump" could not be run')
  103. return False
  104. # Download using rtmpdump. rtmpdump returns exit code 2 when
  105. # the connection was interrumpted and resuming appears to be
  106. # possible. This is part of rtmpdump's normal usage, AFAIK.
  107. basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
  108. if player_url is not None:
  109. basic_args += ['--swfVfy', player_url]
  110. if page_url is not None:
  111. basic_args += ['--pageUrl', page_url]
  112. if app is not None:
  113. basic_args += ['--app', app]
  114. if play_path is not None:
  115. basic_args += ['--playpath', play_path]
  116. if tc_url is not None:
  117. basic_args += ['--tcUrl', url]
  118. if test:
  119. basic_args += ['--stop', '1']
  120. if flash_version is not None:
  121. basic_args += ['--flashVer', flash_version]
  122. if live:
  123. basic_args += ['--live']
  124. if isinstance(conn, list):
  125. for entry in conn:
  126. basic_args += ['--conn', entry]
  127. elif isinstance(conn, compat_str):
  128. basic_args += ['--conn', conn]
  129. if protocol is not None:
  130. basic_args += ['--protocol', protocol]
  131. args = basic_args + [[], ['--resume', '--skip', '1']][not live and self.params.get('continuedl', False)]
  132. if sys.platform == 'win32' and sys.version_info < (3, 0):
  133. # Windows subprocess module does not actually support Unicode
  134. # on Python 2.x
  135. # See http://stackoverflow.com/a/9951851/35070
  136. subprocess_encoding = sys.getfilesystemencoding()
  137. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  138. else:
  139. subprocess_encoding = None
  140. if self.params.get('verbose', False):
  141. if subprocess_encoding:
  142. str_args = [
  143. a.decode(subprocess_encoding) if isinstance(a, bytes) else a
  144. for a in args]
  145. else:
  146. str_args = args
  147. try:
  148. import pipes
  149. shell_quote = lambda args: ' '.join(map(pipes.quote, str_args))
  150. except ImportError:
  151. shell_quote = repr
  152. self.to_screen('[debug] rtmpdump command line: ' + shell_quote(str_args))
  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