You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

252 lines
9.5 KiB

  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. stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
  60. ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
  61. stream.close()
  62. def _write_ytdl_file(self, ctx):
  63. frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
  64. downloader = {
  65. 'current_fragment': {
  66. 'index': ctx['fragment_index'],
  67. },
  68. }
  69. if ctx.get('fragment_count') is not None:
  70. downloader['fragment_count'] = ctx['fragment_count']
  71. frag_index_stream.write(json.dumps({'downloader': downloader}))
  72. frag_index_stream.close()
  73. def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
  74. fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
  75. success = ctx['dl'].download(fragment_filename, {
  76. 'url': frag_url,
  77. 'http_headers': headers or info_dict.get('http_headers'),
  78. })
  79. if not success:
  80. return False, None
  81. down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
  82. ctx['fragment_filename_sanitized'] = frag_sanitized
  83. frag_content = down.read()
  84. down.close()
  85. return True, frag_content
  86. def _append_fragment(self, ctx, frag_content):
  87. try:
  88. ctx['dest_stream'].write(frag_content)
  89. finally:
  90. if self.__do_ytdl_file(ctx):
  91. self._write_ytdl_file(ctx)
  92. if not self.params.get('keep_fragments', False):
  93. os.remove(ctx['fragment_filename_sanitized'])
  94. del ctx['fragment_filename_sanitized']
  95. def _prepare_frag_download(self, ctx):
  96. if 'live' not in ctx:
  97. ctx['live'] = False
  98. if not ctx['live']:
  99. total_frags_str = '%d' % ctx['total_frags']
  100. ad_frags = ctx.get('ad_frags', 0)
  101. if ad_frags:
  102. total_frags_str += ' (not including %d ad)' % ad_frags
  103. else:
  104. total_frags_str = 'unknown (live)'
  105. self.to_screen(
  106. '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
  107. self.report_destination(ctx['filename'])
  108. dl = HttpQuietDownloader(
  109. self.ydl,
  110. {
  111. 'continuedl': True,
  112. 'quiet': True,
  113. 'noprogress': True,
  114. 'ratelimit': self.params.get('ratelimit'),
  115. 'retries': self.params.get('retries', 0),
  116. 'nopart': self.params.get('nopart', False),
  117. 'test': self.params.get('test', False),
  118. }
  119. )
  120. tmpfilename = self.temp_name(ctx['filename'])
  121. open_mode = 'wb'
  122. resume_len = 0
  123. # Establish possible resume length
  124. if os.path.isfile(encodeFilename(tmpfilename)):
  125. open_mode = 'ab'
  126. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  127. # Should be initialized before ytdl file check
  128. ctx.update({
  129. 'tmpfilename': tmpfilename,
  130. 'fragment_index': 0,
  131. })
  132. if self.__do_ytdl_file(ctx):
  133. if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
  134. self._read_ytdl_file(ctx)
  135. if ctx['fragment_index'] > 0 and resume_len == 0:
  136. self.report_warning(
  137. 'Inconsistent state of incomplete fragment download. '
  138. 'Restarting from the beginning...')
  139. ctx['fragment_index'] = resume_len = 0
  140. self._write_ytdl_file(ctx)
  141. else:
  142. self._write_ytdl_file(ctx)
  143. assert ctx['fragment_index'] == 0
  144. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  145. ctx.update({
  146. 'dl': dl,
  147. 'dest_stream': dest_stream,
  148. 'tmpfilename': tmpfilename,
  149. # Total complete fragments downloaded so far in bytes
  150. 'complete_frags_downloaded_bytes': resume_len,
  151. })
  152. def _start_frag_download(self, ctx):
  153. total_frags = ctx['total_frags']
  154. # This dict stores the download progress, it's updated by the progress
  155. # hook
  156. state = {
  157. 'status': 'downloading',
  158. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  159. 'fragment_index': ctx['fragment_index'],
  160. 'fragment_count': total_frags,
  161. 'filename': ctx['filename'],
  162. 'tmpfilename': ctx['tmpfilename'],
  163. }
  164. start = time.time()
  165. ctx.update({
  166. 'started': start,
  167. # Amount of fragment's bytes downloaded by the time of the previous
  168. # frag progress hook invocation
  169. 'prev_frag_downloaded_bytes': 0,
  170. })
  171. def frag_progress_hook(s):
  172. if s['status'] not in ('downloading', 'finished'):
  173. return
  174. time_now = time.time()
  175. state['elapsed'] = time_now - start
  176. frag_total_bytes = s.get('total_bytes') or 0
  177. if not ctx['live']:
  178. estimated_size = (
  179. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  180. (state['fragment_index'] + 1) * total_frags)
  181. state['total_bytes_estimate'] = estimated_size
  182. if s['status'] == 'finished':
  183. state['fragment_index'] += 1
  184. ctx['fragment_index'] = state['fragment_index']
  185. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  186. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  187. ctx['prev_frag_downloaded_bytes'] = 0
  188. else:
  189. frag_downloaded_bytes = s['downloaded_bytes']
  190. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  191. if not ctx['live']:
  192. state['eta'] = self.calc_eta(
  193. start, time_now, estimated_size,
  194. state['downloaded_bytes'])
  195. state['speed'] = s.get('speed') or ctx.get('speed')
  196. ctx['speed'] = state['speed']
  197. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  198. self._hook_progress(state)
  199. ctx['dl'].add_progress_hook(frag_progress_hook)
  200. return start
  201. def _finish_frag_download(self, ctx):
  202. ctx['dest_stream'].close()
  203. if self.__do_ytdl_file(ctx):
  204. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  205. if os.path.isfile(ytdl_filename):
  206. os.remove(ytdl_filename)
  207. elapsed = time.time() - ctx['started']
  208. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  209. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  210. self._hook_progress({
  211. 'downloaded_bytes': fsize,
  212. 'total_bytes': fsize,
  213. 'filename': ctx['filename'],
  214. 'status': 'finished',
  215. 'elapsed': elapsed,
  216. })