fragment.py 7.6 KB

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