1 from __future__ import division, unicode_literals
8 from .common import FileDownloader
9 from .http import HttpFD
18 class HttpQuietDownloader(HttpFD):
19 def to_screen(self, *args, **kargs):
23 class FragmentFD(FileDownloader):
25 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
29 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
31 skip_unavailable_fragments:
32 Skip unavailable fragments (DASH and hlsnative only)
35 def report_retry_fragment(self, err, frag_index, count, retries):
37 '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
38 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
40 def report_skip_fragment(self, frag_index):
41 self.to_screen('[download] Skipping fragment %d...' % frag_index)
43 def _prepare_url(self, info_dict, url):
44 headers = info_dict.get('http_headers')
45 return sanitized_Request(url, None, headers) if headers else url
47 def _prepare_and_start_frag_download(self, ctx):
48 self._prepare_frag_download(ctx)
49 self._start_frag_download(ctx)
51 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
53 success = ctx['dl'].download(down, {
55 'http_headers': headers or info_dict.get('http_headers'),
59 frag_content = down.getvalue()
61 return True, frag_content
63 def _append_fragment(self, ctx, frag_content):
64 ctx['dest_stream'].write(frag_content)
65 if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
66 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
67 frag_index_stream.write(json.dumps({
69 'last_fragment_index': ctx['fragment_index']
72 frag_index_stream.close()
74 def _prepare_frag_download(self, ctx):
78 '[%s] Total fragments: %s'
79 % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
80 self.report_destination(ctx['filename'])
81 dl = HttpQuietDownloader(
87 'ratelimit': self.params.get('ratelimit'),
88 'retries': self.params.get('retries', 0),
89 'nopart': self.params.get('nopart', False),
90 'test': self.params.get('test', False),
93 tmpfilename = self.temp_name(ctx['filename'])
97 # Establish possible resume length
98 if os.path.isfile(encodeFilename(tmpfilename)):
100 resume_len = os.path.getsize(encodeFilename(tmpfilename))
101 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
102 if os.path.isfile(ytdl_filename):
103 frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
104 frag_index = json.loads(frag_index_stream.read())['download']['last_fragment_index']
105 frag_index_stream.close()
106 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
110 'dest_stream': dest_stream,
111 'tmpfilename': tmpfilename,
112 'fragment_index': frag_index,
113 # Total complete fragments downloaded so far in bytes
114 'complete_frags_downloaded_bytes': resume_len,
117 def _start_frag_download(self, ctx):
118 total_frags = ctx['total_frags']
119 # This dict stores the download progress, it's updated by the progress
122 'status': 'downloading',
123 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
124 'fragment_index': ctx['fragment_index'],
125 'fragment_count': total_frags,
126 'filename': ctx['filename'],
127 'tmpfilename': ctx['tmpfilename'],
133 # Amount of fragment's bytes downloaded by the time of the previous
134 # frag progress hook invocation
135 'prev_frag_downloaded_bytes': 0,
138 def frag_progress_hook(s):
139 if s['status'] not in ('downloading', 'finished'):
142 time_now = time.time()
143 state['elapsed'] = time_now - start
144 frag_total_bytes = s.get('total_bytes') or 0
147 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
148 (state['fragment_index'] + 1) * total_frags)
149 state['total_bytes_estimate'] = estimated_size
151 if s['status'] == 'finished':
152 state['fragment_index'] += 1
153 ctx['fragment_index'] = state['fragment_index']
154 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
155 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
156 ctx['prev_frag_downloaded_bytes'] = 0
158 frag_downloaded_bytes = s['downloaded_bytes']
159 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
161 state['eta'] = self.calc_eta(
162 start, time_now, estimated_size,
163 state['downloaded_bytes'])
164 state['speed'] = s.get('speed') or ctx.get('speed')
165 ctx['speed'] = state['speed']
166 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
167 self._hook_progress(state)
169 ctx['dl'].add_progress_hook(frag_progress_hook)
173 def _finish_frag_download(self, ctx):
174 ctx['dest_stream'].close()
175 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
176 if os.path.isfile(ytdl_filename):
177 os.remove(ytdl_filename)
178 elapsed = time.time() - ctx['started']
179 self.try_rename(ctx['tmpfilename'], ctx['filename'])
180 fsize = os.path.getsize(encodeFilename(ctx['filename']))
182 self._hook_progress({
183 'downloaded_bytes': fsize,
184 'total_bytes': fsize,
185 'filename': ctx['filename'],
186 'status': 'finished',