1 from __future__ import division, unicode_literals
9 from .fragment import FragmentFD
10 from ..compat import (
11 compat_etree_fromstring,
14 compat_urllib_parse_urlparse,
26 class DataTruncatedError(Exception):
30 class FlvReader(io.BytesIO):
33 The file format is documented in https://www.adobe.com/devnet/f4v.html
36 def read_bytes(self, n):
39 raise DataTruncatedError(
40 'FlvReader error: need %d bytes while only %d bytes got' % (
44 # Utility functions for reading numbers and strings
45 def read_unsigned_long_long(self):
46 return compat_struct_unpack('!Q', self.read_bytes(8))[0]
48 def read_unsigned_int(self):
49 return compat_struct_unpack('!I', self.read_bytes(4))[0]
51 def read_unsigned_char(self):
52 return compat_struct_unpack('!B', self.read_bytes(1))[0]
54 def read_string(self):
57 char = self.read_bytes(1)
63 def read_box_info(self):
65 Read a box and return the info as a tuple: (box_size, box_type, box_data)
67 real_size = size = self.read_unsigned_int()
68 box_type = self.read_bytes(4)
71 real_size = self.read_unsigned_long_long()
73 return real_size, box_type, self.read_bytes(real_size - header_end)
77 self.read_unsigned_char()
80 quality_entry_count = self.read_unsigned_char()
82 for i in range(quality_entry_count):
85 segment_run_count = self.read_unsigned_int()
87 for i in range(segment_run_count):
88 first_segment = self.read_unsigned_int()
89 fragments_per_segment = self.read_unsigned_int()
90 segments.append((first_segment, fragments_per_segment))
93 'segment_run': segments,
98 self.read_unsigned_char()
102 self.read_unsigned_int()
104 quality_entry_count = self.read_unsigned_char()
105 # QualitySegmentUrlModifiers
106 for i in range(quality_entry_count):
109 fragments_count = self.read_unsigned_int()
111 for i in range(fragments_count):
112 first = self.read_unsigned_int()
113 first_ts = self.read_unsigned_long_long()
114 duration = self.read_unsigned_int()
116 discontinuity_indicator = self.read_unsigned_char()
118 discontinuity_indicator = None
122 'duration': duration,
123 'discontinuity_indicator': discontinuity_indicator,
127 'fragments': fragments,
132 self.read_unsigned_char()
136 self.read_unsigned_int() # BootstrapinfoVersion
137 # Profile,Live,Update,Reserved
138 flags = self.read_unsigned_char()
139 live = flags & 0x20 != 0
141 self.read_unsigned_int()
143 self.read_unsigned_long_long()
144 # SmpteTimeCodeOffset
145 self.read_unsigned_long_long()
147 self.read_string() # MovieIdentifier
148 server_count = self.read_unsigned_char()
150 for i in range(server_count):
152 quality_count = self.read_unsigned_char()
154 for i in range(quality_count):
161 segments_count = self.read_unsigned_char()
163 for i in range(segments_count):
164 box_size, box_type, box_data = self.read_box_info()
165 assert box_type == b'asrt'
166 segment = FlvReader(box_data).read_asrt()
167 segments.append(segment)
168 fragments_run_count = self.read_unsigned_char()
170 for i in range(fragments_run_count):
171 box_size, box_type, box_data = self.read_box_info()
172 assert box_type == b'afrt'
173 fragments.append(FlvReader(box_data).read_afrt())
176 'segments': segments,
177 'fragments': fragments,
181 def read_bootstrap_info(self):
182 total_size, box_type, box_data = self.read_box_info()
183 assert box_type == b'abst'
184 return FlvReader(box_data).read_abst()
187 def read_bootstrap_info(bootstrap_bytes):
188 return FlvReader(bootstrap_bytes).read_bootstrap_info()
191 def build_fragments_list(boot_info):
192 """ Return a list of (segment, fragment) for each fragment in the video """
194 segment_run_table = boot_info['segments'][0]
195 fragment_run_entry_table = boot_info['fragments'][0]['fragments']
196 first_frag_number = fragment_run_entry_table[0]['first']
197 fragments_counter = itertools.count(first_frag_number)
198 for segment, fragments_count in segment_run_table['segment_run']:
199 # In some live HDS streams (for example Rai), `fragments_count` is
200 # abnormal and causing out-of-memory errors. It's OK to change the
201 # number of fragments for live streams as they are updated periodically
202 if fragments_count == 4294967295 and boot_info['live']:
204 for _ in range(fragments_count):
205 res.append((segment, next(fragments_counter)))
207 if boot_info['live']:
213 def write_unsigned_int(stream, val):
214 stream.write(compat_struct_pack('!I', val))
217 def write_unsigned_int_24(stream, val):
218 stream.write(compat_struct_pack('!I', val)[1:])
221 def write_flv_header(stream):
222 """Writes the FLV header to stream"""
224 stream.write(b'FLV\x01')
225 stream.write(b'\x05')
226 stream.write(b'\x00\x00\x00\x09')
227 stream.write(b'\x00\x00\x00\x00')
230 def write_metadata_tag(stream, metadata):
231 """Writes optional metadata tag to stream"""
233 FLV_TAG_HEADER_LEN = 11
236 stream.write(SCRIPT_TAG)
237 write_unsigned_int_24(stream, len(metadata))
238 stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
239 stream.write(metadata)
240 write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
243 def remove_encrypted_media(media):
244 return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
245 'drmAdditionalHeaderSetId' not in e.attrib,
250 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
253 class F4mFD(FragmentFD):
255 A downloader for f4m manifests or AdobeHDS.
260 def _get_unencrypted_media(self, doc):
261 media = doc.findall(_add_ns('media'))
263 self.report_error('No media found')
264 for e in (doc.findall(_add_ns('drmAdditionalHeader')) +
265 doc.findall(_add_ns('drmAdditionalHeaderSet'))):
266 # If id attribute is missing it's valid for all media nodes
267 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
268 if 'id' not in e.attrib:
269 self.report_error('Missing ID in f4m DRM')
270 media = remove_encrypted_media(media)
272 self.report_error('Unsupported DRM')
275 def _get_bootstrap_from_url(self, bootstrap_url):
276 bootstrap = self.ydl.urlopen(bootstrap_url).read()
277 return read_bootstrap_info(bootstrap)
279 def _update_live_fragments(self, bootstrap_url, latest_fragment):
282 while (not fragments_list) and (retries > 0):
283 boot_info = self._get_bootstrap_from_url(bootstrap_url)
284 fragments_list = build_fragments_list(boot_info)
285 fragments_list = [f for f in fragments_list if f[1] > latest_fragment]
286 if not fragments_list:
287 # Retry after a while
291 if not fragments_list:
292 self.report_error('Failed to update fragments')
294 return fragments_list
296 def _parse_bootstrap_node(self, node, base_url):
297 # Sometimes non empty inline bootstrap info can be specified along
298 # with bootstrap url attribute (e.g. dummy inline bootstrap info
299 # contains whitespace characters in [1]). We will prefer bootstrap
300 # url over inline bootstrap info when present.
301 # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
302 bootstrap_url = node.get('url')
304 bootstrap_url = compat_urlparse.urljoin(
305 base_url, bootstrap_url)
306 boot_info = self._get_bootstrap_from_url(bootstrap_url)
309 bootstrap = base64.b64decode(node.text.encode('ascii'))
310 boot_info = read_bootstrap_info(bootstrap)
311 return boot_info, bootstrap_url
313 def real_download(self, filename, info_dict):
314 man_url = info_dict['url']
315 requested_bitrate = info_dict.get('tbr')
316 self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)
318 urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))
319 man_url = urlh.geturl()
320 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
321 # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
322 # and https://github.com/rg3/youtube-dl/issues/7823)
323 manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
325 doc = compat_etree_fromstring(manifest)
326 formats = [(int(f.attrib.get('bitrate', -1)), f)
327 for f in self._get_unencrypted_media(doc)]
328 if requested_bitrate is None or len(formats) == 1:
329 # get the best format
330 formats = sorted(formats, key=lambda f: f[0])
331 rate, media = formats[-1]
333 rate, media = list(filter(
334 lambda f: int(f[0]) == requested_bitrate, formats))[0]
336 base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
337 bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
338 # From Adobe F4M 3.0 spec:
339 # The <baseURL> element SHALL be the base URL for all relative
340 # (HTTP-based) URLs in the manifest. If <baseURL> is not present, said
341 # URLs should be relative to the location of the containing document.
342 boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, man_url)
343 live = boot_info['live']
344 metadata_node = media.find(_add_ns('metadata'))
345 if metadata_node is not None:
346 metadata = base64.b64decode(metadata_node.text.encode('ascii'))
350 fragments_list = build_fragments_list(boot_info)
351 test = self.params.get('test', False)
353 # We only download the first fragment
354 fragments_list = fragments_list[:1]
355 total_frags = len(fragments_list)
356 # For some akamai manifests we'll need to add a query to the fragment url
357 akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
360 'filename': filename,
361 'total_frags': total_frags,
365 self._prepare_frag_download(ctx)
367 dest_stream = ctx['dest_stream']
369 write_flv_header(dest_stream)
371 write_metadata_tag(dest_stream, metadata)
373 base_url_parsed = compat_urllib_parse_urlparse(base_url)
375 self._start_frag_download(ctx)
378 while fragments_list:
379 seg_i, frag_i = fragments_list.pop(0)
380 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
382 if base_url_parsed.query:
383 query.append(base_url_parsed.query)
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 frag_filename = '%s-%s' % (ctx['tmpfilename'], name)
391 success = ctx['dl'].download(frag_filename, {
392 'url': url_parsed.geturl(),
393 'http_headers': info_dict.get('http_headers'),
397 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
398 down_data = down.read()
400 reader = FlvReader(down_data)
403 _, box_type, box_data = reader.read_box_info()
404 except DataTruncatedError:
406 # In tests, segments may be truncated, and thus
407 # FlvReader may not be able to parse the whole
408 # chunk. If so, write the segment as is
409 # See https://github.com/rg3/youtube-dl/issues/9214
410 dest_stream.write(down_data)
413 if box_type == b'mdat':
414 dest_stream.write(box_data)
417 os.remove(encodeFilename(frag_sanitized))
419 frags_filenames.append(frag_sanitized)
420 except (compat_urllib_error.HTTPError, ) as err:
421 if live and (err.code == 404 or err.code == 410):
422 # We didn't keep up with the live window. Continue
423 # with the next available fragment.
424 msg = 'Fragment %d unavailable' % frag_i
425 self.report_warning(msg)
430 if not fragments_list and not test and live and bootstrap_url:
431 fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
432 total_frags += len(fragments_list)
433 if fragments_list and (fragments_list[0][1] > frag_i + 1):
434 msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
435 self.report_warning(msg)
437 self._finish_frag_download(ctx)
439 for frag_file in frags_filenames:
440 os.remove(encodeFilename(frag_file))