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.

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