fragment.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. from __future__ import division, unicode_literals
  2. import os
  3. import time
  4. import io
  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. compat_str,
  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(ctx['tmpfilename'] + '.fragindex', 'w')
  53. frag_index_stream.write(compat_str(ctx['frag_index']))
  54. frag_index_stream.close()
  55. def _prepare_frag_download(self, ctx):
  56. if 'live' not in ctx:
  57. ctx['live'] = False
  58. self.to_screen(
  59. '[%s] Total fragments: %s'
  60. % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
  61. self.report_destination(ctx['filename'])
  62. dl = HttpQuietDownloader(
  63. self.ydl,
  64. {
  65. 'continuedl': True,
  66. 'quiet': True,
  67. 'noprogress': True,
  68. 'ratelimit': self.params.get('ratelimit'),
  69. 'retries': self.params.get('retries', 0),
  70. 'nopart': self.params.get('nopart', False),
  71. 'test': self.params.get('test', False),
  72. }
  73. )
  74. tmpfilename = self.temp_name(ctx['filename'])
  75. open_mode = 'wb'
  76. resume_len = 0
  77. frag_index = 0
  78. # Establish possible resume length
  79. if os.path.isfile(encodeFilename(tmpfilename)):
  80. open_mode = 'ab'
  81. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  82. if os.path.isfile(encodeFilename(tmpfilename + '.fragindex')):
  83. frag_index_stream, _ = sanitize_open(tmpfilename + '.fragindex', 'r')
  84. frag_index = int(frag_index_stream.read())
  85. frag_index_stream.close()
  86. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  87. ctx.update({
  88. 'dl': dl,
  89. 'dest_stream': dest_stream,
  90. 'tmpfilename': tmpfilename,
  91. 'frag_index': frag_index,
  92. # Total complete fragments downloaded so far in bytes
  93. 'complete_frags_downloaded_bytes': resume_len,
  94. })
  95. def _start_frag_download(self, ctx):
  96. total_frags = ctx['total_frags']
  97. # This dict stores the download progress, it's updated by the progress
  98. # hook
  99. state = {
  100. 'status': 'downloading',
  101. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  102. 'frag_index': ctx['frag_index'],
  103. 'frag_count': total_frags,
  104. 'filename': ctx['filename'],
  105. 'tmpfilename': ctx['tmpfilename'],
  106. }
  107. start = time.time()
  108. ctx.update({
  109. 'started': start,
  110. # Amount of fragment's bytes downloaded by the time of the previous
  111. # frag progress hook invocation
  112. 'prev_frag_downloaded_bytes': 0,
  113. })
  114. def frag_progress_hook(s):
  115. if s['status'] not in ('downloading', 'finished'):
  116. return
  117. time_now = time.time()
  118. state['elapsed'] = time_now - start
  119. frag_total_bytes = s.get('total_bytes') or 0
  120. if not ctx['live']:
  121. estimated_size = (
  122. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  123. (state['frag_index'] + 1) * total_frags)
  124. state['total_bytes_estimate'] = estimated_size
  125. if s['status'] == 'finished':
  126. state['frag_index'] += 1
  127. ctx['frag_index'] = state['frag_index']
  128. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  129. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  130. ctx['prev_frag_downloaded_bytes'] = 0
  131. else:
  132. frag_downloaded_bytes = s['downloaded_bytes']
  133. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  134. if not ctx['live']:
  135. state['eta'] = self.calc_eta(
  136. start, time_now, estimated_size,
  137. state['downloaded_bytes'])
  138. state['speed'] = s.get('speed') or ctx.get('speed')
  139. ctx['speed'] = state['speed']
  140. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  141. self._hook_progress(state)
  142. ctx['dl'].add_progress_hook(frag_progress_hook)
  143. return start
  144. def _finish_frag_download(self, ctx):
  145. ctx['dest_stream'].close()
  146. if os.path.isfile(encodeFilename(ctx['tmpfilename'] + '.fragindex')):
  147. os.remove(encodeFilename(ctx['tmpfilename'] + '.fragindex'))
  148. elapsed = time.time() - ctx['started']
  149. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  150. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  151. self._hook_progress({
  152. 'downloaded_bytes': fsize,
  153. 'total_bytes': fsize,
  154. 'filename': ctx['filename'],
  155. 'status': 'finished',
  156. 'elapsed': elapsed,
  157. })