logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

rtmp.py (8990B)


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