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({
69 'frag_index': ctx['frag_index']
71 frag_index_stream.close()
73 def _prepare_frag_download(self, ctx):
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(
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),
92 tmpfilename = self.temp_name(ctx['filename'])
96 # Establish possible resume length
97 if os.path.isfile(encodeFilename(tmpfilename)):
99 resume_len = os.path.getsize(encodeFilename(tmpfilename))
100 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
101 if os.path.isfile(ytdl_filename):
102 frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
103 frag_index = json.loads(frag_index_stream.read())['frag_index']
104 frag_index_stream.close()
105 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
109 'dest_stream': dest_stream,
110 'tmpfilename': tmpfilename,
111 'frag_index': frag_index,
112 # Total complete fragments downloaded so far in bytes
113 'complete_frags_downloaded_bytes': resume_len,
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
121 'status': 'downloading',
122 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
123 'frag_index': ctx['frag_index'],
124 'frag_count': total_frags,
125 'filename': ctx['filename'],
126 'tmpfilename': ctx['tmpfilename'],
132 # Amount of fragment's bytes downloaded by the time of the previous
133 # frag progress hook invocation
134 'prev_frag_downloaded_bytes': 0,
137 def frag_progress_hook(s):
138 if s['status'] not in ('downloading', 'finished'):
141 time_now = time.time()
142 state['elapsed'] = time_now - start
143 frag_total_bytes = s.get('total_bytes') or 0
146 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
147 (state['frag_index'] + 1) * total_frags)
148 state['total_bytes_estimate'] = estimated_size
150 if s['status'] == 'finished':
151 state['frag_index'] += 1
152 ctx['frag_index'] = state['frag_index']
153 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
154 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
155 ctx['prev_frag_downloaded_bytes'] = 0
157 frag_downloaded_bytes = s['downloaded_bytes']
158 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
160 state['eta'] = self.calc_eta(
161 start, time_now, estimated_size,
162 state['downloaded_bytes'])
163 state['speed'] = s.get('speed') or ctx.get('speed')
164 ctx['speed'] = state['speed']
165 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
166 self._hook_progress(state)
168 ctx['dl'].add_progress_hook(frag_progress_hook)
172 def _finish_frag_download(self, ctx):
173 ctx['dest_stream'].close()
174 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
175 if os.path.isfile(ytdl_filename):
176 os.remove(ytdl_filename)
177 elapsed = time.time() - ctx['started']
178 self.try_rename(ctx['tmpfilename'], ctx['filename'])
179 fsize = os.path.getsize(encodeFilename(ctx['filename']))
181 self._hook_progress({
182 'downloaded_bytes': fsize,
183 'total_bytes': fsize,
184 'filename': ctx['filename'],
185 'status': 'finished',