1 from __future__ import division, unicode_literals
7 from .common import FileDownloader
8 from .http import HttpFD
17 class HttpQuietDownloader(HttpFD):
18 def to_screen(self, *args, **kargs):
22 class FragmentFD(FileDownloader):
24 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
28 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
30 skip_unavailable_fragments:
31 Skip unavailable fragments (DASH and hlsnative only)
32 keep_fragments: Keep downloaded fragments on disk after downloading is
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)
53 def __do_ytdl_file(ctx):
54 return not ctx['live'] and not ctx['tmpfilename'] == '-'
56 def _read_ytdl_file(self, ctx):
57 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
58 ctx['fragment_index'] = json.loads(stream.read())['download']['current_fragment_index']
61 def _write_ytdl_file(self, ctx):
62 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
63 frag_index_stream.write(json.dumps({
65 'current_fragment_index': ctx['fragment_index']
68 frag_index_stream.close()
70 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
71 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
72 success = ctx['dl'].download(fragment_filename, {
74 'http_headers': headers or info_dict.get('http_headers'),
78 down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
79 ctx['fragment_filename_sanitized'] = frag_sanitized
80 frag_content = down.read()
82 return True, frag_content
84 def _append_fragment(self, ctx, frag_content):
86 ctx['dest_stream'].write(frag_content)
88 if self.__do_ytdl_file(ctx):
89 self._write_ytdl_file(ctx)
90 if not self.params.get('keep_fragments', False):
91 os.remove(ctx['fragment_filename_sanitized'])
92 del ctx['fragment_filename_sanitized']
94 def _prepare_frag_download(self, ctx):
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(
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),
113 tmpfilename = self.temp_name(ctx['filename'])
117 # Establish possible resume length
118 if os.path.isfile(encodeFilename(tmpfilename)):
120 resume_len = os.path.getsize(encodeFilename(tmpfilename))
122 # Should be initialized before ytdl file check
124 'tmpfilename': tmpfilename,
128 if self.__do_ytdl_file(ctx):
129 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
130 self._read_ytdl_file(ctx)
132 self._write_ytdl_file(ctx)
133 if ctx['fragment_index'] > 0:
134 assert resume_len > 0
136 assert resume_len == 0
138 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
142 'dest_stream': dest_stream,
143 'tmpfilename': tmpfilename,
144 # Total complete fragments downloaded so far in bytes
145 'complete_frags_downloaded_bytes': resume_len,
148 def _start_frag_download(self, ctx):
149 total_frags = ctx['total_frags']
150 # This dict stores the download progress, it's updated by the progress
153 'status': 'downloading',
154 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
155 'fragment_index': ctx['fragment_index'],
156 'fragment_count': total_frags,
157 'filename': ctx['filename'],
158 'tmpfilename': ctx['tmpfilename'],
164 # Amount of fragment's bytes downloaded by the time of the previous
165 # frag progress hook invocation
166 'prev_frag_downloaded_bytes': 0,
169 def frag_progress_hook(s):
170 if s['status'] not in ('downloading', 'finished'):
173 time_now = time.time()
174 state['elapsed'] = time_now - start
175 frag_total_bytes = s.get('total_bytes') or 0
178 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
179 (state['fragment_index'] + 1) * total_frags)
180 state['total_bytes_estimate'] = estimated_size
182 if s['status'] == 'finished':
183 state['fragment_index'] += 1
184 ctx['fragment_index'] = state['fragment_index']
185 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
186 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
187 ctx['prev_frag_downloaded_bytes'] = 0
189 frag_downloaded_bytes = s['downloaded_bytes']
190 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
192 state['eta'] = self.calc_eta(
193 start, time_now, estimated_size,
194 state['downloaded_bytes'])
195 state['speed'] = s.get('speed') or ctx.get('speed')
196 ctx['speed'] = state['speed']
197 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
198 self._hook_progress(state)
200 ctx['dl'].add_progress_hook(frag_progress_hook)
204 def _finish_frag_download(self, ctx):
205 ctx['dest_stream'].close()
206 if self.__do_ytdl_file(ctx):
207 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
208 if os.path.isfile(ytdl_filename):
209 os.remove(ytdl_filename)
210 elapsed = time.time() - ctx['started']
211 self.try_rename(ctx['tmpfilename'], ctx['filename'])
212 fsize = os.path.getsize(encodeFilename(ctx['filename']))
214 self._hook_progress({
215 'downloaded_bytes': fsize,
216 'total_bytes': fsize,
217 'filename': ctx['filename'],
218 'status': 'finished',