1 from __future__
import division
, unicode_literals
8 from .fragment
import FragmentFD
10 compat_etree_fromstring
,
13 compat_urllib_parse_urlparse
,
23 class DataTruncatedError(Exception):
27 class FlvReader(io
.BytesIO
):
30 The file format is documented in https://www.adobe.com/devnet/f4v.html
33 def read_bytes(self
, n
):
36 raise DataTruncatedError(
37 'FlvReader error: need %d bytes while only %d bytes got' % (
41 # Utility functions for reading numbers and strings
42 def read_unsigned_long_long(self
):
43 return compat_struct_unpack('!Q', self
.read_bytes(8))[0]
45 def read_unsigned_int(self
):
46 return compat_struct_unpack('!I', self
.read_bytes(4))[0]
48 def read_unsigned_char(self
):
49 return compat_struct_unpack('!B', self
.read_bytes(1))[0]
51 def read_string(self
):
54 char
= self
.read_bytes(1)
60 def read_box_info(self
):
62 Read a box and return the info as a tuple: (box_size, box_type, box_data)
64 real_size
= size
= self
.read_unsigned_int()
65 box_type
= self
.read_bytes(4)
68 real_size
= self
.read_unsigned_long_long()
70 return real_size
, box_type
, self
.read_bytes(real_size
- header_end
)
74 self
.read_unsigned_char()
77 quality_entry_count
= self
.read_unsigned_char()
79 for i
in range(quality_entry_count
):
82 segment_run_count
= self
.read_unsigned_int()
84 for i
in range(segment_run_count
):
85 first_segment
= self
.read_unsigned_int()
86 fragments_per_segment
= self
.read_unsigned_int()
87 segments
.append((first_segment
, fragments_per_segment
))
90 'segment_run': segments
,
95 self
.read_unsigned_char()
99 self
.read_unsigned_int()
101 quality_entry_count
= self
.read_unsigned_char()
102 # QualitySegmentUrlModifiers
103 for i
in range(quality_entry_count
):
106 fragments_count
= self
.read_unsigned_int()
108 for i
in range(fragments_count
):
109 first
= self
.read_unsigned_int()
110 first_ts
= self
.read_unsigned_long_long()
111 duration
= self
.read_unsigned_int()
113 discontinuity_indicator
= self
.read_unsigned_char()
115 discontinuity_indicator
= None
119 'duration': duration
,
120 'discontinuity_indicator': discontinuity_indicator
,
124 'fragments': fragments
,
129 self
.read_unsigned_char()
133 self
.read_unsigned_int() # BootstrapinfoVersion
134 # Profile,Live,Update,Reserved
135 flags
= self
.read_unsigned_char()
136 live
= flags
& 0x20 != 0
138 self
.read_unsigned_int()
140 self
.read_unsigned_long_long()
141 # SmpteTimeCodeOffset
142 self
.read_unsigned_long_long()
144 self
.read_string() # MovieIdentifier
145 server_count
= self
.read_unsigned_char()
147 for i
in range(server_count
):
149 quality_count
= self
.read_unsigned_char()
151 for i
in range(quality_count
):
158 segments_count
= self
.read_unsigned_char()
160 for i
in range(segments_count
):
161 box_size
, box_type
, box_data
= self
.read_box_info()
162 assert box_type
== b
'asrt'
163 segment
= FlvReader(box_data
).read_asrt()
164 segments
.append(segment
)
165 fragments_run_count
= self
.read_unsigned_char()
167 for i
in range(fragments_run_count
):
168 box_size
, box_type
, box_data
= self
.read_box_info()
169 assert box_type
== b
'afrt'
170 fragments
.append(FlvReader(box_data
).read_afrt())
173 'segments': segments
,
174 'fragments': fragments
,
178 def read_bootstrap_info(self
):
179 total_size
, box_type
, box_data
= self
.read_box_info()
180 assert box_type
== b
'abst'
181 return FlvReader(box_data
).read_abst()
184 def read_bootstrap_info(bootstrap_bytes
):
185 return FlvReader(bootstrap_bytes
).read_bootstrap_info()
188 def build_fragments_list(boot_info
):
189 """ Return a list of (segment, fragment) for each fragment in the video """
191 segment_run_table
= boot_info
['segments'][0]
192 fragment_run_entry_table
= boot_info
['fragments'][0]['fragments']
193 first_frag_number
= fragment_run_entry_table
[0]['first']
194 fragments_counter
= itertools
.count(first_frag_number
)
195 for segment
, fragments_count
in segment_run_table
['segment_run']:
196 # In some live HDS streams (for example Rai), `fragments_count` is
197 # abnormal and causing out-of-memory errors. It's OK to change the
198 # number of fragments for live streams as they are updated periodically
199 if fragments_count
== 4294967295 and boot_info
['live']:
201 for _
in range(fragments_count
):
202 res
.append((segment
, next(fragments_counter
)))
204 if boot_info
['live']:
210 def write_unsigned_int(stream
, val
):
211 stream
.write(compat_struct_pack('!I', val
))
214 def write_unsigned_int_24(stream
, val
):
215 stream
.write(compat_struct_pack('!I', val
)[1:])
218 def write_flv_header(stream
):
219 """Writes the FLV header to stream"""
221 stream
.write(b
'FLV\x01')
222 stream
.write(b
'\x05')
223 stream
.write(b
'\x00\x00\x00\x09')
224 stream
.write(b
'\x00\x00\x00\x00')
227 def write_metadata_tag(stream
, metadata
):
228 """Writes optional metadata tag to stream"""
230 FLV_TAG_HEADER_LEN
= 11
233 stream
.write(SCRIPT_TAG
)
234 write_unsigned_int_24(stream
, len(metadata
))
235 stream
.write(b
'\x00\x00\x00\x00\x00\x00\x00')
236 stream
.write(metadata
)
237 write_unsigned_int(stream
, FLV_TAG_HEADER_LEN
+ len(metadata
))
240 def remove_encrypted_media(media
):
241 return list(filter(lambda e
: 'drmAdditionalHeaderId' not in e
.attrib
and
242 'drmAdditionalHeaderSetId' not in e
.attrib
,
247 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
250 class F4mFD(FragmentFD
):
252 A downloader for f4m manifests or AdobeHDS.
257 def _get_unencrypted_media(self
, doc
):
258 media
= doc
.findall(_add_ns('media'))
260 self
.report_error('No media found')
261 for e
in (doc
.findall(_add_ns('drmAdditionalHeader')) +
262 doc
.findall(_add_ns('drmAdditionalHeaderSet'))):
263 # If id attribute is missing it's valid for all media nodes
264 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
265 if 'id' not in e
.attrib
:
266 self
.report_error('Missing ID in f4m DRM')
267 media
= remove_encrypted_media(media
)
269 self
.report_error('Unsupported DRM')
272 def _get_bootstrap_from_url(self
, bootstrap_url
):
273 bootstrap
= self
.ydl
.urlopen(bootstrap_url
).read()
274 return read_bootstrap_info(bootstrap
)
276 def _update_live_fragments(self
, bootstrap_url
, latest_fragment
):
279 while (not fragments_list
) and (retries
> 0):
280 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
281 fragments_list
= build_fragments_list(boot_info
)
282 fragments_list
= [f
for f
in fragments_list
if f
[1] > latest_fragment
]
283 if not fragments_list
:
284 # Retry after a while
288 if not fragments_list
:
289 self
.report_error('Failed to update fragments')
291 return fragments_list
293 def _parse_bootstrap_node(self
, node
, base_url
):
294 # Sometimes non empty inline bootstrap info can be specified along
295 # with bootstrap url attribute (e.g. dummy inline bootstrap info
296 # contains whitespace characters in [1]). We will prefer bootstrap
297 # url over inline bootstrap info when present.
298 # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
299 bootstrap_url
= node
.get('url')
301 bootstrap_url
= compat_urlparse
.urljoin(
302 base_url
, bootstrap_url
)
303 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
306 bootstrap
= base64
.b64decode(node
.text
.encode('ascii'))
307 boot_info
= read_bootstrap_info(bootstrap
)
308 return boot_info
, bootstrap_url
310 def real_download(self
, filename
, info_dict
):
311 man_url
= info_dict
['url']
312 requested_bitrate
= info_dict
.get('tbr')
313 self
.to_screen('[%s] Downloading f4m manifest' % self
.FD_NAME
)
315 urlh
= self
.ydl
.urlopen(self
._prepare
_url
(info_dict
, man_url
))
316 man_url
= urlh
.geturl()
317 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
318 # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
319 # and https://github.com/rg3/youtube-dl/issues/7823)
320 manifest
= fix_xml_ampersands(urlh
.read().decode('utf-8', 'ignore')).strip()
322 doc
= compat_etree_fromstring(manifest
)
323 formats
= [(int(f
.attrib
.get('bitrate', -1)), f
)
324 for f
in self
._get
_unencrypted
_media
(doc
)]
325 if requested_bitrate
is None or len(formats
) == 1:
326 # get the best format
327 formats
= sorted(formats
, key
=lambda f
: f
[0])
328 rate
, media
= formats
[-1]
330 rate
, media
= list(filter(
331 lambda f
: int(f
[0]) == requested_bitrate
, formats
))[0]
333 base_url
= compat_urlparse
.urljoin(man_url
, media
.attrib
['url'])
334 bootstrap_node
= doc
.find(_add_ns('bootstrapInfo'))
335 # From Adobe F4M 3.0 spec:
336 # The <baseURL> element SHALL be the base URL for all relative
337 # (HTTP-based) URLs in the manifest. If <baseURL> is not present, said
338 # URLs should be relative to the location of the containing document.
339 boot_info
, bootstrap_url
= self
._parse
_bootstrap
_node
(bootstrap_node
, man_url
)
340 live
= boot_info
['live']
341 metadata_node
= media
.find(_add_ns('metadata'))
342 if metadata_node
is not None:
343 metadata
= base64
.b64decode(metadata_node
.text
.encode('ascii'))
347 fragments_list
= build_fragments_list(boot_info
)
348 test
= self
.params
.get('test', False)
350 # We only download the first fragment
351 fragments_list
= fragments_list
[:1]
352 total_frags
= len(fragments_list
)
353 # For some akamai manifests we'll need to add a query to the fragment url
354 akamai_pv
= xpath_text(doc
, _add_ns('pv-2.0'))
357 'filename': filename
,
358 'total_frags': total_frags
,
362 self
._prepare
_frag
_download
(ctx
)
364 dest_stream
= ctx
['dest_stream']
366 if ctx
['complete_frags_downloaded_bytes'] == 0:
367 write_flv_header(dest_stream
)
369 write_metadata_tag(dest_stream
, metadata
)
371 base_url_parsed
= compat_urllib_parse_urlparse(base_url
)
373 self
._start
_frag
_download
(ctx
)
376 while fragments_list
:
377 seg_i
, frag_i
= fragments_list
.pop(0)
379 if frag_index
<= ctx
['fragment_index']:
381 name
= 'Seg%d-Frag%d' % (seg_i
, frag_i
)
383 if base_url_parsed
.query
:
384 query
.append(base_url_parsed
.query
)
386 query
.append(akamai_pv
.strip(';'))
387 if info_dict
.get('extra_param_to_segment_url'):
388 query
.append(info_dict
['extra_param_to_segment_url'])
389 url_parsed
= base_url_parsed
._replace
(path
=base_url_parsed
.path
+ name
, query
='&'.join(query
))
391 success
, down_data
= self
._download
_fragment
(ctx
, url_parsed
.geturl(), info_dict
)
394 reader
= FlvReader(down_data
)
397 _
, box_type
, box_data
= reader
.read_box_info()
398 except DataTruncatedError
:
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/rg3/youtube-dl/issues/9214
404 dest_stream
.write(down_data
)
407 if box_type
== b
'mdat':
408 self
._append
_fragment
(ctx
, box_data
)
410 except (compat_urllib_error
.HTTPError
, ) as err
:
411 if live
and (err
.code
== 404 or err
.code
== 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
)
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 self
._finish
_frag
_download
(ctx
)