fragment.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. For each incomplete fragment download youtube-dl keeps on disk a special
  27. bookkeeping file with download state and metadata (in future such files will
  28. be used for any incomplete download handled by youtube-dl). This file is
  29. used to properly handle resuming, check download file consistency and detect
  30. potential errors. The file has a .ytdl extension and represents a standard
  31. JSON file of the following format:
  32. extractor:
  33. Dictionary of extractor related data. TBD.
  34. downloader:
  35. Dictionary of downloader related data. May contain following data:
  36. current_fragment:
  37. Dictionary with current (being downloaded) fragment data:
  38. index: Index of current fragment among all fragments
  39. fragment_count:
  40. Total count of fragments
  41. """
  42. def report_retry_fragment(self, err, frag_index, count, retries):
  43. self.to_screen(
  44. '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
  45. % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
  46. def report_skip_fragment(self, frag_index):
  47. self.to_screen('[download] Skipping fragment %d...' % frag_index)
  48. def _prepare_url(self, info_dict, url):
  49. headers = info_dict.get('http_headers')
  50. return sanitized_Request(url, None, headers) if headers else url
  51. def _prepare_and_start_frag_download(self, ctx):
  52. self._prepare_frag_download(ctx)
  53. self._start_frag_download(ctx)
  54. @staticmethod
  55. def __do_ytdl_file(ctx):
  56. return not ctx['live'] and not ctx['tmpfilename'] == '-'
  57. def _read_ytdl_file(self, ctx):
  58. stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
  59. ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
  60. stream.close()
  61. def _write_ytdl_file(self, ctx):
  62. frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
  63. downloader = {
  64. 'current_fragment': {
  65. 'index': ctx['fragment_index'],
  66. },
  67. }
  68. if ctx.get('fragment_count') is not None:
  69. downloader['fragment_count'] = ctx['fragment_count']
  70. frag_index_stream.write(json.dumps({'downloader': downloader}))
  71. frag_index_stream.close()
  72. def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
  73. fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
  74. success = ctx['dl'].download(fragment_filename, {
  75. 'url': frag_url,
  76. 'http_headers': headers or info_dict.get('http_headers'),
  77. })
  78. if not success:
  79. return False, None
  80. down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
  81. ctx['fragment_filename_sanitized'] = frag_sanitized
  82. frag_content = down.read()
  83. down.close()
  84. return True, frag_content
  85. def _append_fragment(self, ctx, frag_content):
  86. try:
  87. ctx['dest_stream'].write(frag_content)
  88. finally:
  89. if self.__do_ytdl_file(ctx):
  90. self._write_ytdl_file(ctx)
  91. if not self.params.get('keep_fragments', False):
  92. os.remove(ctx['fragment_filename_sanitized'])
  93. del ctx['fragment_filename_sanitized']
  94. def _prepare_frag_download(self, ctx):
  95. if 'live' not in ctx:
  96. ctx['live'] = False
  97. self.to_screen(
  98. '[%s] Total fragments: %s'
  99. % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
  100. self.report_destination(ctx['filename'])
  101. dl = HttpQuietDownloader(
  102. self.ydl,
  103. {
  104. 'continuedl': True,
  105. 'quiet': True,
  106. 'noprogress': True,
  107. 'ratelimit': self.params.get('ratelimit'),
  108. 'retries': self.params.get('retries', 0),
  109. 'nopart': self.params.get('nopart', False),
  110. 'test': self.params.get('test', False),
  111. }
  112. )
  113. tmpfilename = self.temp_name(ctx['filename'])
  114. open_mode = 'wb'
  115. resume_len = 0
  116. # Establish possible resume length
  117. if os.path.isfile(encodeFilename(tmpfilename)):
  118. open_mode = 'ab'
  119. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  120. # Should be initialized before ytdl file check
  121. ctx.update({
  122. 'tmpfilename': tmpfilename,
  123. 'fragment_index': 0,
  124. })
  125. if self.__do_ytdl_file(ctx):
  126. if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
  127. self._read_ytdl_file(ctx)
  128. else:
  129. self._write_ytdl_file(ctx)
  130. if ctx['fragment_index'] > 0:
  131. assert resume_len > 0
  132. else:
  133. assert resume_len == 0
  134. dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
  135. ctx.update({
  136. 'dl': dl,
  137. 'dest_stream': dest_stream,
  138. 'tmpfilename': tmpfilename,
  139. # Total complete fragments downloaded so far in bytes
  140. 'complete_frags_downloaded_bytes': resume_len,
  141. })
  142. def _start_frag_download(self, ctx):
  143. total_frags = ctx['total_frags']
  144. # This dict stores the download progress, it's updated by the progress
  145. # hook
  146. state = {
  147. 'status': 'downloading',
  148. 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
  149. 'fragment_index': ctx['fragment_index'],
  150. 'fragment_count': total_frags,
  151. 'filename': ctx['filename'],
  152. 'tmpfilename': ctx['tmpfilename'],
  153. }
  154. start = time.time()
  155. ctx.update({
  156. 'started': start,
  157. # Amount of fragment's bytes downloaded by the time of the previous
  158. # frag progress hook invocation
  159. 'prev_frag_downloaded_bytes': 0,
  160. })
  161. def frag_progress_hook(s):
  162. if s['status'] not in ('downloading', 'finished'):
  163. return
  164. time_now = time.time()
  165. state['elapsed'] = time_now - start
  166. frag_total_bytes = s.get('total_bytes') or 0
  167. if not ctx['live']:
  168. estimated_size = (
  169. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
  170. (state['fragment_index'] + 1) * total_frags)
  171. state['total_bytes_estimate'] = estimated_size
  172. if s['status'] == 'finished':
  173. state['fragment_index'] += 1
  174. ctx['fragment_index'] = state['fragment_index']
  175. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  176. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  177. ctx['prev_frag_downloaded_bytes'] = 0
  178. else:
  179. frag_downloaded_bytes = s['downloaded_bytes']
  180. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  181. if not ctx['live']:
  182. state['eta'] = self.calc_eta(
  183. start, time_now, estimated_size,
  184. state['downloaded_bytes'])
  185. state['speed'] = s.get('speed') or ctx.get('speed')
  186. ctx['speed'] = state['speed']
  187. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  188. self._hook_progress(state)
  189. ctx['dl'].add_progress_hook(frag_progress_hook)
  190. return start
  191. def _finish_frag_download(self, ctx):
  192. ctx['dest_stream'].close()
  193. if self.__do_ytdl_file(ctx):
  194. ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
  195. if os.path.isfile(ytdl_filename):
  196. os.remove(ytdl_filename)
  197. elapsed = time.time() - ctx['started']
  198. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  199. fsize = os.path.getsize(encodeFilename(ctx['filename']))
  200. self._hook_progress({
  201. 'downloaded_bytes': fsize,
  202. 'total_bytes': fsize,
  203. 'filename': ctx['filename'],
  204. 'status': 'finished',
  205. 'elapsed': elapsed,
  206. })