logo

youtube-dl

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

fragment.py (11804B)


  1. from __future__ import division, unicode_literals
  2. import os
  3. import time
  4. import json
  5. from .common import FileDownloader
  6. from .http import HttpFD
  7. from ..utils import (
  8. error_to_compat_str,
  9. encodeFilename,
  10. sanitize_open,
  11. sanitized_Request,
  12. )
  13. class HttpQuietDownloader(HttpFD):
  14. def to_screen(self, *args, **kargs):
  15. pass
  16. class FragmentFD(FileDownloader):
  17. """
  18. A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
  19. Available options:
  20. fragment_retries: Number of times to retry a fragment for HTTP error (DASH
  21. and hlsnative only)
  22. skip_unavailable_fragments:
  23. Skip unavailable fragments (DASH and hlsnative only)
  24. keep_fragments: Keep downloaded fragments on disk after downloading is
  25. finished
  26. For each incomplete fragment download youtube-dl keeps on disk a special
  27. bookkeeping file with download state and metadata (in future such files will
  28. be used for any incomplete download handled by youtube-dl). This file is
  29. used to properly handle resuming, check download file consistency and detect
  30. potential errors. The file has a .ytdl extension and represents a standard
  31. JSON file of the following format:
  32. extractor:
  33. Dictionary of extractor related data. TBD.
  34. downloader:
  35. Dictionary of downloader related data. May contain following data:
  36. current_fragment:
  37. Dictionary with current (being downloaded) fragment data:
  38. index: 0-based index of current fragment among all fragments
  39. fragment_count:
  40. Total count of fragments
  41. This feature is experimental and file format may change in future.
  42. """
  43. def report_retry_fragment(self, err, frag_index, count, retries):
  44. self.to_screen(
  45. '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
  46. % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
  47. def report_skip_fragment(self, frag_index):
  48. self.to_screen('[download] Skipping fragment %d...' % frag_index)
  49. def _prepare_url(self, info_dict, url):
  50. headers = info_dict.get('http_headers')
  51. return sanitized_Request(url, None, headers) if headers else url
  52. def _prepare_and_start_frag_download(self, ctx):
  53. self._prepare_frag_download(ctx)
  54. self._start_frag_download(ctx)
  55. @staticmethod
  56. def __do_ytdl_file(ctx):
  57. return ctx['live'] is not True and ctx['tmpfilename'] != '-'
  58. def _read_ytdl_file(self, ctx):
  59. assert 'ytdl_corrupt' not in ctx
  60. stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
  61. try:
  62. ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
  63. except Exception:
  64. ctx['ytdl_corrupt'] = True
  65. finally:
  66. stream.close()
  67. def _write_ytdl_file(self, ctx):
  68. frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
  69. downloader = {
  70. 'current_fragment': {
  71. 'index': ctx['fragment_index'],
  72. },
  73. }
  74. if ctx.get('fragment_count') is not None:
  75. downloader['fragment_count'] = ctx['fragment_count']
  76. frag_index_stream.write(json.dumps({'downloader': downloader}))
  77. frag_index_stream.close()
  78. def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
  79. fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
  80. fragment_info_dict = {
  81. 'url': frag_url,
  82. 'http_headers': headers or info_dict.get('http_headers'),
  83. }
  84. frag_resume_len = 0
  85. if ctx['dl'].params.get('continuedl', True):
  86. frag_resume_len = self.filesize_or_none(
  87. self.temp_name(fragment_filename))
  88. fragment_info_dict['frag_resume_len'] = frag_resume_len
  89. ctx['frag_resume_len'] = frag_resume_len or 0
  90. success = ctx['dl'].download(fragment_filename, fragment_info_dict)
  91. if not success:
  92. return False, None
  93. if fragment_info_dict.get('filetime'):
  94. ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
  95. down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
  96. ctx['fragment_filename_sanitized'] = frag_sanitized
  97. frag_content = down.read()
  98. down.close()
  99. return True, frag_content
  100. def _append_fragment(self, ctx, frag_content):
  101. try:
  102. ctx['dest_stream'].write(frag_content)
  103. ctx['dest_stream'].flush()
  104. finally:
  105. if self.__do_ytdl_file(ctx):
  106. self._write_ytdl_file(ctx)
  107. if not self.params.get('keep_fragments', False):
  108. os.remove(encodeFilename(ctx['fragment_filename_sanitized']))
  109. del ctx['fragment_filename_sanitized']
  110. def _prepare_frag_download(self, ctx):
  111. if not ctx.setdefault('live', False):
  112. total_frags_str = '%d' % ctx['total_frags']
  113. ad_frags = ctx.get('ad_frags', 0)
  114. if ad_frags:
  115. total_frags_str += ' (not including %d ad)' % ad_frags
  116. else:
  117. total_frags_str = 'unknown (live)'
  118. self.to_screen(
  119. '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
  120. self.report_destination(ctx['filename'])
  121. continuedl = self.params.get('continuedl', True)
  122. dl = HttpQuietDownloader(
  123. self.ydl,
  124. {
  125. 'continuedl': continuedl,
  126. 'quiet': True,
  127. 'noprogress': True,
  128. 'ratelimit': self.params.get('ratelimit'),
  129. 'retries': self.params.get('retries', 0),
  130. 'nopart': self.params.get('nopart', False),
  131. 'test': self.params.get('test', False),
  132. }
  133. )
  134. tmpfilename = self.temp_name(ctx['filename'])
  135. open_mode = 'wb'
  136. # Establish possible resume length
  137. resume_len = self.filesize_or_none(tmpfilename) or 0
  138. if resume_len > 0:
  139. open_mode = 'ab'
  140. # Should be initialized before ytdl file check
  141. ctx.update({
  142. 'tmpfilename': tmpfilename,
  143. 'fragment_index': 0,
  144. })
  145. if self.__do_ytdl_file(ctx):
  146. ytdl_file_exists = os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename'])))
  147. if continuedl and ytdl_file_exists:
  148. self._read_ytdl_file(ctx)
  149. is_corrupt = ctx.get('ytdl_corrupt') is True
  150. is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
  151. if is_corrupt or is_inconsistent:
  152. message = (
  153. '.ytdl file is corrupt' if is_corrupt else
  154. 'Inconsistent state of incomplete fragment download')
  155. self.report_warning(
  156. '%s. Restarting from the beginning...' % message)
  157. ctx['fragment_index'] = resume_len = 0
  158. if 'ytdl_corrupt' in ctx:
  159. del ctx['ytdl_corrupt']
  160. self._write_ytdl_file(ctx)
  161. else:
  162. if not continuedl:
  163. if ytdl_file_exists:
  164. self._read_ytdl_file(ctx)
  165. ctx['fragment_index'] = resume_len = 0
  166. self._write_ytdl_file(ctx)
  167. assert ctx['fragment_index'] == 0
  168. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  169. ctx.update({
  170. 'dl': dl,
  171. 'dest_stream': dest_stream,
  172. 'tmpfilename': tmpfilename,
  173. # Total complete fragments downloaded so far in bytes
  174. 'complete_frags_downloaded_bytes': resume_len,
  175. })
  176. def _start_frag_download(self, ctx):
  177. resume_len = ctx['complete_frags_downloaded_bytes']
  178. total_frags = ctx['total_frags']
  179. # This dict stores the download progress, it's updated by the progress
  180. # hook
  181. state = {
  182. 'status': 'downloading',
  183. 'downloaded_bytes': resume_len,
  184. 'fragment_index': ctx['fragment_index'],
  185. 'fragment_count': total_frags,
  186. 'filename': ctx['filename'],
  187. 'tmpfilename': ctx['tmpfilename'],
  188. }
  189. start = time.time()
  190. ctx.update({
  191. 'started': start,
  192. 'fragment_started': start,
  193. # Amount of fragment's bytes downloaded by the time of the previous
  194. # frag progress hook invocation
  195. 'prev_frag_downloaded_bytes': 0,
  196. })
  197. def frag_progress_hook(s):
  198. if s['status'] not in ('downloading', 'finished'):
  199. return
  200. if not total_frags and ctx.get('fragment_count'):
  201. state['fragment_count'] = ctx['fragment_count']
  202. time_now = time.time()
  203. state['elapsed'] = time_now - start
  204. frag_total_bytes = s.get('total_bytes') or 0
  205. if not ctx['live']:
  206. estimated_size = (
  207. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
  208. / (state['fragment_index'] + 1) * total_frags)
  209. state['total_bytes_estimate'] = estimated_size
  210. if s['status'] == 'finished':
  211. state['fragment_index'] += 1
  212. ctx['fragment_index'] = state['fragment_index']
  213. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  214. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  215. ctx['speed'] = state['speed'] = self.calc_speed(
  216. ctx['fragment_started'], time_now, frag_total_bytes)
  217. ctx['fragment_started'] = time.time()
  218. ctx['prev_frag_downloaded_bytes'] = 0
  219. else:
  220. frag_downloaded_bytes = s['downloaded_bytes']
  221. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  222. ctx['speed'] = state['speed'] = self.calc_speed(
  223. ctx['fragment_started'], time_now, frag_downloaded_bytes - ctx['frag_resume_len'])
  224. if not ctx['live']:
  225. state['eta'] = self.calc_eta(state['speed'], estimated_size - state['downloaded_bytes'])
  226. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  227. self._hook_progress(state)
  228. ctx['dl'].add_progress_hook(frag_progress_hook)
  229. return start
  230. def _finish_frag_download(self, ctx):
  231. ctx['dest_stream'].close()
  232. if self.__do_ytdl_file(ctx):
  233. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  234. if os.path.isfile(ytdl_filename):
  235. os.remove(ytdl_filename)
  236. elapsed = time.time() - ctx['started']
  237. if ctx['tmpfilename'] == '-':
  238. downloaded_bytes = ctx['complete_frags_downloaded_bytes']
  239. else:
  240. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  241. if self.params.get('updatetime', True):
  242. filetime = ctx.get('fragment_filetime')
  243. if filetime:
  244. try:
  245. os.utime(ctx['filename'], (time.time(), filetime))
  246. except Exception:
  247. pass
  248. downloaded_bytes = self.filesize_or_none(ctx['filename']) or 0
  249. self._hook_progress({
  250. 'downloaded_bytes': downloaded_bytes,
  251. 'total_bytes': downloaded_bytes,
  252. 'filename': ctx['filename'],
  253. 'status': 'finished',
  254. 'elapsed': elapsed,
  255. })