fragment.py 7.5 KB

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