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 FlvReader(io
.BytesIO
):
29 The file format is documented in https://www.adobe.com/devnet/f4v.html
32 # Utility functions for reading numbers and strings
33 def read_unsigned_long_long(self
):
34 return struct_unpack('!Q', self
.read(8))[0]
36 def read_unsigned_int(self
):
37 return struct_unpack('!I', self
.read(4))[0]
39 def read_unsigned_char(self
):
40 return struct_unpack('!B', self
.read(1))[0]
42 def read_string(self
):
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(4)
59 real_size
= self
.read_unsigned_long_long()
61 return real_size
, box_type
, self
.read(real_size
- header_end
)
65 self
.read_unsigned_char()
68 quality_entry_count
= self
.read_unsigned_char()
70 for i
in range(quality_entry_count
):
73 segment_run_count
= self
.read_unsigned_int()
75 for i
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 i
in range(quality_entry_count
):
97 fragments_count
= self
.read_unsigned_int()
99 for i
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 i
in range(server_count
):
140 quality_count
= self
.read_unsigned_char()
142 for i
in range(quality_count
):
149 segments_count
= self
.read_unsigned_char()
151 for i
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 i
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 for _
in range(fragments_count
):
188 res
.append((segment
, next(fragments_counter
)))
190 if boot_info
['live']:
196 def write_unsigned_int(stream
, val
):
197 stream
.write(struct_pack('!I', val
))
200 def write_unsigned_int_24(stream
, val
):
201 stream
.write(struct_pack('!I', val
)[1:])
204 def write_flv_header(stream
):
205 """Writes the FLV header to stream"""
207 stream
.write(b
'FLV\x01')
208 stream
.write(b
'\x05')
209 stream
.write(b
'\x00\x00\x00\x09')
210 stream
.write(b
'\x00\x00\x00\x00')
213 def write_metadata_tag(stream
, metadata
):
214 """Writes optional metadata tag to stream"""
216 FLV_TAG_HEADER_LEN
= 11
219 stream
.write(SCRIPT_TAG
)
220 write_unsigned_int_24(stream
, len(metadata
))
221 stream
.write(b
'\x00\x00\x00\x00\x00\x00\x00')
222 stream
.write(metadata
)
223 write_unsigned_int(stream
, FLV_TAG_HEADER_LEN
+ len(metadata
))
227 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
230 class F4mFD(FragmentFD
):
232 A downloader for f4m manifests or AdobeHDS.
237 def _get_unencrypted_media(self
, doc
):
238 media
= doc
.findall(_add_ns('media'))
240 self
.report_error('No media found')
241 for e
in (doc
.findall(_add_ns('drmAdditionalHeader')) +
242 doc
.findall(_add_ns('drmAdditionalHeaderSet'))):
243 # If id attribute is missing it's valid for all media nodes
244 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
245 if 'id' not in e
.attrib
:
246 self
.report_error('Missing ID in f4m DRM')
247 media
= list(filter(lambda e
: 'drmAdditionalHeaderId' not in e
.attrib
and
248 'drmAdditionalHeaderSetId' not in e
.attrib
,
251 self
.report_error('Unsupported DRM')
254 def _get_bootstrap_from_url(self
, bootstrap_url
):
255 bootstrap
= self
.ydl
.urlopen(bootstrap_url
).read()
256 return read_bootstrap_info(bootstrap
)
258 def _update_live_fragments(self
, bootstrap_url
, latest_fragment
):
261 while (not fragments_list
) and (retries
> 0):
262 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
263 fragments_list
= build_fragments_list(boot_info
)
264 fragments_list
= [f
for f
in fragments_list
if f
[1] > latest_fragment
]
265 if not fragments_list
:
266 # Retry after a while
270 if not fragments_list
:
271 self
.report_error('Failed to update fragments')
273 return fragments_list
275 def _parse_bootstrap_node(self
, node
, base_url
):
276 # Sometimes non empty inline bootstrap info can be specified along
277 # with bootstrap url attribute (e.g. dummy inline bootstrap info
278 # contains whitespace characters in [1]). We will prefer bootstrap
279 # url over inline bootstrap info when present.
280 # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
281 bootstrap_url
= node
.get('url')
283 bootstrap_url
= compat_urlparse
.urljoin(
284 base_url
, bootstrap_url
)
285 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
288 bootstrap
= base64
.b64decode(node
.text
.encode('ascii'))
289 boot_info
= read_bootstrap_info(bootstrap
)
290 return boot_info
, bootstrap_url
292 def real_download(self
, filename
, info_dict
):
293 man_url
= info_dict
['url']
294 requested_bitrate
= info_dict
.get('tbr')
295 self
.to_screen('[%s] Downloading f4m manifest' % self
.FD_NAME
)
296 urlh
= self
.ydl
.urlopen(man_url
)
297 man_url
= urlh
.geturl()
298 # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
299 # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
300 # and https://github.com/rg3/youtube-dl/issues/7823)
301 manifest
= fix_xml_ampersands(urlh
.read().decode('utf-8', 'ignore')).strip()
303 doc
= compat_etree_fromstring(manifest
)
304 formats
= [(int(f
.attrib
.get('bitrate', -1)), f
)
305 for f
in self
._get
_unencrypted
_media
(doc
)]
306 if requested_bitrate
is None:
307 # get the best format
308 formats
= sorted(formats
, key
=lambda f
: f
[0])
309 rate
, media
= formats
[-1]
311 rate
, media
= list(filter(
312 lambda f
: int(f
[0]) == requested_bitrate
, formats
))[0]
314 base_url
= compat_urlparse
.urljoin(man_url
, media
.attrib
['url'])
315 bootstrap_node
= doc
.find(_add_ns('bootstrapInfo'))
316 boot_info
, bootstrap_url
= self
._parse
_bootstrap
_node
(bootstrap_node
, base_url
)
317 live
= boot_info
['live']
318 metadata_node
= media
.find(_add_ns('metadata'))
319 if metadata_node
is not None:
320 metadata
= base64
.b64decode(metadata_node
.text
.encode('ascii'))
324 fragments_list
= build_fragments_list(boot_info
)
325 test
= self
.params
.get('test', False)
327 # We only download the first fragment
328 fragments_list
= fragments_list
[:1]
329 total_frags
= len(fragments_list
)
330 # For some akamai manifests we'll need to add a query to the fragment url
331 akamai_pv
= xpath_text(doc
, _add_ns('pv-2.0'))
334 'filename': filename
,
335 'total_frags': total_frags
,
339 self
._prepare
_frag
_download
(ctx
)
341 dest_stream
= ctx
['dest_stream']
343 write_flv_header(dest_stream
)
345 write_metadata_tag(dest_stream
, metadata
)
347 base_url_parsed
= compat_urllib_parse_urlparse(base_url
)
349 self
._start
_frag
_download
(ctx
)
352 while fragments_list
:
353 seg_i
, frag_i
= fragments_list
.pop(0)
354 name
= 'Seg%d-Frag%d' % (seg_i
, frag_i
)
356 if base_url_parsed
.query
:
357 query
.append(base_url_parsed
.query
)
359 query
.append(akamai_pv
.strip(';'))
360 if info_dict
.get('extra_param_to_segment_url'):
361 query
.append(info_dict
['extra_param_to_segment_url'])
362 url_parsed
= base_url_parsed
._replace
(path
=base_url_parsed
.path
+ name
, query
='&'.join(query
))
363 frag_filename
= '%s-%s' % (ctx
['tmpfilename'], name
)
365 success
= ctx
['dl'].download(frag_filename
, {'url': url_parsed
.geturl()})
368 (down
, frag_sanitized
) = sanitize_open(frag_filename
, 'rb')
369 down_data
= down
.read()
371 reader
= FlvReader(down_data
)
373 _
, box_type
, box_data
= reader
.read_box_info()
374 if box_type
== b
'mdat':
375 dest_stream
.write(box_data
)
378 os
.remove(encodeFilename(frag_sanitized
))
380 frags_filenames
.append(frag_sanitized
)
381 except (compat_urllib_error
.HTTPError
, ) as err
:
382 if live
and (err
.code
== 404 or err
.code
== 410):
383 # We didn't keep up with the live window. Continue
384 # with the next available fragment.
385 msg
= 'Fragment %d unavailable' % frag_i
386 self
.report_warning(msg
)
391 if not fragments_list
and not test
and live
and bootstrap_url
:
392 fragments_list
= self
._update
_live
_fragments
(bootstrap_url
, frag_i
)
393 total_frags
+= len(fragments_list
)
394 if fragments_list
and (fragments_list
[0][1] > frag_i
+ 1):
395 msg
= 'Missed %d fragments' % (fragments_list
[0][1] - (frag_i
+ 1))
396 self
.report_warning(msg
)
398 self
._finish
_frag
_download
(ctx
)
400 for frag_file
in frags_filenames
:
401 os
.remove(encodeFilename(frag_file
))