1 from __future__ import division, unicode_literals
8 from .common import FileDownloader
9 from .http import HttpFD
19 class HttpQuietDownloader(HttpFD):
20 def to_screen(self, *args, **kargs):
24 class FragmentFD(FileDownloader):
26 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
30 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
32 skip_unavailable_fragments:
33 Skip unavailable fragments (DASH and hlsnative only)
36 def report_retry_fragment(self, err, frag_index, count, retries):
38 '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
39 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
41 def report_skip_fragment(self, frag_index):
42 self.to_screen('[download] Skipping fragment %d...' % frag_index)
44 def _prepare_url(self, info_dict, url):
45 headers = info_dict.get('http_headers')
46 return sanitized_Request(url, None, headers) if headers else url
48 def _prepare_and_start_frag_download(self, ctx):
49 self._prepare_frag_download(ctx)
50 self._start_frag_download(ctx)
52 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
54 success = ctx['dl'].download(down, {
56 'http_headers': headers or info_dict.get('http_headers'),
60 frag_content = down.getvalue()
62 return True, frag_content
64 def _append_fragment(self, ctx, frag_content):
65 ctx['dest_stream'].write(frag_content)
66 if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
67 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
68 frag_index_stream.write(json.dumps({
70 'last_fragment_index': ctx['fragment_index']
73 frag_index_stream.close()
75 def _prepare_frag_download(self, ctx):
79 '[%s] Total fragments: %s'
80 % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
81 self.report_destination(ctx['filename'])
82 dl = HttpQuietDownloader(
88 'ratelimit': self.params.get('ratelimit'),
89 'retries': self.params.get('retries', 0),
90 'nopart': self.params.get('nopart', False),
91 'test': self.params.get('test', False),
94 tmpfilename = self.temp_name(ctx['filename'])
98 # Establish possible resume length
99 if os.path.isfile(encodeFilename(tmpfilename)):
101 resume_len = os.path.getsize(encodeFilename(tmpfilename))
102 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
103 if os.path.isfile(ytdl_filename):
104 frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
105 frag_index = json.loads(frag_index_stream.read())['download']['last_fragment_index']
106 frag_index_stream.close()
107 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
111 'dest_stream': dest_stream,
112 'tmpfilename': tmpfilename,
113 'fragment_index': frag_index,
114 # Total complete fragments downloaded so far in bytes
115 'complete_frags_downloaded_bytes': resume_len,
118 def _start_frag_download(self, ctx):
119 total_frags = ctx['total_frags']
120 # This dict stores the download progress, it's updated by the progress
123 'status': 'downloading',
124 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
125 'fragment_index': ctx['fragment_index'],
126 'fragment_count': total_frags,
127 'filename': ctx['filename'],
128 'tmpfilename': ctx['tmpfilename'],
134 # Amount of fragment's bytes downloaded by the time of the previous
135 # frag progress hook invocation
136 'prev_frag_downloaded_bytes': 0,
139 def frag_progress_hook(s):
140 if s['status'] not in ('downloading', 'finished'):
143 time_now = time.time()
144 state['elapsed'] = time_now - start
145 frag_total_bytes = s.get('total_bytes') or 0
148 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
149 (state['fragment_index'] + 1) * total_frags)
150 state['total_bytes_estimate'] = estimated_size
152 if s['status'] == 'finished':
153 state['fragment_index'] += 1
154 ctx['fragment_index'] = state['fragment_index']
155 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
156 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
157 ctx['prev_frag_downloaded_bytes'] = 0
159 frag_downloaded_bytes = s['downloaded_bytes']
160 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
162 state['eta'] = self.calc_eta(
163 start, time_now, estimated_size,
164 state['downloaded_bytes'])
165 state['speed'] = s.get('speed') or ctx.get('speed')
166 ctx['speed'] = state['speed']
167 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
168 self._hook_progress(state)
170 ctx['dl'].add_progress_hook(frag_progress_hook)
174 def _finish_frag_download(self, ctx):
175 ctx['dest_stream'].close()
176 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
177 if os.path.isfile(ytdl_filename):
178 os.remove(ytdl_filename)
179 elapsed = time.time() - ctx['started']
180 self.try_rename(ctx['tmpfilename'], ctx['filename'])
181 fsize = os.path.getsize(encodeFilename(ctx['filename']))
183 self._hook_progress({
184 'downloaded_bytes': fsize,
185 'total_bytes': fsize,
186 'filename': ctx['filename'],
187 'status': 'finished',