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.

188 lines
6.9 KiB

  1. from __future__ import division, unicode_literals
  2. import os
  3. import time
  4. import io
  5. import json
  6. from .common import FileDownloader
  7. from .http import HttpFD
  8. from ..utils import (
  9. error_to_compat_str,
  10. encodeFilename,
  11. sanitize_open,
  12. sanitized_Request,
  13. )
  14. class HttpQuietDownloader(HttpFD):
  15. def to_screen(self, *args, **kargs):
  16. pass
  17. class FragmentFD(FileDownloader):
  18. """
  19. A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
  20. Available options:
  21. fragment_retries: Number of times to retry a fragment for HTTP error (DASH
  22. and hlsnative only)
  23. skip_unavailable_fragments:
  24. Skip unavailable fragments (DASH and hlsnative only)
  25. """
  26. def report_retry_fragment(self, err, frag_index, count, retries):
  27. self.to_screen(
  28. '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
  29. % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
  30. def report_skip_fragment(self, frag_index):
  31. self.to_screen('[download] Skipping fragment %d...' % frag_index)
  32. def _prepare_url(self, info_dict, url):
  33. headers = info_dict.get('http_headers')
  34. return sanitized_Request(url, None, headers) if headers else url
  35. def _prepare_and_start_frag_download(self, ctx):
  36. self._prepare_frag_download(ctx)
  37. self._start_frag_download(ctx)
  38. def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
  39. down = io.BytesIO()
  40. success = ctx['dl'].download(down, {
  41. 'url': frag_url,
  42. 'http_headers': headers or info_dict.get('http_headers'),
  43. })
  44. if not success:
  45. return False, None
  46. frag_content = down.getvalue()
  47. down.close()
  48. return True, frag_content
  49. def _append_fragment(self, ctx, frag_content):
  50. ctx['dest_stream'].write(frag_content)
  51. if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
  52. frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
  53. frag_index_stream.write(json.dumps({
  54. 'download': {
  55. 'last_fragment_index': ctx['fragment_index']
  56. },
  57. }))
  58. frag_index_stream.close()
  59. def _prepare_frag_download(self, ctx):
  60. if 'live' not in ctx:
  61. ctx['live'] = False
  62. self.to_screen(
  63. '[%s] Total fragments: %s'
  64. % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
  65. self.report_destination(ctx['filename'])
  66. dl = HttpQuietDownloader(
  67. self.ydl,
  68. {
  69. 'continuedl': True,
  70. 'quiet': True,
  71. 'noprogress': True,
  72. 'ratelimit': self.params.get('ratelimit'),
  73. 'retries': self.params.get('retries', 0),
  74. 'nopart': self.params.get('nopart', False),
  75. 'test': self.params.get('test', False),
  76. }
  77. )
  78. tmpfilename = self.temp_name(ctx['filename'])
  79. open_mode = 'wb'
  80. resume_len = 0
  81. frag_index = 0
  82. # Establish possible resume length
  83. if os.path.isfile(encodeFilename(tmpfilename)):
  84. open_mode = 'ab'
  85. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  86. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  87. if os.path.isfile(ytdl_filename):
  88. frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
  89. frag_index = json.loads(frag_index_stream.read())['download']['last_fragment_index']
  90. frag_index_stream.close()
  91. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  92. ctx.update({
  93. 'dl': dl,
  94. 'dest_stream': dest_stream,
  95. 'tmpfilename': tmpfilename,
  96. 'fragment_index': frag_index,
  97. # Total complete fragments downloaded so far in bytes
  98. 'complete_frags_downloaded_bytes': resume_len,
  99. })
  100. def _start_frag_download(self, ctx):
  101. total_frags = ctx['total_frags']
  102. # This dict stores the download progress, it's updated by the progress
  103. # hook
  104. state = {
  105. 'status': 'downloading',
  106. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  107. 'fragment_index': ctx['fragment_index'],
  108. 'fragment_count': total_frags,
  109. 'filename': ctx['filename'],
  110. 'tmpfilename': ctx['tmpfilename'],
  111. }
  112. start = time.time()
  113. ctx.update({
  114. 'started': start,
  115. # Amount of fragment's bytes downloaded by the time of the previous
  116. # frag progress hook invocation
  117. 'prev_frag_downloaded_bytes': 0,
  118. })
  119. def frag_progress_hook(s):
  120. if s['status'] not in ('downloading', 'finished'):
  121. return
  122. time_now = time.time()
  123. state['elapsed'] = time_now - start
  124. frag_total_bytes = s.get('total_bytes') or 0
  125. if not ctx['live']:
  126. estimated_size = (
  127. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  128. (state['fragment_index'] + 1) * total_frags)
  129. state['total_bytes_estimate'] = estimated_size
  130. if s['status'] == 'finished':
  131. state['fragment_index'] += 1
  132. ctx['fragment_index'] = state['fragment_index']
  133. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  134. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  135. ctx['prev_frag_downloaded_bytes'] = 0
  136. else:
  137. frag_downloaded_bytes = s['downloaded_bytes']
  138. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  139. if not ctx['live']:
  140. state['eta'] = self.calc_eta(
  141. start, time_now, estimated_size,
  142. state['downloaded_bytes'])
  143. state['speed'] = s.get('speed') or ctx.get('speed')
  144. ctx['speed'] = state['speed']
  145. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  146. self._hook_progress(state)
  147. ctx['dl'].add_progress_hook(frag_progress_hook)
  148. return start
  149. def _finish_frag_download(self, ctx):
  150. ctx['dest_stream'].close()
  151. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  152. if os.path.isfile(ytdl_filename):
  153. os.remove(ytdl_filename)
  154. elapsed = time.time() - ctx['started']
  155. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  156. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  157. self._hook_progress({
  158. 'downloaded_bytes': fsize,
  159. 'total_bytes': fsize,
  160. 'filename': ctx['filename'],
  161. 'status': 'finished',
  162. 'elapsed': elapsed,
  163. })