fragment.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 yt-dlp 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 yt-dlp). 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 not ctx['live'] and not 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, request_data=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. 'request_data': request_data,
  84. }
  85. success = ctx['dl'].download(fragment_filename, fragment_info_dict)
  86. if not success:
  87. return False, None
  88. if fragment_info_dict.get('filetime'):
  89. ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
  90. down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
  91. ctx['fragment_filename_sanitized'] = frag_sanitized
  92. frag_content = down.read()
  93. down.close()
  94. return True, frag_content
  95. def _append_fragment(self, ctx, frag_content):
  96. try:
  97. ctx['dest_stream'].write(frag_content)
  98. ctx['dest_stream'].flush()
  99. finally:
  100. if self.__do_ytdl_file(ctx):
  101. self._write_ytdl_file(ctx)
  102. if not self.params.get('keep_fragments', False):
  103. os.remove(encodeFilename(ctx['fragment_filename_sanitized']))
  104. del ctx['fragment_filename_sanitized']
  105. def _prepare_frag_download(self, ctx):
  106. if 'live' not in ctx:
  107. ctx['live'] = False
  108. if not ctx['live']:
  109. total_frags_str = '%d' % ctx['total_frags']
  110. ad_frags = ctx.get('ad_frags', 0)
  111. if ad_frags:
  112. total_frags_str += ' (not including %d ad)' % ad_frags
  113. else:
  114. total_frags_str = 'unknown (live)'
  115. self.to_screen(
  116. '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
  117. self.report_destination(ctx['filename'])
  118. dl = HttpQuietDownloader(
  119. self.ydl,
  120. {
  121. 'continuedl': True,
  122. 'quiet': True,
  123. 'noprogress': True,
  124. 'ratelimit': self.params.get('ratelimit'),
  125. 'retries': self.params.get('retries', 0),
  126. 'nopart': self.params.get('nopart', False),
  127. 'test': self.params.get('test', False),
  128. }
  129. )
  130. tmpfilename = self.temp_name(ctx['filename'])
  131. open_mode = 'wb'
  132. resume_len = 0
  133. # Establish possible resume length
  134. if os.path.isfile(encodeFilename(tmpfilename)):
  135. open_mode = 'ab'
  136. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  137. # Should be initialized before ytdl file check
  138. ctx.update({
  139. 'tmpfilename': tmpfilename,
  140. 'fragment_index': 0,
  141. })
  142. if self.__do_ytdl_file(ctx):
  143. if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
  144. self._read_ytdl_file(ctx)
  145. is_corrupt = ctx.get('ytdl_corrupt') is True
  146. is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
  147. if is_corrupt or is_inconsistent:
  148. message = (
  149. '.ytdl file is corrupt' if is_corrupt else
  150. 'Inconsistent state of incomplete fragment download')
  151. self.report_warning(
  152. '%s. Restarting from the beginning ...' % message)
  153. ctx['fragment_index'] = resume_len = 0
  154. if 'ytdl_corrupt' in ctx:
  155. del ctx['ytdl_corrupt']
  156. self._write_ytdl_file(ctx)
  157. else:
  158. self._write_ytdl_file(ctx)
  159. assert ctx['fragment_index'] == 0
  160. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  161. ctx.update({
  162. 'dl': dl,
  163. 'dest_stream': dest_stream,
  164. 'tmpfilename': tmpfilename,
  165. # Total complete fragments downloaded so far in bytes
  166. 'complete_frags_downloaded_bytes': resume_len,
  167. })
  168. def _start_frag_download(self, ctx):
  169. resume_len = ctx['complete_frags_downloaded_bytes']
  170. total_frags = ctx['total_frags']
  171. # This dict stores the download progress, it's updated by the progress
  172. # hook
  173. state = {
  174. 'status': 'downloading',
  175. 'downloaded_bytes': resume_len,
  176. 'fragment_index': ctx['fragment_index'],
  177. 'fragment_count': total_frags,
  178. 'filename': ctx['filename'],
  179. 'tmpfilename': ctx['tmpfilename'],
  180. }
  181. start = time.time()
  182. ctx.update({
  183. 'started': start,
  184. # Amount of fragment's bytes downloaded by the time of the previous
  185. # frag progress hook invocation
  186. 'prev_frag_downloaded_bytes': 0,
  187. })
  188. def frag_progress_hook(s):
  189. if s['status'] not in ('downloading', 'finished'):
  190. return
  191. time_now = time.time()
  192. state['elapsed'] = time_now - start
  193. frag_total_bytes = s.get('total_bytes') or 0
  194. if not ctx['live']:
  195. estimated_size = (
  196. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
  197. / (state['fragment_index'] + 1) * total_frags)
  198. state['total_bytes_estimate'] = estimated_size
  199. if s['status'] == 'finished':
  200. state['fragment_index'] += 1
  201. ctx['fragment_index'] = state['fragment_index']
  202. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  203. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  204. ctx['prev_frag_downloaded_bytes'] = 0
  205. else:
  206. frag_downloaded_bytes = s['downloaded_bytes']
  207. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  208. if not ctx['live']:
  209. state['eta'] = self.calc_eta(
  210. start, time_now, estimated_size - resume_len,
  211. state['downloaded_bytes'] - resume_len)
  212. state['speed'] = s.get('speed') or ctx.get('speed')
  213. ctx['speed'] = state['speed']
  214. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  215. self._hook_progress(state)
  216. ctx['dl'].add_progress_hook(frag_progress_hook)
  217. return start
  218. def _finish_frag_download(self, ctx):
  219. ctx['dest_stream'].close()
  220. if self.__do_ytdl_file(ctx):
  221. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  222. if os.path.isfile(ytdl_filename):
  223. os.remove(ytdl_filename)
  224. elapsed = time.time() - ctx['started']
  225. if ctx['tmpfilename'] == '-':
  226. downloaded_bytes = ctx['complete_frags_downloaded_bytes']
  227. else:
  228. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  229. if self.params.get('updatetime', True):
  230. filetime = ctx.get('fragment_filetime')
  231. if filetime:
  232. try:
  233. os.utime(ctx['filename'], (time.time(), filetime))
  234. except Exception:
  235. pass
  236. downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))
  237. self._hook_progress({
  238. 'downloaded_bytes': downloaded_bytes,
  239. 'total_bytes': downloaded_bytes,
  240. 'filename': ctx['filename'],
  241. 'status': 'finished',
  242. 'elapsed': elapsed,
  243. })
  244. def _prepare_external_frag_download(self, ctx):
  245. if 'live' not in ctx:
  246. ctx['live'] = False
  247. if not ctx['live']:
  248. total_frags_str = '%d' % ctx['total_frags']
  249. ad_frags = ctx.get('ad_frags', 0)
  250. if ad_frags:
  251. total_frags_str += ' (not including %d ad)' % ad_frags
  252. else:
  253. total_frags_str = 'unknown (live)'
  254. self.to_screen(
  255. '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
  256. tmpfilename = self.temp_name(ctx['filename'])
  257. # Should be initialized before ytdl file check
  258. ctx.update({
  259. 'tmpfilename': tmpfilename,
  260. 'fragment_index': 0,
  261. })