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.

214 lines
8.7 KiB

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. try:
  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. time_now = time.time()
  49. eta = self.calc_eta(start, time_now, 100 - resume_percent, percent - resume_percent)
  50. speed = self.calc_speed(start, time_now, downloaded_data_len - resume_downloaded_data_len)
  51. data_len = None
  52. if percent > 0:
  53. data_len = int(downloaded_data_len * 100 / percent)
  54. self._hook_progress({
  55. 'status': 'downloading',
  56. 'downloaded_bytes': downloaded_data_len,
  57. 'total_bytes_estimate': data_len,
  58. 'tmpfilename': tmpfilename,
  59. 'filename': filename,
  60. 'eta': eta,
  61. 'elapsed': time_now - start,
  62. 'speed': speed,
  63. })
  64. cursor_in_new_line = False
  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._hook_progress({
  73. 'downloaded_bytes': downloaded_data_len,
  74. 'tmpfilename': tmpfilename,
  75. 'filename': filename,
  76. 'status': 'downloading',
  77. 'elapsed': time_now - start,
  78. 'speed': speed,
  79. })
  80. cursor_in_new_line = False
  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. finally:
  87. proc.wait()
  88. if not cursor_in_new_line:
  89. self.to_screen('')
  90. return proc.returncode
  91. url = info_dict['url']
  92. player_url = info_dict.get('player_url')
  93. page_url = info_dict.get('page_url')
  94. app = info_dict.get('app')
  95. play_path = info_dict.get('play_path')
  96. tc_url = info_dict.get('tc_url')
  97. flash_version = info_dict.get('flash_version')
  98. live = info_dict.get('rtmp_live', False)
  99. conn = info_dict.get('rtmp_conn')
  100. protocol = info_dict.get('rtmp_protocol')
  101. real_time = info_dict.get('rtmp_real_time', False)
  102. no_resume = info_dict.get('no_resume', False)
  103. continue_dl = self.params.get('continuedl', True)
  104. self.report_destination(filename)
  105. tmpfilename = self.temp_name(filename)
  106. test = self.params.get('test', False)
  107. # Check for rtmpdump first
  108. if not check_executable('rtmpdump', ['-h']):
  109. self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install it.')
  110. return False
  111. # Download using rtmpdump. rtmpdump returns exit code 2 when
  112. # the connection was interrupted and resuming appears to be
  113. # possible. This is part of rtmpdump's normal usage, AFAIK.
  114. basic_args = [
  115. 'rtmpdump', '--verbose', '-r', url,
  116. '-o', tmpfilename]
  117. if player_url is not None:
  118. basic_args += ['--swfVfy', player_url]
  119. if page_url is not None:
  120. basic_args += ['--pageUrl', page_url]
  121. if app is not None:
  122. basic_args += ['--app', app]
  123. if play_path is not None:
  124. basic_args += ['--playpath', play_path]
  125. if tc_url is not None:
  126. basic_args += ['--tcUrl', tc_url]
  127. if test:
  128. basic_args += ['--stop', '1']
  129. if flash_version is not None:
  130. basic_args += ['--flashVer', flash_version]
  131. if live:
  132. basic_args += ['--live']
  133. if isinstance(conn, list):
  134. for entry in conn:
  135. basic_args += ['--conn', entry]
  136. elif isinstance(conn, compat_str):
  137. basic_args += ['--conn', conn]
  138. if protocol is not None:
  139. basic_args += ['--protocol', protocol]
  140. if real_time:
  141. basic_args += ['--realtime']
  142. args = basic_args
  143. if not no_resume and continue_dl and not live:
  144. args += ['--resume']
  145. if not live and continue_dl:
  146. args += ['--skip', '1']
  147. args = [encodeArgument(a) for a in args]
  148. self._debug_cmd(args, exe='rtmpdump')
  149. RD_SUCCESS = 0
  150. RD_FAILED = 1
  151. RD_INCOMPLETE = 2
  152. RD_NO_CONNECT = 3
  153. started = time.time()
  154. try:
  155. retval = run_rtmpdump(args)
  156. except KeyboardInterrupt:
  157. if not info_dict.get('is_live'):
  158. raise
  159. retval = RD_SUCCESS
  160. self.to_screen('\n[rtmpdump] Interrupted by user')
  161. if retval == RD_NO_CONNECT:
  162. self.report_error('[rtmpdump] Could not connect to RTMP server.')
  163. return False
  164. while retval in (RD_INCOMPLETE, RD_FAILED) and not test and not live:
  165. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  166. self.to_screen('[rtmpdump] Downloaded %s bytes' % prevsize)
  167. time.sleep(5.0) # This seems to be needed
  168. args = basic_args + ['--resume']
  169. if retval == RD_FAILED:
  170. args += ['--skip', '1']
  171. args = [encodeArgument(a) for a in args]
  172. retval = run_rtmpdump(args)
  173. cursize = os.path.getsize(encodeFilename(tmpfilename))
  174. if prevsize == cursize and retval == RD_FAILED:
  175. break
  176. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  177. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  178. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  179. retval = RD_SUCCESS
  180. break
  181. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  182. fsize = os.path.getsize(encodeFilename(tmpfilename))
  183. self.to_screen('[rtmpdump] Downloaded %s bytes' % fsize)
  184. self.try_rename(tmpfilename, filename)
  185. self._hook_progress({
  186. 'downloaded_bytes': fsize,
  187. 'total_bytes': fsize,
  188. 'filename': filename,
  189. 'status': 'finished',
  190. 'elapsed': time.time() - started,
  191. })
  192. return True
  193. else:
  194. self.to_stderr('\n')
  195. self.report_error('rtmpdump exited with code %d' % retval)
  196. return False