]> jfr.im git - yt-dlp.git/blame - youtube_dl/downloader/fragment.py
[extractor/common] Add durations for DASH fragments with bare SegmentURLs
[yt-dlp.git] / youtube_dl / downloader / fragment.py
CommitLineData
95d8f7ea
S
1from __future__ import division, unicode_literals
2
3import os
4import time
ea0c2f21 5import json
95d8f7ea
S
6
7from .common import FileDownloader
8from .http import HttpFD
9from ..utils import (
2e99cd30 10 error_to_compat_str,
95d8f7ea
S
11 encodeFilename,
12 sanitize_open,
69035555 13 sanitized_Request,
95d8f7ea
S
14)
15
16
17class HttpQuietDownloader(HttpFD):
18 def to_screen(self, *args, **kargs):
19 pass
20
21
22class FragmentFD(FileDownloader):
23 """
24 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
16a8b798
S
25
26 Available options:
27
9603b660
S
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)
0eee52f3
S
32 keep_fragments: Keep downloaded fragments on disk after downloading is
33 finished
290f64db
S
34
35 For each incomplete fragment download youtube-dl 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 youtube-dl). 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:
85f6de25 49 index: 0-based index of current fragment among all fragments
290f64db
S
50 fragment_count:
51 Total count of fragments
50534b71 52
85f6de25 53 This feature is experimental and file format may change in future.
95d8f7ea
S
54 """
55
75a24854 56 def report_retry_fragment(self, err, frag_index, count, retries):
721f26b8 57 self.to_screen(
75a24854
RA
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)))
721f26b8 60
75a24854
RA
61 def report_skip_fragment(self, frag_index):
62 self.to_screen('[download] Skipping fragment %d...' % frag_index)
9603b660 63
69035555
S
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
95d8f7ea
S
68 def _prepare_and_start_frag_download(self, ctx):
69 self._prepare_frag_download(ctx)
70 self._start_frag_download(ctx)
71
adb4b03c
S
72 @staticmethod
73 def __do_ytdl_file(ctx):
74 return not ctx['live'] and not ctx['tmpfilename'] == '-'
75
d3f0687c
S
76 def _read_ytdl_file(self, ctx):
77 stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
290f64db 78 ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
d3f0687c
S
79 stream.close()
80
81 def _write_ytdl_file(self, ctx):
82 frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
290f64db
S
83 downloader = {
84 'current_fragment': {
85 'index': ctx['fragment_index'],
d3f0687c 86 },
290f64db
S
87 }
88 if ctx.get('fragment_count') is not None:
89 downloader['fragment_count'] = ctx['fragment_count']
90 frag_index_stream.write(json.dumps({'downloader': downloader}))
d3f0687c
S
91 frag_index_stream.close()
92
75a24854 93 def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
d3f0687c
S
94 fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
95 success = ctx['dl'].download(fragment_filename, {
75a24854
RA
96 'url': frag_url,
97 'http_headers': headers or info_dict.get('http_headers'),
98 })
99 if not success:
100 return False, None
d3f0687c
S
101 down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
102 ctx['fragment_filename_sanitized'] = frag_sanitized
103 frag_content = down.read()
75a24854
RA
104 down.close()
105 return True, frag_content
106
107 def _append_fragment(self, ctx, frag_content):
d3f0687c
S
108 try:
109 ctx['dest_stream'].write(frag_content)
110 finally:
adb4b03c 111 if self.__do_ytdl_file(ctx):
d3f0687c 112 self._write_ytdl_file(ctx)
0eee52f3
S
113 if not self.params.get('keep_fragments', False):
114 os.remove(ctx['fragment_filename_sanitized'])
d3f0687c 115 del ctx['fragment_filename_sanitized']
75a24854 116
95d8f7ea 117 def _prepare_frag_download(self, ctx):
5fa1702c
S
118 if 'live' not in ctx:
119 ctx['live'] = False
5efaf43c
S
120 if not ctx['live']:
121 total_frags_str = '%d' % ctx['total_frags']
122 ad_frags = ctx.get('ad_frags', 0)
123 if ad_frags:
124 total_frags_str += ' (not including %d ad)' % ad_frags
125 else:
126 total_frags_str = 'unknown (live)'
5fa1702c 127 self.to_screen(
5efaf43c 128 '[%s] Total fragments: %s' % (self.FD_NAME, total_frags_str))
95d8f7ea
S
129 self.report_destination(ctx['filename'])
130 dl = HttpQuietDownloader(
131 self.ydl,
132 {
133 'continuedl': True,
134 'quiet': True,
135 'noprogress': True,
d800609c 136 'ratelimit': self.params.get('ratelimit'),
6828c809 137 'retries': self.params.get('retries', 0),
7097bffb 138 'nopart': self.params.get('nopart', False),
95d8f7ea
S
139 'test': self.params.get('test', False),
140 }
141 )
142 tmpfilename = self.temp_name(ctx['filename'])
75a24854
RA
143 open_mode = 'wb'
144 resume_len = 0
d3f0687c 145
75a24854
RA
146 # Establish possible resume length
147 if os.path.isfile(encodeFilename(tmpfilename)):
148 open_mode = 'ab'
149 resume_len = os.path.getsize(encodeFilename(tmpfilename))
d3f0687c 150
adb4b03c
S
151 # Should be initialized before ytdl file check
152 ctx.update({
153 'tmpfilename': tmpfilename,
154 'fragment_index': 0,
155 })
d3f0687c 156
adb4b03c
S
157 if self.__do_ytdl_file(ctx):
158 if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
159 self._read_ytdl_file(ctx)
e7c3e334 160 if ctx['fragment_index'] > 0 and resume_len == 0:
6f3b4a98 161 self.report_warning(
e7c3e334
S
162 'Inconsistent state of incomplete fragment download. '
163 'Restarting from the beginning...')
164 ctx['fragment_index'] = resume_len = 0
165 self._write_ytdl_file(ctx)
adb4b03c
S
166 else:
167 self._write_ytdl_file(ctx)
e7c3e334 168 assert ctx['fragment_index'] == 0
d3f0687c 169
75a24854
RA
170 dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
171
95d8f7ea
S
172 ctx.update({
173 'dl': dl,
174 'dest_stream': dest_stream,
175 'tmpfilename': tmpfilename,
75a24854
RA
176 # Total complete fragments downloaded so far in bytes
177 'complete_frags_downloaded_bytes': resume_len,
95d8f7ea
S
178 })
179
180 def _start_frag_download(self, ctx):
181 total_frags = ctx['total_frags']
182 # This dict stores the download progress, it's updated by the progress
183 # hook
184 state = {
185 'status': 'downloading',
75a24854 186 'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
3e0304fe
RA
187 'fragment_index': ctx['fragment_index'],
188 'fragment_count': total_frags,
95d8f7ea
S
189 'filename': ctx['filename'],
190 'tmpfilename': ctx['tmpfilename'],
b83b782d
S
191 }
192
193 start = time.time()
194 ctx.update({
195 'started': start,
709185a2
S
196 # Amount of fragment's bytes downloaded by the time of the previous
197 # frag progress hook invocation
b83b782d
S
198 'prev_frag_downloaded_bytes': 0,
199 })
95d8f7ea
S
200
201 def frag_progress_hook(s):
202 if s['status'] not in ('downloading', 'finished'):
203 return
204
5fa1702c 205 time_now = time.time()
2c2f1efd 206 state['elapsed'] = time_now - start
3c91e416 207 frag_total_bytes = s.get('total_bytes') or 0
5fa1702c
S
208 if not ctx['live']:
209 estimated_size = (
210 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
3e0304fe 211 (state['fragment_index'] + 1) * total_frags)
5fa1702c 212 state['total_bytes_estimate'] = estimated_size
95d8f7ea 213
709185a2 214 if s['status'] == 'finished':
3e0304fe
RA
215 state['fragment_index'] += 1
216 ctx['fragment_index'] = state['fragment_index']
b83b782d
S
217 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
218 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
219 ctx['prev_frag_downloaded_bytes'] = 0
709185a2
S
220 else:
221 frag_downloaded_bytes = s['downloaded_bytes']
b83b782d 222 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
5fa1702c
S
223 if not ctx['live']:
224 state['eta'] = self.calc_eta(
225 start, time_now, estimated_size,
226 state['downloaded_bytes'])
1b5284b1
S
227 state['speed'] = s.get('speed') or ctx.get('speed')
228 ctx['speed'] = state['speed']
b83b782d 229 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
95d8f7ea
S
230 self._hook_progress(state)
231
232 ctx['dl'].add_progress_hook(frag_progress_hook)
233
234 return start
235
236 def _finish_frag_download(self, ctx):
237 ctx['dest_stream'].close()
adb4b03c
S
238 if self.__do_ytdl_file(ctx):
239 ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
240 if os.path.isfile(ytdl_filename):
241 os.remove(ytdl_filename)
95d8f7ea
S
242 elapsed = time.time() - ctx['started']
243 self.try_rename(ctx['tmpfilename'], ctx['filename'])
244 fsize = os.path.getsize(encodeFilename(ctx['filename']))
245
246 self._hook_progress({
247 'downloaded_bytes': fsize,
248 'total_bytes': fsize,
249 'filename': ctx['filename'],
250 'status': 'finished',
251 'elapsed': elapsed,
252 })