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.

144 lines
5.1 KiB

  1. from __future__ import division, unicode_literals
  2. import os
  3. import time
  4. from .common import FileDownloader
  5. from .http import HttpFD
  6. from ..utils import (
  7. error_to_compat_str,
  8. encodeFilename,
  9. sanitize_open,
  10. sanitized_Request,
  11. )
  12. class HttpQuietDownloader(HttpFD):
  13. def to_screen(self, *args, **kargs):
  14. pass
  15. class FragmentFD(FileDownloader):
  16. """
  17. A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
  18. Available options:
  19. fragment_retries: Number of times to retry a fragment for HTTP error (DASH
  20. and hlsnative only)
  21. skip_unavailable_fragments:
  22. Skip unavailable fragments (DASH and hlsnative only)
  23. """
  24. def report_retry_fragment(self, err, fragment_name, count, retries):
  25. self.to_screen(
  26. '[download] Got server HTTP error: %s. Retrying fragment %s (attempt %d of %s)...'
  27. % (error_to_compat_str(err), fragment_name, count, self.format_retries(retries)))
  28. def report_skip_fragment(self, fragment_name):
  29. self.to_screen('[download] Skipping fragment %s...' % fragment_name)
  30. def _prepare_url(self, info_dict, url):
  31. headers = info_dict.get('http_headers')
  32. return sanitized_Request(url, None, headers) if headers else url
  33. def _prepare_and_start_frag_download(self, ctx):
  34. self._prepare_frag_download(ctx)
  35. self._start_frag_download(ctx)
  36. def _prepare_frag_download(self, ctx):
  37. if 'live' not in ctx:
  38. ctx['live'] = False
  39. self.to_screen(
  40. '[%s] Total fragments: %s'
  41. % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
  42. self.report_destination(ctx['filename'])
  43. dl = HttpQuietDownloader(
  44. self.ydl,
  45. {
  46. 'continuedl': True,
  47. 'quiet': True,
  48. 'noprogress': True,
  49. 'ratelimit': self.params.get('ratelimit'),
  50. 'retries': self.params.get('retries', 0),
  51. 'test': self.params.get('test', False),
  52. }
  53. )
  54. tmpfilename = self.temp_name(ctx['filename'])
  55. dest_stream, tmpfilename = sanitize_open(tmpfilename, 'wb')
  56. ctx.update({
  57. 'dl': dl,
  58. 'dest_stream': dest_stream,
  59. 'tmpfilename': tmpfilename,
  60. })
  61. def _start_frag_download(self, ctx):
  62. total_frags = ctx['total_frags']
  63. # This dict stores the download progress, it's updated by the progress
  64. # hook
  65. state = {
  66. 'status': 'downloading',
  67. 'downloaded_bytes': 0,
  68. 'frag_index': 0,
  69. 'frag_count': total_frags,
  70. 'filename': ctx['filename'],
  71. 'tmpfilename': ctx['tmpfilename'],
  72. }
  73. start = time.time()
  74. ctx.update({
  75. 'started': start,
  76. # Total complete fragments downloaded so far in bytes
  77. 'complete_frags_downloaded_bytes': 0,
  78. # Amount of fragment's bytes downloaded by the time of the previous
  79. # frag progress hook invocation
  80. 'prev_frag_downloaded_bytes': 0,
  81. })
  82. def frag_progress_hook(s):
  83. if s['status'] not in ('downloading', 'finished'):
  84. return
  85. time_now = time.time()
  86. state['elapsed'] = time_now - start
  87. frag_total_bytes = s.get('total_bytes') or 0
  88. if not ctx['live']:
  89. estimated_size = (
  90. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  91. (state['frag_index'] + 1) * total_frags)
  92. state['total_bytes_estimate'] = estimated_size
  93. if s['status'] == 'finished':
  94. state['frag_index'] += 1
  95. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  96. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  97. ctx['prev_frag_downloaded_bytes'] = 0
  98. else:
  99. frag_downloaded_bytes = s['downloaded_bytes']
  100. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  101. if not ctx['live']:
  102. state['eta'] = self.calc_eta(
  103. start, time_now, estimated_size,
  104. state['downloaded_bytes'])
  105. state['speed'] = s.get('speed') or ctx.get('speed')
  106. ctx['speed'] = state['speed']
  107. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  108. self._hook_progress(state)
  109. ctx['dl'].add_progress_hook(frag_progress_hook)
  110. return start
  111. def _finish_frag_download(self, ctx):
  112. ctx['dest_stream'].close()
  113. elapsed = time.time() - ctx['started']
  114. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  115. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  116. self._hook_progress({
  117. 'downloaded_bytes': fsize,
  118. 'total_bytes': fsize,
  119. 'filename': ctx['filename'],
  120. 'status': 'finished',
  121. 'elapsed': elapsed,
  122. })