fragment.py 7.0 KB

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