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):
18 class FlvReader(io
.BytesIO
):
21 The file format is documented in https://www.adobe.com/devnet/f4v.html
24 def read_bytes(self
, n
):
27 raise DataTruncatedError(
28 'FlvReader error: need %d bytes while only %d bytes got' % (
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
):
45 char
= self
.read_bytes(1)
51 def read_box_info(self
):
53 Read a box and return the info as a tuple: (box_size, box_type, box_data)
55 real_size
= size
= self
.read_unsigned_int()
56 box_type
= self
.read_bytes(4)
59 real_size
= self
.read_unsigned_long_long()
61 return real_size
, box_type
, self
.read_bytes(real_size
- header_end
)
65 self
.read_unsigned_char()
68 quality_entry_count
= self
.read_unsigned_char()
70 for _
in range(quality_entry_count
):
73 segment_run_count
= self
.read_unsigned_int()
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
))
81 'segment_run': segments
,
86 self
.read_unsigned_char()
90 self
.read_unsigned_int()
92 quality_entry_count
= self
.read_unsigned_char()
93 # QualitySegmentUrlModifiers
94 for _
in range(quality_entry_count
):
97 fragments_count
= self
.read_unsigned_int()
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()
104 discontinuity_indicator
= self
.read_unsigned_char()
106 discontinuity_indicator
= None
110 'duration': duration
,
111 'discontinuity_indicator': discontinuity_indicator
,
115 'fragments': fragments
,
120 self
.read_unsigned_char()
124 self
.read_unsigned_int() # BootstrapinfoVersion
125 # Profile,Live,Update,Reserved
126 flags
= self
.read_unsigned_char()
127 live
= flags
& 0x20 != 0
129 self
.read_unsigned_int()
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()
138 for _
in range(server_count
):
140 quality_count
= self
.read_unsigned_char()
142 for _
in range(quality_count
):
149 segments_count
= self
.read_unsigned_char()
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()
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())
164 'segments': segments
,
165 'fragments': fragments
,
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 """
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']:
192 for _
in range(fragments_count
):
193 res
.append((segment
, next(fragments_counter
)))
195 if boot_info
['live']:
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"""
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"""
221 FLV_TAG_HEADER_LEN
= 11
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
,
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)
246 base_url
= base_url
.strip()
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'))
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
)
268 self
.report_error('Unsupported DRM')
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
):
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
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')
300 bootstrap_url
= urllib
.parse
.urljoin(
301 base_url
, bootstrap_url
)
302 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
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
))
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]
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
)
346 fragments_list
= build_fragments_list(boot_info
)
347 test
= self
.params
.get('test', False)
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'))
356 'filename': filename
,
357 'total_frags': total_frags
,
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
)
368 write_metadata_tag(dest_stream
, metadata
)
370 base_url_parsed
= urllib
.parse
.urlparse(base_url
)
372 self
._start
_frag
_download
(ctx
, info_dict
)
375 while fragments_list
:
376 seg_i
, frag_i
= fragments_list
.pop(0)
378 if frag_index
<= ctx
['fragment_index']:
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
))
390 success
= self
._download
_fragment
(ctx
, url_parsed
.geturl(), info_dict
)
393 down_data
= self
._read
_fragment
(ctx
)
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/ytdl-org/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 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
)
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
)