rtmp.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. get_exe_version,
  11. )
  12. def rtmpdump_version():
  13. return get_exe_version(
  14. 'rtmpdump', ['--help'], r'(?i)RTMPDump\s*v?([0-9a-zA-Z._-]+)')
  15. class RtmpFD(FileDownloader):
  16. def real_download(self, filename, info_dict):
  17. def run_rtmpdump(args):
  18. start = time.time()
  19. resume_percent = None
  20. resume_downloaded_data_len = None
  21. proc = Popen(args, stderr=subprocess.PIPE)
  22. cursor_in_new_line = True
  23. proc_stderr_closed = False
  24. try:
  25. while not proc_stderr_closed:
  26. # read line from stderr
  27. line = ''
  28. while True:
  29. char = proc.stderr.read(1)
  30. if not char:
  31. proc_stderr_closed = True
  32. break
  33. if char in [b'\r', b'\n']:
  34. break
  35. line += char.decode('ascii', 'replace')
  36. if not line:
  37. # proc_stderr_closed is True
  38. continue
  39. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec \(([0-9]{1,2}\.[0-9])%\)', line)
  40. if mobj:
  41. downloaded_data_len = int(float(mobj.group(1)) * 1024)
  42. percent = float(mobj.group(2))
  43. if not resume_percent:
  44. resume_percent = percent
  45. resume_downloaded_data_len = downloaded_data_len
  46. time_now = time.time()
  47. eta = self.calc_eta(start, time_now, 100 - resume_percent, percent - resume_percent)
  48. speed = self.calc_speed(start, time_now, downloaded_data_len - resume_downloaded_data_len)
  49. data_len = None
  50. if percent > 0:
  51. data_len = int(downloaded_data_len * 100 / percent)
  52. self._hook_progress({
  53. 'status': 'downloading',
  54. 'downloaded_bytes': downloaded_data_len,
  55. 'total_bytes_estimate': data_len,
  56. 'tmpfilename': tmpfilename,
  57. 'filename': filename,
  58. 'eta': eta,
  59. 'elapsed': time_now - start,
  60. 'speed': speed,
  61. }, info_dict)
  62. cursor_in_new_line = False
  63. else:
  64. # no percent for live streams
  65. mobj = re.search(r'([0-9]+\.[0-9]{3}) kB / [0-9]+\.[0-9]{2} sec', line)
  66. if mobj:
  67. downloaded_data_len = int(float(mobj.group(1)) * 1024)
  68. time_now = time.time()
  69. speed = self.calc_speed(start, time_now, downloaded_data_len)
  70. self._hook_progress({
  71. 'downloaded_bytes': downloaded_data_len,
  72. 'tmpfilename': tmpfilename,
  73. 'filename': filename,
  74. 'status': 'downloading',
  75. 'elapsed': time_now - start,
  76. 'speed': speed,
  77. }, info_dict)
  78. cursor_in_new_line = False
  79. elif self.params.get('verbose', False):
  80. if not cursor_in_new_line:
  81. self.to_screen('')
  82. cursor_in_new_line = True
  83. self.to_screen('[rtmpdump] ' + line)
  84. if not cursor_in_new_line:
  85. self.to_screen('')
  86. return proc.wait()
  87. except BaseException: # Including KeyboardInterrupt
  88. proc.kill(timeout=None)
  89. raise
  90. url = info_dict['url']
  91. player_url = info_dict.get('player_url')
  92. page_url = info_dict.get('page_url')
  93. app = info_dict.get('app')
  94. play_path = info_dict.get('play_path')
  95. tc_url = info_dict.get('tc_url')
  96. flash_version = info_dict.get('flash_version')
  97. live = info_dict.get('rtmp_live', False)
  98. conn = info_dict.get('rtmp_conn')
  99. protocol = info_dict.get('rtmp_protocol')
  100. real_time = info_dict.get('rtmp_real_time', False)
  101. no_resume = info_dict.get('no_resume', False)
  102. continue_dl = self.params.get('continuedl', True)
  103. self.report_destination(filename)
  104. tmpfilename = self.temp_name(filename)
  105. test = self.params.get('test', False)
  106. # Check for rtmpdump first
  107. if not check_executable('rtmpdump', ['-h']):
  108. self.report_error('RTMP download detected but "rtmpdump" could not be run. Please install')
  109. return False
  110. # Download using rtmpdump. rtmpdump returns exit code 2 when
  111. # the connection was interrupted and resuming appears to be
  112. # possible. This is part of rtmpdump's normal usage, AFAIK.
  113. basic_args = [
  114. 'rtmpdump', '--verbose', '-r', url,
  115. '-o', tmpfilename]
  116. if player_url is not None:
  117. basic_args += ['--swfVfy', player_url]
  118. if page_url is not None:
  119. basic_args += ['--pageUrl', page_url]
  120. if app is not None:
  121. basic_args += ['--app', app]
  122. if play_path is not None:
  123. basic_args += ['--playpath', play_path]
  124. if tc_url is not None:
  125. basic_args += ['--tcUrl', tc_url]
  126. if test:
  127. basic_args += ['--stop', '1']
  128. if flash_version is not None:
  129. basic_args += ['--flashVer', flash_version]
  130. if live:
  131. basic_args += ['--live']
  132. if isinstance(conn, list):
  133. for entry in conn:
  134. basic_args += ['--conn', entry]
  135. elif isinstance(conn, str):
  136. basic_args += ['--conn', conn]
  137. if protocol is not None:
  138. basic_args += ['--protocol', protocol]
  139. if real_time:
  140. basic_args += ['--realtime']
  141. args = basic_args
  142. if not no_resume and continue_dl and not live:
  143. args += ['--resume']
  144. if not live and continue_dl:
  145. args += ['--skip', '1']
  146. args = [encodeArgument(a) for a in args]
  147. self._debug_cmd(args, exe='rtmpdump')
  148. RD_SUCCESS = 0
  149. RD_FAILED = 1
  150. RD_INCOMPLETE = 2
  151. RD_NO_CONNECT = 3
  152. started = time.time()
  153. try:
  154. retval = run_rtmpdump(args)
  155. except KeyboardInterrupt:
  156. if not info_dict.get('is_live'):
  157. raise
  158. retval = RD_SUCCESS
  159. self.to_screen('\n[rtmpdump] Interrupted by user')
  160. if retval == RD_NO_CONNECT:
  161. self.report_error('[rtmpdump] Could not connect to RTMP server.')
  162. return False
  163. while retval in (RD_INCOMPLETE, RD_FAILED) and not test and not live:
  164. prevsize = os.path.getsize(tmpfilename)
  165. self.to_screen(f'[rtmpdump] Downloaded {prevsize} bytes')
  166. time.sleep(5.0) # This seems to be needed
  167. args = [*basic_args, '--resume']
  168. if retval == RD_FAILED:
  169. args += ['--skip', '1']
  170. args = [encodeArgument(a) for a in args]
  171. retval = run_rtmpdump(args)
  172. cursize = os.path.getsize(tmpfilename)
  173. if prevsize == cursize and retval == RD_FAILED:
  174. break
  175. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  176. if prevsize == cursize and retval == RD_INCOMPLETE and cursize > 1024:
  177. self.to_screen('[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  178. retval = RD_SUCCESS
  179. break
  180. if retval == RD_SUCCESS or (test and retval == RD_INCOMPLETE):
  181. fsize = os.path.getsize(tmpfilename)
  182. self.to_screen(f'[rtmpdump] Downloaded {fsize} bytes')
  183. self.try_rename(tmpfilename, filename)
  184. self._hook_progress({
  185. 'downloaded_bytes': fsize,
  186. 'total_bytes': fsize,
  187. 'filename': filename,
  188. 'status': 'finished',
  189. 'elapsed': time.time() - started,
  190. }, info_dict)
  191. return True
  192. else:
  193. self.to_stderr('\n')
  194. self.report_error('rtmpdump exited with code %d' % retval)
  195. return False