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)
34 def report_retry_fragment(self, err, frag_index, count, retries):
36 '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
37 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
39 def report_skip_fragment(self, frag_index):
40 self.to_screen('[download] Skipping fragment %d...' % frag_index)
42 def _prepare_url(self, info_dict, url):
43 headers = info_dict.get('http_headers')
44 return sanitized_Request(url, None, headers) if headers else url
46 def _prepare_and_start_frag_download(self, ctx):
47 self._prepare_frag_download(ctx)
48 self._start_frag_download(ctx)
50 def _read_ytdl_file(self, ctx):
51 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
52 ctx['fragment_index'] = json.loads(stream.read())['download']['current_fragment_index']
55 def _write_ytdl_file(self, ctx):
56 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
57 frag_index_stream.write(json.dumps({
59 'current_fragment_index': ctx['fragment_index']
62 frag_index_stream.close()
64 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
65 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
66 success = ctx['dl'].download(fragment_filename, {
68 'http_headers': headers or info_dict.get('http_headers'),
72 down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
73 ctx['fragment_filename_sanitized'] = frag_sanitized
74 frag_content = down.read()
76 return True, frag_content
78 def _append_fragment(self, ctx, frag_content):
80 ctx['dest_stream'].write(frag_content)
82 if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
83 self._write_ytdl_file(ctx)
84 os.remove(ctx['fragment_filename_sanitized'])
85 del ctx['fragment_filename_sanitized']
87 def _prepare_frag_download(self, ctx):
91 '[%s] Total fragments: %s'
92 % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
93 self.report_destination(ctx['filename'])
94 dl = HttpQuietDownloader(
100 'ratelimit': self.params.get('ratelimit'),
101 'retries': self.params.get('retries', 0),
102 'nopart': self.params.get('nopart', False),
103 'test': self.params.get('test', False),
106 tmpfilename = self.temp_name(ctx['filename'])
110 # Establish possible resume length
111 if os.path.isfile(encodeFilename(tmpfilename)):
113 resume_len = os.path.getsize(encodeFilename(tmpfilename))
115 ctx['fragment_index'] = 0
116 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
117 self._read_ytdl_file(ctx)
119 self._write_ytdl_file(ctx)
121 if ctx['fragment_index'] > 0:
122 assert resume_len > 0
124 assert resume_len == 0
126 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
130 'dest_stream': dest_stream,
131 'tmpfilename': tmpfilename,
132 # Total complete fragments downloaded so far in bytes
133 'complete_frags_downloaded_bytes': resume_len,
136 def _start_frag_download(self, ctx):
137 total_frags = ctx['total_frags']
138 # This dict stores the download progress, it's updated by the progress
141 'status': 'downloading',
142 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
143 'fragment_index': ctx['fragment_index'],
144 'fragment_count': total_frags,
145 'filename': ctx['filename'],
146 'tmpfilename': ctx['tmpfilename'],
152 # Amount of fragment's bytes downloaded by the time of the previous
153 # frag progress hook invocation
154 'prev_frag_downloaded_bytes': 0,
157 def frag_progress_hook(s):
158 if s['status'] not in ('downloading', 'finished'):
161 time_now = time.time()
162 state['elapsed'] = time_now - start
163 frag_total_bytes = s.get('total_bytes') or 0
166 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
167 (state['fragment_index'] + 1) * total_frags)
168 state['total_bytes_estimate'] = estimated_size
170 if s['status'] == 'finished':
171 state['fragment_index'] += 1
172 ctx['fragment_index'] = state['fragment_index']
173 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
174 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
175 ctx['prev_frag_downloaded_bytes'] = 0
177 frag_downloaded_bytes = s['downloaded_bytes']
178 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
180 state['eta'] = self.calc_eta(
181 start, time_now, estimated_size,
182 state['downloaded_bytes'])
183 state['speed'] = s.get('speed') or ctx.get('speed')
184 ctx['speed'] = state['speed']
185 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
186 self._hook_progress(state)
188 ctx['dl'].add_progress_hook(frag_progress_hook)
192 def _finish_frag_download(self, ctx):
193 ctx['dest_stream'].close()
194 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
195 if os.path.isfile(ytdl_filename):
196 os.remove(ytdl_filename)
197 elapsed = time.time() - ctx['started']
198 self.try_rename(ctx['tmpfilename'], ctx['filename'])
199 fsize = os.path.getsize(encodeFilename(ctx['filename']))
201 self._hook_progress({
202 'downloaded_bytes': fsize,
203 'total_bytes': fsize,
204 'filename': ctx['filename'],
205 'status': 'finished',