rtmp.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. self.report_destination(filename)
  102. tmpfilename = self.temp_name(filename)
  103. test = self.params.get('test', False)
  104. # Check for rtmpdump first
  105. if not check_executable('rtmpdump', ['-h']):
  106. self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install it.')
  107. return False
  108. # Download using rtmpdump. rtmpdump returns exit code 2 when
  109. # the connection was interrumpted and resuming appears to be
  110. # possible. This is part of rtmpdump's normal usage, AFAIK.
  111. basic_args = ['rtmpdump', '--verbose', '-r', url, '-o', tmpfilename]
  112. if player_url is not None:
  113. basic_args += ['--swfVfy', player_url]
  114. if page_url is not None:
  115. basic_args += ['--pageUrl', page_url]
  116. if app is not None:
  117. basic_args += ['--app', app]
  118. if play_path is not None:
  119. basic_args += ['--playpath', play_path]
  120. if tc_url is not None:
  121. basic_args += ['--tcUrl', url]
  122. if test:
  123. basic_args += ['--stop', '1']
  124. if flash_version is not None:
  125. basic_args += ['--flashVer', flash_version]
  126. if live:
  127. basic_args += ['--live']
  128. if isinstance(conn, list):
  129. for entry in conn:
  130. basic_args += ['--conn', entry]
  131. elif isinstance(conn, compat_str):
  132. basic_args += ['--conn', conn]
  133. if protocol is not None:
  134. basic_args += ['--protocol', protocol]
  135. if not no_resume:
  136. basic_args += ['--resume']
  137. args = basic_args + [[], ['--skip', '1']][not live and self.params.get('continuedl', False)]
  138. if sys.platform == 'win32' and sys.version_info < (3, 0):
  139. # Windows subprocess module does not actually support Unicode
  140. # on Python 2.x
  141. # See http://stackoverflow.com/a/9951851/35070
  142. subprocess_encoding = sys.getfilesystemencoding()
  143. args = [a.encode(subprocess_encoding, 'ignore') for a in args]
  144. else:
  145. subprocess_encoding = None
  146. self._debug_cmd(args, subprocess_encoding, 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. retval = run_rtmpdump(basic_args + ['-e'] + [[], ['-k', '1']][retval == RD_FAILED])
  160. cursize = os.path.getsize(encodeFilename(tmpfilename))
  161. if prevsize == cursize and retval == RD_FAILED:
  162. break
  163. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  164. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  165. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  166. retval = RD_SUCCESS
  167. break
  168. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  169. fsize = os.path.getsize(encodeFilename(tmpfilename))
  170. self.to_screen('[rtmpdump] %s bytes' % fsize)
  171. self.try_rename(tmpfilename, filename)
  172. self._hook_progress({
  173. 'downloaded_bytes': fsize,
  174. 'total_bytes': fsize,
  175. 'filename': filename,
  176. 'status': 'finished',
  177. })
  178. return True
  179. else:
  180. self.to_stderr('\n')
  181. self.report_error('rtmpdump exited with code %d' % retval)
  182. return False