[ie/tiktok] Fix and deprioritize JSON subtitles (#10516)
[yt-dlp3.git] / yt_dlp / downloader / f4m.py
blob22d0ebd26555fcb4a31bb4d69e4a79e79f718c09
1 import base64
2 import io
3 import itertools
4 import struct
5 import time
6 import urllib.parse
8 from .fragment import FragmentFD
9 from ..compat import compat_etree_fromstring
10 from ..networking.exceptions import HTTPError
11 from ..utils import fix_xml_ampersands, xpath_text
14 class DataTruncatedError(Exception):
15 pass
18 class FlvReader(io.BytesIO):
19 """
20 Reader for Flv files
21 The file format is documented in https://www.adobe.com/devnet/f4v.html
22 """
24 def read_bytes(self, n):
25 data = self.read(n)
26 if len(data) < n:
27 raise DataTruncatedError(
28 'FlvReader error: need %d bytes while only %d bytes got' % (
29 n, len(data)))
30 return data
32 # Utility functions for reading numbers and strings
33 def read_unsigned_long_long(self):
34 return struct.unpack('!Q', self.read_bytes(8))[0]
36 def read_unsigned_int(self):
37 return struct.unpack('!I', self.read_bytes(4))[0]
39 def read_unsigned_char(self):
40 return struct.unpack('!B', self.read_bytes(1))[0]
42 def read_string(self):
43 res = b''
44 while True:
45 char = self.read_bytes(1)
46 if char == b'\x00':
47 break
48 res += char
49 return res
51 def read_box_info(self):
52 """
53 Read a box and return the info as a tuple: (box_size, box_type, box_data)
54 """
55 real_size = size = self.read_unsigned_int()
56 box_type = self.read_bytes(4)
57 header_end = 8
58 if size == 1:
59 real_size = self.read_unsigned_long_long()
60 header_end = 16
61 return real_size, box_type, self.read_bytes(real_size - header_end)
63 def read_asrt(self):
64 # version
65 self.read_unsigned_char()
66 # flags
67 self.read_bytes(3)
68 quality_entry_count = self.read_unsigned_char()
69 # QualityEntryCount
70 for _ in range(quality_entry_count):
71 self.read_string()
73 segment_run_count = self.read_unsigned_int()
74 segments = []
75 for _ in range(segment_run_count):
76 first_segment = self.read_unsigned_int()
77 fragments_per_segment = self.read_unsigned_int()
78 segments.append((first_segment, fragments_per_segment))
80 return {
81 'segment_run': segments,
84 def read_afrt(self):
85 # version
86 self.read_unsigned_char()
87 # flags
88 self.read_bytes(3)
89 # time scale
90 self.read_unsigned_int()
92 quality_entry_count = self.read_unsigned_char()
93 # QualitySegmentUrlModifiers
94 for _ in range(quality_entry_count):
95 self.read_string()
97 fragments_count = self.read_unsigned_int()
98 fragments = []
99 for _ in range(fragments_count):
100 first = self.read_unsigned_int()
101 first_ts = self.read_unsigned_long_long()
102 duration = self.read_unsigned_int()
103 if duration == 0:
104 discontinuity_indicator = self.read_unsigned_char()
105 else:
106 discontinuity_indicator = None
107 fragments.append({
108 'first': first,
109 'ts': first_ts,
110 'duration': duration,
111 'discontinuity_indicator': discontinuity_indicator,
114 return {
115 'fragments': fragments,
118 def read_abst(self):
119 # version
120 self.read_unsigned_char()
121 # flags
122 self.read_bytes(3)
124 self.read_unsigned_int() # BootstrapinfoVersion
125 # Profile,Live,Update,Reserved
126 flags = self.read_unsigned_char()
127 live = flags & 0x20 != 0
128 # time scale
129 self.read_unsigned_int()
130 # CurrentMediaTime
131 self.read_unsigned_long_long()
132 # SmpteTimeCodeOffset
133 self.read_unsigned_long_long()
135 self.read_string() # MovieIdentifier
136 server_count = self.read_unsigned_char()
137 # ServerEntryTable
138 for _ in range(server_count):
139 self.read_string()
140 quality_count = self.read_unsigned_char()
141 # QualityEntryTable
142 for _ in range(quality_count):
143 self.read_string()
144 # DrmData
145 self.read_string()
146 # MetaData
147 self.read_string()
149 segments_count = self.read_unsigned_char()
150 segments = []
151 for _ in range(segments_count):
152 box_size, box_type, box_data = self.read_box_info()
153 assert box_type == b'asrt'
154 segment = FlvReader(box_data).read_asrt()
155 segments.append(segment)
156 fragments_run_count = self.read_unsigned_char()
157 fragments = []
158 for _ in range(fragments_run_count):
159 box_size, box_type, box_data = self.read_box_info()
160 assert box_type == b'afrt'
161 fragments.append(FlvReader(box_data).read_afrt())
163 return {
164 'segments': segments,
165 'fragments': fragments,
166 'live': live,
169 def read_bootstrap_info(self):
170 total_size, box_type, box_data = self.read_box_info()
171 assert box_type == b'abst'
172 return FlvReader(box_data).read_abst()
175 def read_bootstrap_info(bootstrap_bytes):
176 return FlvReader(bootstrap_bytes).read_bootstrap_info()
179 def build_fragments_list(boot_info):
180 """ Return a list of (segment, fragment) for each fragment in the video """
181 res = []
182 segment_run_table = boot_info['segments'][0]
183 fragment_run_entry_table = boot_info['fragments'][0]['fragments']
184 first_frag_number = fragment_run_entry_table[0]['first']
185 fragments_counter = itertools.count(first_frag_number)
186 for segment, fragments_count in segment_run_table['segment_run']:
187 # In some live HDS streams (e.g. Rai), `fragments_count` is
188 # abnormal and causing out-of-memory errors. It's OK to change the
189 # number of fragments for live streams as they are updated periodically
190 if fragments_count == 4294967295 and boot_info['live']:
191 fragments_count = 2
192 for _ in range(fragments_count):
193 res.append((segment, next(fragments_counter)))
195 if boot_info['live']:
196 res = res[-2:]
198 return res
201 def write_unsigned_int(stream, val):
202 stream.write(struct.pack('!I', val))
205 def write_unsigned_int_24(stream, val):
206 stream.write(struct.pack('!I', val)[1:])
209 def write_flv_header(stream):
210 """Writes the FLV header to stream"""
211 # FLV header
212 stream.write(b'FLV\x01')
213 stream.write(b'\x05')
214 stream.write(b'\x00\x00\x00\x09')
215 stream.write(b'\x00\x00\x00\x00')
218 def write_metadata_tag(stream, metadata):
219 """Writes optional metadata tag to stream"""
220 SCRIPT_TAG = b'\x12'
221 FLV_TAG_HEADER_LEN = 11
223 if metadata:
224 stream.write(SCRIPT_TAG)
225 write_unsigned_int_24(stream, len(metadata))
226 stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
227 stream.write(metadata)
228 write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
231 def remove_encrypted_media(media):
232 return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib
233 and 'drmAdditionalHeaderSetId' not in e.attrib,
234 media))
237 def _add_ns(prop, ver=1):
238 return '{http://ns.adobe.com/f4m/%d.0}%s' % (ver, prop)
241 def get_base_url(manifest):
242 base_url = xpath_text(
243 manifest, [_add_ns('baseURL'), _add_ns('baseURL', 2)],
244 'base URL', default=None)
245 if base_url:
246 base_url = base_url.strip()
247 return base_url
250 class F4mFD(FragmentFD):
252 A downloader for f4m manifests or AdobeHDS.
255 def _get_unencrypted_media(self, doc):
256 media = doc.findall(_add_ns('media'))
257 if not media:
258 self.report_error('No media found')
259 if not self.params.get('allow_unplayable_formats'):
260 for e in (doc.findall(_add_ns('drmAdditionalHeader'))
261 + doc.findall(_add_ns('drmAdditionalHeaderSet'))):
262 # If id attribute is missing it's valid for all media nodes
263 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
264 if 'id' not in e.attrib:
265 self.report_error('Missing ID in f4m DRM')
266 media = remove_encrypted_media(media)
267 if not media:
268 self.report_error('Unsupported DRM')
269 return media
271 def _get_bootstrap_from_url(self, bootstrap_url):
272 bootstrap = self.ydl.urlopen(bootstrap_url).read()
273 return read_bootstrap_info(bootstrap)
275 def _update_live_fragments(self, bootstrap_url, latest_fragment):
276 fragments_list = []
277 retries = 30
278 while (not fragments_list) and (retries > 0):
279 boot_info = self._get_bootstrap_from_url(bootstrap_url)
280 fragments_list = build_fragments_list(boot_info)
281 fragments_list = [f for f in fragments_list if f[1] > latest_fragment]
282 if not fragments_list:
283 # Retry after a while
284 time.sleep(5.0)
285 retries -= 1
287 if not fragments_list:
288 self.report_error('Failed to update fragments')
290 return fragments_list
292 def _parse_bootstrap_node(self, node, base_url):
293 # Sometimes non empty inline bootstrap info can be specified along
294 # with bootstrap url attribute (e.g. dummy inline bootstrap info
295 # contains whitespace characters in [1]). We will prefer bootstrap
296 # url over inline bootstrap info when present.
297 # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
298 bootstrap_url = node.get('url')
299 if bootstrap_url:
300 bootstrap_url = urllib.parse.urljoin(
301 base_url, bootstrap_url)
302 boot_info = self._get_bootstrap_from_url(bootstrap_url)
303 else:
304 bootstrap_url = None
305 bootstrap = base64.b64decode(node.text)
306 boot_info = read_bootstrap_info(bootstrap)
307 return boot_info, bootstrap_url
309 def real_download(self, filename, info_dict):
310 man_url = info_dict['url']
311 requested_bitrate = info_dict.get('tbr')
312 self.to_screen(f'[{self.FD_NAME}] Downloading f4m manifest')
314 urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))
315 man_url = urlh.url
316 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
317 # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244
318 # and https://github.com/ytdl-org/youtube-dl/issues/7823)
319 manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
321 doc = compat_etree_fromstring(manifest)
322 formats = [(int(f.attrib.get('bitrate', -1)), f)
323 for f in self._get_unencrypted_media(doc)]
324 if requested_bitrate is None or len(formats) == 1:
325 # get the best format
326 formats = sorted(formats, key=lambda f: f[0])
327 rate, media = formats[-1]
328 else:
329 rate, media = next(filter(
330 lambda f: int(f[0]) == requested_bitrate, formats))
332 # Prefer baseURL for relative URLs as per 11.2 of F4M 3.0 spec.
333 man_base_url = get_base_url(doc) or man_url
335 base_url = urllib.parse.urljoin(man_base_url, media.attrib['url'])
336 bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
337 boot_info, bootstrap_url = self._parse_bootstrap_node(
338 bootstrap_node, man_base_url)
339 live = boot_info['live']
340 metadata_node = media.find(_add_ns('metadata'))
341 if metadata_node is not None:
342 metadata = base64.b64decode(metadata_node.text)
343 else:
344 metadata = None
346 fragments_list = build_fragments_list(boot_info)
347 test = self.params.get('test', False)
348 if test:
349 # We only download the first fragment
350 fragments_list = fragments_list[:1]
351 total_frags = len(fragments_list)
352 # For some akamai manifests we'll need to add a query to the fragment url
353 akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
355 ctx = {
356 'filename': filename,
357 'total_frags': total_frags,
358 'live': bool(live),
361 self._prepare_frag_download(ctx)
363 dest_stream = ctx['dest_stream']
365 if ctx['complete_frags_downloaded_bytes'] == 0:
366 write_flv_header(dest_stream)
367 if not live:
368 write_metadata_tag(dest_stream, metadata)
370 base_url_parsed = urllib.parse.urlparse(base_url)
372 self._start_frag_download(ctx, info_dict)
374 frag_index = 0
375 while fragments_list:
376 seg_i, frag_i = fragments_list.pop(0)
377 frag_index += 1
378 if frag_index <= ctx['fragment_index']:
379 continue
380 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
381 query = []
382 if base_url_parsed.query:
383 query.append(base_url_parsed.query)
384 if akamai_pv:
385 query.append(akamai_pv.strip(';'))
386 if info_dict.get('extra_param_to_segment_url'):
387 query.append(info_dict['extra_param_to_segment_url'])
388 url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))
389 try:
390 success = self._download_fragment(ctx, url_parsed.geturl(), info_dict)
391 if not success:
392 return False
393 down_data = self._read_fragment(ctx)
394 reader = FlvReader(down_data)
395 while True:
396 try:
397 _, box_type, box_data = reader.read_box_info()
398 except DataTruncatedError:
399 if test:
400 # In tests, segments may be truncated, and thus
401 # FlvReader may not be able to parse the whole
402 # chunk. If so, write the segment as is
403 # See https://github.com/ytdl-org/youtube-dl/issues/9214
404 dest_stream.write(down_data)
405 break
406 raise
407 if box_type == b'mdat':
408 self._append_fragment(ctx, box_data)
409 break
410 except HTTPError as err:
411 if live and (err.status == 404 or err.status == 410):
412 # We didn't keep up with the live window. Continue
413 # with the next available fragment.
414 msg = 'Fragment %d unavailable' % frag_i
415 self.report_warning(msg)
416 fragments_list = []
417 else:
418 raise
420 if not fragments_list and not test and live and bootstrap_url:
421 fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
422 total_frags += len(fragments_list)
423 if fragments_list and (fragments_list[0][1] > frag_i + 1):
424 msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
425 self.report_warning(msg)
427 return self._finish_frag_download(ctx, info_dict)