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.

243 lines
9.0 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. self.to_screen(
  99. '[%s] Total fragments: %s'
  100. % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
  101. self.report_destination(ctx['filename'])
  102. dl = HttpQuietDownloader(
  103. self.ydl,
  104. {
  105. 'continuedl': True,
  106. 'quiet': True,
  107. 'noprogress': True,
  108. 'ratelimit': self.params.get('ratelimit'),
  109. 'retries': self.params.get('retries', 0),
  110. 'nopart': self.params.get('nopart', False),
  111. 'test': self.params.get('test', False),
  112. }
  113. )
  114. tmpfilename = self.temp_name(ctx['filename'])
  115. open_mode = 'wb'
  116. resume_len = 0
  117. # Establish possible resume length
  118. if os.path.isfile(encodeFilename(tmpfilename)):
  119. open_mode = 'ab'
  120. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  121. # Should be initialized before ytdl file check
  122. ctx.update({
  123. 'tmpfilename': tmpfilename,
  124. 'fragment_index': 0,
  125. })
  126. if self.__do_ytdl_file(ctx):
  127. if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
  128. self._read_ytdl_file(ctx)
  129. else:
  130. self._write_ytdl_file(ctx)
  131. if ctx['fragment_index'] > 0:
  132. assert resume_len > 0
  133. else:
  134. assert resume_len == 0
  135. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  136. ctx.update({
  137. 'dl': dl,
  138. 'dest_stream': dest_stream,
  139. 'tmpfilename': tmpfilename,
  140. # Total complete fragments downloaded so far in bytes
  141. 'complete_frags_downloaded_bytes': resume_len,
  142. })
  143. def _start_frag_download(self, ctx):
  144. total_frags = ctx['total_frags']
  145. # This dict stores the download progress, it's updated by the progress
  146. # hook
  147. state = {
  148. 'status': 'downloading',
  149. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  150. 'fragment_index': ctx['fragment_index'],
  151. 'fragment_count': total_frags,
  152. 'filename': ctx['filename'],
  153. 'tmpfilename': ctx['tmpfilename'],
  154. }
  155. start = time.time()
  156. ctx.update({
  157. 'started': start,
  158. # Amount of fragment's bytes downloaded by the time of the previous
  159. # frag progress hook invocation
  160. 'prev_frag_downloaded_bytes': 0,
  161. })
  162. def frag_progress_hook(s):
  163. if s['status'] not in ('downloading', 'finished'):
  164. return
  165. time_now = time.time()
  166. state['elapsed'] = time_now - start
  167. frag_total_bytes = s.get('total_bytes') or 0
  168. if not ctx['live']:
  169. estimated_size = (
  170. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  171. (state['fragment_index'] + 1) * total_frags)
  172. state['total_bytes_estimate'] = estimated_size
  173. if s['status'] == 'finished':
  174. state['fragment_index'] += 1
  175. ctx['fragment_index'] = state['fragment_index']
  176. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  177. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  178. ctx['prev_frag_downloaded_bytes'] = 0
  179. else:
  180. frag_downloaded_bytes = s['downloaded_bytes']
  181. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  182. if not ctx['live']:
  183. state['eta'] = self.calc_eta(
  184. start, time_now, estimated_size,
  185. state['downloaded_bytes'])
  186. state['speed'] = s.get('speed') or ctx.get('speed')
  187. ctx['speed'] = state['speed']
  188. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  189. self._hook_progress(state)
  190. ctx['dl'].add_progress_hook(frag_progress_hook)
  191. return start
  192. def _finish_frag_download(self, ctx):
  193. ctx['dest_stream'].close()
  194. if self.__do_ytdl_file(ctx):
  195. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  196. if os.path.isfile(ytdl_filename):
  197. os.remove(ytdl_filename)
  198. elapsed = time.time() - ctx['started']
  199. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  200. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  201. self._hook_progress({
  202. 'downloaded_bytes': fsize,
  203. 'total_bytes': fsize,
  204. 'filename': ctx['filename'],
  205. 'status': 'finished',
  206. 'elapsed': elapsed,
  207. })