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.

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