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.

203 lines
8.1 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 time
  6. from .common import FileDownloader
  7. from ..compat import compat_str
  8. from ..utils import (
  9. check_executable,
  10. encodeFilename,
  11. encodeArgument,
  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')
  91. page_url = info_dict.get('page_url')
  92. app = info_dict.get('app')
  93. play_path = info_dict.get('play_path')
  94. tc_url = info_dict.get('tc_url')
  95. flash_version = info_dict.get('flash_version')
  96. live = info_dict.get('rtmp_live', False)
  97. conn = info_dict.get('rtmp_conn')
  98. protocol = info_dict.get('rtmp_protocol')
  99. real_time = info_dict.get('rtmp_real_time', False)
  100. no_resume = info_dict.get('no_resume', False)
  101. continue_dl = self.params.get('continuedl', True)
  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 interrupted and resuming appears to be
  111. # possible. This is part of rtmpdump's normal usage, AFAIK.
  112. basic_args = [
  113. 'rtmpdump', '--verbose', '-r', url,
  114. '-o', tmpfilename]
  115. if player_url is not None:
  116. basic_args += ['--swfVfy', player_url]
  117. if page_url is not None:
  118. basic_args += ['--pageUrl', page_url]
  119. if app is not None:
  120. basic_args += ['--app', app]
  121. if play_path is not None:
  122. basic_args += ['--playpath', play_path]
  123. if tc_url is not None:
  124. basic_args += ['--tcUrl', tc_url]
  125. if test:
  126. basic_args += ['--stop', '1']
  127. if flash_version is not None:
  128. basic_args += ['--flashVer', flash_version]
  129. if live:
  130. basic_args += ['--live']
  131. if isinstance(conn, list):
  132. for entry in conn:
  133. basic_args += ['--conn', entry]
  134. elif isinstance(conn, compat_str):
  135. basic_args += ['--conn', conn]
  136. if protocol is not None:
  137. basic_args += ['--protocol', protocol]
  138. if real_time:
  139. basic_args += ['--realtime']
  140. args = basic_args
  141. if not no_resume and continue_dl and not live:
  142. args += ['--resume']
  143. if not live and continue_dl:
  144. args += ['--skip', '1']
  145. args = [encodeArgument(a) for a in args]
  146. self._debug_cmd(args, exe='rtmpdump')
  147. RD_SUCCESS = 0
  148. RD_FAILED = 1
  149. RD_INCOMPLETE = 2
  150. RD_NO_CONNECT = 3
  151. retval = run_rtmpdump(args)
  152. if retval == RD_NO_CONNECT:
  153. self.report_error('[rtmpdump] Could not connect to RTMP server.')
  154. return False
  155. while (retval == RD_INCOMPLETE or retval == RD_FAILED) and not test and not live:
  156. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  157. self.to_screen('[rtmpdump] %s bytes' % prevsize)
  158. time.sleep(5.0) # This seems to be needed
  159. args = basic_args + ['--resume']
  160. if retval == RD_FAILED:
  161. args += ['--skip', '1']
  162. args = [encodeArgument(a) for a in args]
  163. retval = run_rtmpdump(args)
  164. cursize = os.path.getsize(encodeFilename(tmpfilename))
  165. if prevsize == cursize and retval == RD_FAILED:
  166. break
  167. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  168. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  169. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  170. retval = RD_SUCCESS
  171. break
  172. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  173. fsize = os.path.getsize(encodeFilename(tmpfilename))
  174. self.to_screen('[rtmpdump] %s bytes' % fsize)
  175. self.try_rename(tmpfilename, filename)
  176. self._hook_progress({
  177. 'downloaded_bytes': fsize,
  178. 'total_bytes': fsize,
  179. 'filename': filename,
  180. 'status': 'finished',
  181. })
  182. return True
  183. else:
  184. self.to_stderr('\n')
  185. self.report_error('rtmpdump exited with code %d' % retval)
  186. return False