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 for _ in range(fragments_count):
200 res.append((segment, next(fragments_counter)))
202 if boot_info['live']:
208 def write_unsigned_int(stream, val):
209 stream.write(compat_struct_pack('!I', val))
212 def write_unsigned_int_24(stream, val):
213 stream.write(compat_struct_pack('!I', val)[1:])
216 def write_flv_header(stream):
217 """Writes the FLV header to stream"""
219 stream.write(b'FLV\x01')
220 stream.write(b'\x05')
221 stream.write(b'\x00\x00\x00\x09')
222 stream.write(b'\x00\x00\x00\x00')
225 def write_metadata_tag(stream, metadata):
226 """Writes optional metadata tag to stream"""
228 FLV_TAG_HEADER_LEN = 11
231 stream.write(SCRIPT_TAG)
232 write_unsigned_int_24(stream, len(metadata))
233 stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
234 stream.write(metadata)
235 write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
238 def remove_encrypted_media(media):
239 return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
240 'drmAdditionalHeaderSetId' not in e.attrib,
245 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
248 class F4mFD(FragmentFD):
250 A downloader for f4m manifests or AdobeHDS.
255 def _get_unencrypted_media(self, doc):
256 media = doc.findall(_add_ns('media'))
258 self.report_error('No media found')
259 for e in (doc.findall(_add_ns('drmAdditionalHeader')) +
260 doc.findall(_add_ns('drmAdditionalHeaderSet'))):
261 # If id attribute is missing it's valid for all media nodes
262 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
263 if 'id' not in e.attrib:
264 self.report_error('Missing ID in f4m DRM')
265 media = remove_encrypted_media(media)
267 self.report_error('Unsupported DRM')
270 def _get_bootstrap_from_url(self, bootstrap_url):
271 bootstrap = self.ydl.urlopen(bootstrap_url).read()
272 return read_bootstrap_info(bootstrap)
274 def _update_live_fragments(self, bootstrap_url, latest_fragment):
277 while (not fragments_list) and (retries > 0):
278 boot_info = self._get_bootstrap_from_url(bootstrap_url)
279 fragments_list = build_fragments_list(boot_info)
280 fragments_list = [f for f in fragments_list if f[1] > latest_fragment]
281 if not fragments_list:
282 # Retry after a while
286 if not fragments_list:
287 self.report_error('Failed to update fragments')
289 return fragments_list
291 def _parse_bootstrap_node(self, node, base_url):
292 # Sometimes non empty inline bootstrap info can be specified along
293 # with bootstrap url attribute (e.g. dummy inline bootstrap info
294 # contains whitespace characters in [1]). We will prefer bootstrap
295 # url over inline bootstrap info when present.
296 # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
297 bootstrap_url = node.get('url')
299 bootstrap_url = compat_urlparse.urljoin(
300 base_url, bootstrap_url)
301 boot_info = self._get_bootstrap_from_url(bootstrap_url)
304 bootstrap = base64.b64decode(node.text.encode('ascii'))
305 boot_info = read_bootstrap_info(bootstrap)
306 return boot_info, bootstrap_url
308 def real_download(self, filename, info_dict):
309 man_url = info_dict['url']
310 requested_bitrate = info_dict.get('tbr')
311 self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)
312 urlh = self.ydl.urlopen(man_url)
313 man_url = urlh.geturl()
314 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
315 # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
316 # and https://github.com/rg3/youtube-dl/issues/7823)
317 manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
319 doc = compat_etree_fromstring(manifest)
320 formats = [(int(f.attrib.get('bitrate', -1)), f)
321 for f in self._get_unencrypted_media(doc)]
322 if requested_bitrate is None or len(formats) == 1:
323 # get the best format
324 formats = sorted(formats, key=lambda f: f[0])
325 rate, media = formats[-1]
327 rate, media = list(filter(
328 lambda f: int(f[0]) == requested_bitrate, formats))[0]
330 base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
331 bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
332 boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, base_url)
333 live = boot_info['live']
334 metadata_node = media.find(_add_ns('metadata'))
335 if metadata_node is not None:
336 metadata = base64.b64decode(metadata_node.text.encode('ascii'))
340 fragments_list = build_fragments_list(boot_info)
341 test = self.params.get('test', False)
343 # We only download the first fragment
344 fragments_list = fragments_list[:1]
345 total_frags = len(fragments_list)
346 # For some akamai manifests we'll need to add a query to the fragment url
347 akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
350 'filename': filename,
351 'total_frags': total_frags,
355 self._prepare_frag_download(ctx)
357 dest_stream = ctx['dest_stream']
359 write_flv_header(dest_stream)
361 write_metadata_tag(dest_stream, metadata)
363 base_url_parsed = compat_urllib_parse_urlparse(base_url)
365 self._start_frag_download(ctx)
368 while fragments_list:
369 seg_i, frag_i = fragments_list.pop(0)
370 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
372 if base_url_parsed.query:
373 query.append(base_url_parsed.query)
375 query.append(akamai_pv.strip(';'))
376 if info_dict.get('extra_param_to_segment_url'):
377 query.append(info_dict['extra_param_to_segment_url'])
378 url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))
379 frag_filename = '%s-%s' % (ctx['tmpfilename'], name)
381 success = ctx['dl'].download(frag_filename, {'url': url_parsed.geturl()})
384 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
385 down_data = down.read()
387 reader = FlvReader(down_data)
390 _, box_type, box_data = reader.read_box_info()
391 except DataTruncatedError:
393 # In tests, segments may be truncated, and thus
394 # FlvReader may not be able to parse the whole
395 # chunk. If so, write the segment as is
396 # See https://github.com/rg3/youtube-dl/issues/9214
397 dest_stream.write(down_data)
400 if box_type == b'mdat':
401 dest_stream.write(box_data)
404 os.remove(encodeFilename(frag_sanitized))
406 frags_filenames.append(frag_sanitized)
407 except (compat_urllib_error.HTTPError, ) as err:
408 if live and (err.code == 404 or err.code == 410):
409 # We didn't keep up with the live window. Continue
410 # with the next available fragment.
411 msg = 'Fragment %d unavailable' % frag_i
412 self.report_warning(msg)
417 if not fragments_list and not test and live and bootstrap_url:
418 fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
419 total_frags += len(fragments_list)
420 if fragments_list and (fragments_list[0][1] > frag_i + 1):
421 msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
422 self.report_warning(msg)
424 self._finish_frag_download(ctx)
426 for frag_file in frags_filenames:
427 os.remove(encodeFilename(frag_file))