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)
317 urlh = self.ydl.urlopen(man_url)
318 man_url = urlh.geturl()
319 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
320 # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
321 # and https://github.com/rg3/youtube-dl/issues/7823)
322 manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
324 doc = compat_etree_fromstring(manifest)
325 formats = [(int(f.attrib.get('bitrate', -1)), f)
326 for f in self._get_unencrypted_media(doc)]
327 if requested_bitrate is None or len(formats) == 1:
328 # get the best format
329 formats = sorted(formats, key=lambda f: f[0])
330 rate, media = formats[-1]
332 rate, media = list(filter(
333 lambda f: int(f[0]) == requested_bitrate, formats))[0]
335 base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
336 bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
337 # From Adobe F4M 3.0 spec:
338 # The <baseURL> element SHALL be the base URL for all relative
339 # (HTTP-based) URLs in the manifest. If <baseURL> is not present, said
340 # URLs should be relative to the location of the containing document.
341 boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, man_url)
342 live = boot_info['live']
343 metadata_node = media.find(_add_ns('metadata'))
344 if metadata_node is not None:
345 metadata = base64.b64decode(metadata_node.text.encode('ascii'))
349 fragments_list = build_fragments_list(boot_info)
350 test = self.params.get('test', False)
352 # We only download the first fragment
353 fragments_list = fragments_list[:1]
354 total_frags = len(fragments_list)
355 # For some akamai manifests we'll need to add a query to the fragment url
356 akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
359 'filename': filename,
360 'total_frags': total_frags,
364 self._prepare_frag_download(ctx)
366 dest_stream = ctx['dest_stream']
368 write_flv_header(dest_stream)
370 write_metadata_tag(dest_stream, metadata)
372 base_url_parsed = compat_urllib_parse_urlparse(base_url)
374 self._start_frag_download(ctx)
377 while fragments_list:
378 seg_i, frag_i = fragments_list.pop(0)
379 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
381 if base_url_parsed.query:
382 query.append(base_url_parsed.query)
384 query.append(akamai_pv.strip(';'))
385 if info_dict.get('extra_param_to_segment_url'):
386 query.append(info_dict['extra_param_to_segment_url'])
387 url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))
388 frag_filename = '%s-%s' % (ctx['tmpfilename'], name)
390 success = ctx['dl'].download(frag_filename, {'url': url_parsed.geturl()})
393 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
394 down_data = down.read()
396 reader = FlvReader(down_data)
399 _, box_type, box_data = reader.read_box_info()
400 except DataTruncatedError:
402 # In tests, segments may be truncated, and thus
403 # FlvReader may not be able to parse the whole
404 # chunk. If so, write the segment as is
405 # See https://github.com/rg3/youtube-dl/issues/9214
406 dest_stream.write(down_data)
409 if box_type == b'mdat':
410 dest_stream.write(box_data)
413 os.remove(encodeFilename(frag_sanitized))
415 frags_filenames.append(frag_sanitized)
416 except (compat_urllib_error.HTTPError, ) as err:
417 if live and (err.code == 404 or err.code == 410):
418 # We didn't keep up with the live window. Continue
419 # with the next available fragment.
420 msg = 'Fragment %d unavailable' % frag_i
421 self.report_warning(msg)
426 if not fragments_list and not test and live and bootstrap_url:
427 fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
428 total_frags += len(fragments_list)
429 if fragments_list and (fragments_list[0][1] > frag_i + 1):
430 msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
431 self.report_warning(msg)
433 self._finish_frag_download(ctx)
435 for frag_file in frags_filenames:
436 os.remove(encodeFilename(frag_file))