fragment.py 6.8 KB

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