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.

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