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.

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