rtmp.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import os
  2. import re
  3. import subprocess
  4. import time
  5. from .common import FileDownloader
  6. from ..utils import (
  7. Popen,
  8. check_executable,
  9. encodeArgument,
  10. encodeFilename,
  11. get_exe_version,
  12. )
  13. def rtmpdump_version():
  14. return get_exe_version(
  15. 'rtmpdump', ['--help'], r'(?i)RTMPDump\s*v?([0-9a-zA-Z._-]+)')
  16. class RtmpFD(FileDownloader):
  17. def real_download(self, filename, info_dict):
  18. def run_rtmpdump(args):
  19. start = time.time()
  20. resume_percent = None
  21. resume_downloaded_data_len = None
  22. proc = Popen(args, stderr=subprocess.PIPE)
  23. cursor_in_new_line = True
  24. proc_stderr_closed = False
  25. try:
  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. }, info_dict)
  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. }, info_dict)
  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. if not cursor_in_new_line:
  86. self.to_screen('')
  87. return proc.wait()
  88. except BaseException: # Including KeyboardInterrupt
  89. proc.kill(timeout=None)
  90. raise
  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')
  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, 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(f'[rtmpdump] Downloaded {prevsize} bytes')
  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(f'[rtmpdump] Downloaded {fsize} bytes')
  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. }, info_dict)
  192. return True
  193. else:
  194. self.to_stderr('\n')
  195. self.report_error('rtmpdump exited with code %d' % retval)
  196. return False