]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/fragment.py
44beed06644a5e6ccdb221b1d4e15d85b28c1b90
[yt-dlp.git] / yt_dlp / downloader / fragment.py
1 from __future__ import division, unicode_literals
2
3 import os
4 import time
5 import json
6
7 from .common import FileDownloader
8 from .http import HttpFD
9 from ..utils import (
10 error_to_compat_str,
11 encodeFilename,
12 sanitize_open,
13 sanitized_Request,
14 )
15
16
17 class HttpQuietDownloader(HttpFD):
18 def to_screen(self, *args, **kargs):
19 pass
20
21
22 class FragmentFD(FileDownloader):
23 """
24 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
25
26 Available options:
27
28 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
29 and hlsnative only)
30 skip_unavailable_fragments:
31 Skip unavailable fragments (DASH and hlsnative only)
32 keep_fragments: Keep downloaded fragments on disk after downloading is
33 finished
34
35 For each incomplete fragment download yt-dlp keeps on disk a special
36 bookkeeping file with download state and metadata (in future such files will
37 be used for any incomplete download handled by yt-dlp). This file is
38 used to properly handle resuming, check download file consistency and detect
39 potential errors. The file has a .ytdl extension and represents a standard
40 JSON file of the following format:
41
42 extractor:
43 Dictionary of extractor related data. TBD.
44
45 downloader:
46 Dictionary of downloader related data. May contain following data:
47 current_fragment:
48 Dictionary with current (being downloaded) fragment data:
49 index: 0-based index of current fragment among all fragments
50 fragment_count:
51 Total count of fragments
52
53 This feature is experimental and file format may change in future.
54 """
55
56 def report_retry_fragment(self, err, frag_index, count, retries):
57 self.to_screen(
58 '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
59 % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
60
61 def report_skip_fragment(self, frag_index):
62 self.to_screen('[download] Skipping fragment %d...' % frag_index)
63
64 def _prepare_url(self, info_dict, url):
65 headers = info_dict.get('http_headers')
66 return sanitized_Request(url, None, headers) if headers else url
67
68 def _prepare_and_start_frag_download(self, ctx):
69 self._prepare_frag_download(ctx)
70 self._start_frag_download(ctx)
71
72 @staticmethod
73 def __do_ytdl_file(ctx):
74 return not ctx['live'] and not ctx['tmpfilename'] == '-'
75
76 def _read_ytdl_file(self, ctx):
77 assert 'ytdl_corrupt' not in ctx
78 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
79 try:
80 ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
81 except Exception:
82 ctx['ytdl_corrupt'] = True
83 finally:
84 stream.close()
85
86 def _write_ytdl_file(self, ctx):
87 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
88 downloader = {
89 'current_fragment': {
90 'index': ctx['fragment_index'],
91 },
92 }
93 if ctx.get('fragment_count') is not None:
94 downloader['fragment_count'] = ctx['fragment_count']
95 frag_index_stream.write(json.dumps({'downloader': downloader}))
96 frag_index_stream.close()
97
98 def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
99 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
100 fragment_info_dict = {
101 'url': frag_url,
102 'http_headers': headers or info_dict.get('http_headers'),
103 'request_data': request_data,
104 }
105 success = ctx['dl'].download(fragment_filename, fragment_info_dict)
106 if not success:
107 return False, None
108 if fragment_info_dict.get('filetime'):
109 ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
110 down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
111 ctx['fragment_filename_sanitized'] = frag_sanitized
112 frag_content = down.read()
113 down.close()
114 return True, frag_content
115
116 def _append_fragment(self, ctx, frag_content):
117 try:
118 ctx['dest_stream'].write(frag_content)
119 ctx['dest_stream'].flush()
120 finally:
121 if self.__do_ytdl_file(ctx):
122 self._write_ytdl_file(ctx)
123 if not self.params.get('keep_fragments', False):
124 os.remove(encodeFilename(ctx['fragment_filename_sanitized']))
125 del ctx['fragment_filename_sanitized']
126
127 def _prepare_frag_download(self, ctx):
128 if 'live' not in ctx:
129 ctx['live'] = False
130 if not ctx['live']:
131 total_frags_str = '%d' % ctx['total_frags']
132 ad_frags = ctx.get('ad_frags', 0)
133 if ad_frags:
134 total_frags_str += ' (not including %d ad)' % ad_frags
135 else:
136 total_frags_str = 'unknown (live)'
137 self.to_screen(
138 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
139 self.report_destination(ctx['filename'])
140 dl = HttpQuietDownloader(
141 self.ydl,
142 {
143 'continuedl': True,
144 'quiet': True,
145 'noprogress': True,
146 'ratelimit': self.params.get('ratelimit'),
147 'retries': self.params.get('retries', 0),
148 'nopart': self.params.get('nopart', False),
149 'test': self.params.get('test', False),
150 }
151 )
152 tmpfilename = self.temp_name(ctx['filename'])
153 open_mode = 'wb'
154 resume_len = 0
155
156 # Establish possible resume length
157 if os.path.isfile(encodeFilename(tmpfilename)):
158 open_mode = 'ab'
159 resume_len = os.path.getsize(encodeFilename(tmpfilename))
160
161 # Should be initialized before ytdl file check
162 ctx.update({
163 'tmpfilename': tmpfilename,
164 'fragment_index': 0,
165 })
166
167 if self.__do_ytdl_file(ctx):
168 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
169 self._read_ytdl_file(ctx)
170 is_corrupt = ctx.get('ytdl_corrupt') is True
171 is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
172 if is_corrupt or is_inconsistent:
173 message = (
174 '.ytdl file is corrupt' if is_corrupt else
175 'Inconsistent state of incomplete fragment download')
176 self.report_warning(
177 '%s. Restarting from the beginning...' % message)
178 ctx['fragment_index'] = resume_len = 0
179 if 'ytdl_corrupt' in ctx:
180 del ctx['ytdl_corrupt']
181 self._write_ytdl_file(ctx)
182 else:
183 self._write_ytdl_file(ctx)
184 assert ctx['fragment_index'] == 0
185
186 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
187
188 ctx.update({
189 'dl': dl,
190 'dest_stream': dest_stream,
191 'tmpfilename': tmpfilename,
192 # Total complete fragments downloaded so far in bytes
193 'complete_frags_downloaded_bytes': resume_len,
194 })
195
196 def _start_frag_download(self, ctx):
197 resume_len = ctx['complete_frags_downloaded_bytes']
198 total_frags = ctx['total_frags']
199 # This dict stores the download progress, it's updated by the progress
200 # hook
201 state = {
202 'status': 'downloading',
203 'downloaded_bytes': resume_len,
204 'fragment_index': ctx['fragment_index'],
205 'fragment_count': total_frags,
206 'filename': ctx['filename'],
207 'tmpfilename': ctx['tmpfilename'],
208 }
209
210 start = time.time()
211 ctx.update({
212 'started': start,
213 # Amount of fragment's bytes downloaded by the time of the previous
214 # frag progress hook invocation
215 'prev_frag_downloaded_bytes': 0,
216 })
217
218 def frag_progress_hook(s):
219 if s['status'] not in ('downloading', 'finished'):
220 return
221
222 time_now = time.time()
223 state['elapsed'] = time_now - start
224 frag_total_bytes = s.get('total_bytes') or 0
225 if not ctx['live']:
226 estimated_size = (
227 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
228 / (state['fragment_index'] + 1) * total_frags)
229 state['total_bytes_estimate'] = estimated_size
230
231 if s['status'] == 'finished':
232 state['fragment_index'] += 1
233 ctx['fragment_index'] = state['fragment_index']
234 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
235 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
236 ctx['prev_frag_downloaded_bytes'] = 0
237 else:
238 frag_downloaded_bytes = s['downloaded_bytes']
239 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
240 if not ctx['live']:
241 state['eta'] = self.calc_eta(
242 start, time_now, estimated_size - resume_len,
243 state['downloaded_bytes'] - resume_len)
244 state['speed'] = s.get('speed') or ctx.get('speed')
245 ctx['speed'] = state['speed']
246 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
247 self._hook_progress(state)
248
249 ctx['dl'].add_progress_hook(frag_progress_hook)
250
251 return start
252
253 def _finish_frag_download(self, ctx):
254 ctx['dest_stream'].close()
255 if self.__do_ytdl_file(ctx):
256 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
257 if os.path.isfile(ytdl_filename):
258 os.remove(ytdl_filename)
259 elapsed = time.time() - ctx['started']
260
261 if ctx['tmpfilename'] == '-':
262 downloaded_bytes = ctx['complete_frags_downloaded_bytes']
263 else:
264 self.try_rename(ctx['tmpfilename'], ctx['filename'])
265 if self.params.get('updatetime', True):
266 filetime = ctx.get('fragment_filetime')
267 if filetime:
268 try:
269 os.utime(ctx['filename'], (time.time(), filetime))
270 except Exception:
271 pass
272 downloaded_bytes = os.path.getsize(encodeFilename(ctx['filename']))
273
274 self._hook_progress({
275 'downloaded_bytes': downloaded_bytes,
276 'total_bytes': downloaded_bytes,
277 'filename': ctx['filename'],
278 'status': 'finished',
279 'elapsed': elapsed,
280 })
281
282 def _prepare_external_frag_download(self, ctx):
283 if 'live' not in ctx:
284 ctx['live'] = False
285 if not ctx['live']:
286 total_frags_str = '%d' % ctx['total_frags']
287 ad_frags = ctx.get('ad_frags', 0)
288 if ad_frags:
289 total_frags_str += ' (not including %d ad)' % ad_frags
290 else:
291 total_frags_str = 'unknown (live)'
292 self.to_screen(
293 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
294
295 tmpfilename = self.temp_name(ctx['filename'])
296
297 # Should be initialized before ytdl file check
298 ctx.update({
299 'tmpfilename': tmpfilename,
300 'fragment_index': 0,
301 })