fragment.py 11 KB

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