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.

241 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. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  134. ctx.update({
  135. 'dl': dl,
  136. 'dest_stream': dest_stream,
  137. 'tmpfilename': tmpfilename,
  138. # Total complete fragments downloaded so far in bytes
  139. 'complete_frags_downloaded_bytes': resume_len,
  140. })
  141. def _start_frag_download(self, ctx):
  142. total_frags = ctx['total_frags']
  143. # This dict stores the download progress, it's updated by the progress
  144. # hook
  145. state = {
  146. 'status': 'downloading',
  147. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  148. 'fragment_index': ctx['fragment_index'],
  149. 'fragment_count': total_frags,
  150. 'filename': ctx['filename'],
  151. 'tmpfilename': ctx['tmpfilename'],
  152. }
  153. start = time.time()
  154. ctx.update({
  155. 'started': start,
  156. # Amount of fragment's bytes downloaded by the time of the previous
  157. # frag progress hook invocation
  158. 'prev_frag_downloaded_bytes': 0,
  159. })
  160. def frag_progress_hook(s):
  161. if s['status'] not in ('downloading', 'finished'):
  162. return
  163. time_now = time.time()
  164. state['elapsed'] = time_now - start
  165. frag_total_bytes = s.get('total_bytes') or 0
  166. if not ctx['live']:
  167. estimated_size = (
  168. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  169. (state['fragment_index'] + 1) * total_frags)
  170. state['total_bytes_estimate'] = estimated_size
  171. if s['status'] == 'finished':
  172. state['fragment_index'] += 1
  173. ctx['fragment_index'] = state['fragment_index']
  174. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  175. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  176. ctx['prev_frag_downloaded_bytes'] = 0
  177. else:
  178. frag_downloaded_bytes = s['downloaded_bytes']
  179. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  180. if not ctx['live']:
  181. state['eta'] = self.calc_eta(
  182. start, time_now, estimated_size,
  183. state['downloaded_bytes'])
  184. state['speed'] = s.get('speed') or ctx.get('speed')
  185. ctx['speed'] = state['speed']
  186. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  187. self._hook_progress(state)
  188. ctx['dl'].add_progress_hook(frag_progress_hook)
  189. return start
  190. def _finish_frag_download(self, ctx):
  191. ctx['dest_stream'].close()
  192. if self.__do_ytdl_file(ctx):
  193. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  194. if os.path.isfile(ytdl_filename):
  195. os.remove(ytdl_filename)
  196. elapsed = time.time() - ctx['started']
  197. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  198. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  199. self._hook_progress({
  200. 'downloaded_bytes': fsize,
  201. 'total_bytes': fsize,
  202. 'filename': ctx['filename'],
  203. 'status': 'finished',
  204. 'elapsed': elapsed,
  205. })