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
,
25 class FlvReader(io
.BytesIO
):
28 The file format is documented in https://www.adobe.com/devnet/f4v.html
31 # Utility functions for reading numbers and strings
32 def read_unsigned_long_long(self
):
33 return struct_unpack('!Q', self
.read(8))[0]
35 def read_unsigned_int(self
):
36 return struct_unpack('!I', self
.read(4))[0]
38 def read_unsigned_char(self
):
39 return struct_unpack('!B', self
.read(1))[0]
41 def read_string(self
):
50 def read_box_info(self
):
52 Read a box and return the info as a tuple: (box_size, box_type, box_data)
54 real_size
= size
= self
.read_unsigned_int()
55 box_type
= self
.read(4)
58 real_size
= self
.read_unsigned_long_long()
60 return real_size
, box_type
, self
.read(real_size
- header_end
)
64 self
.read_unsigned_char()
67 quality_entry_count
= self
.read_unsigned_char()
69 for i
in range(quality_entry_count
):
72 segment_run_count
= self
.read_unsigned_int()
74 for i
in range(segment_run_count
):
75 first_segment
= self
.read_unsigned_int()
76 fragments_per_segment
= self
.read_unsigned_int()
77 segments
.append((first_segment
, fragments_per_segment
))
80 'segment_run': segments
,
85 self
.read_unsigned_char()
89 self
.read_unsigned_int()
91 quality_entry_count
= self
.read_unsigned_char()
92 # QualitySegmentUrlModifiers
93 for i
in range(quality_entry_count
):
96 fragments_count
= self
.read_unsigned_int()
98 for i
in range(fragments_count
):
99 first
= self
.read_unsigned_int()
100 first_ts
= self
.read_unsigned_long_long()
101 duration
= self
.read_unsigned_int()
103 discontinuity_indicator
= self
.read_unsigned_char()
105 discontinuity_indicator
= None
109 'duration': duration
,
110 'discontinuity_indicator': discontinuity_indicator
,
114 'fragments': fragments
,
119 self
.read_unsigned_char()
123 self
.read_unsigned_int() # BootstrapinfoVersion
124 # Profile,Live,Update,Reserved
125 flags
= self
.read_unsigned_char()
126 live
= flags
& 0x20 != 0
128 self
.read_unsigned_int()
130 self
.read_unsigned_long_long()
131 # SmpteTimeCodeOffset
132 self
.read_unsigned_long_long()
134 self
.read_string() # MovieIdentifier
135 server_count
= self
.read_unsigned_char()
137 for i
in range(server_count
):
139 quality_count
= self
.read_unsigned_char()
141 for i
in range(quality_count
):
148 segments_count
= self
.read_unsigned_char()
150 for i
in range(segments_count
):
151 box_size
, box_type
, box_data
= self
.read_box_info()
152 assert box_type
== b
'asrt'
153 segment
= FlvReader(box_data
).read_asrt()
154 segments
.append(segment
)
155 fragments_run_count
= self
.read_unsigned_char()
157 for i
in range(fragments_run_count
):
158 box_size
, box_type
, box_data
= self
.read_box_info()
159 assert box_type
== b
'afrt'
160 fragments
.append(FlvReader(box_data
).read_afrt())
163 'segments': segments
,
164 'fragments': fragments
,
168 def read_bootstrap_info(self
):
169 total_size
, box_type
, box_data
= self
.read_box_info()
170 assert box_type
== b
'abst'
171 return FlvReader(box_data
).read_abst()
174 def read_bootstrap_info(bootstrap_bytes
):
175 return FlvReader(bootstrap_bytes
).read_bootstrap_info()
178 def build_fragments_list(boot_info
):
179 """ Return a list of (segment, fragment) for each fragment in the video """
181 segment_run_table
= boot_info
['segments'][0]
182 fragment_run_entry_table
= boot_info
['fragments'][0]['fragments']
183 first_frag_number
= fragment_run_entry_table
[0]['first']
184 fragments_counter
= itertools
.count(first_frag_number
)
185 for segment
, fragments_count
in segment_run_table
['segment_run']:
186 for _
in range(fragments_count
):
187 res
.append((segment
, next(fragments_counter
)))
189 if boot_info
['live']:
195 def write_unsigned_int(stream
, val
):
196 stream
.write(struct_pack('!I', val
))
199 def write_unsigned_int_24(stream
, val
):
200 stream
.write(struct_pack('!I', val
)[1:])
203 def write_flv_header(stream
):
204 """Writes the FLV header to stream"""
206 stream
.write(b
'FLV\x01')
207 stream
.write(b
'\x05')
208 stream
.write(b
'\x00\x00\x00\x09')
209 stream
.write(b
'\x00\x00\x00\x00')
212 def write_metadata_tag(stream
, metadata
):
213 """Writes optional metadata tag to stream"""
215 FLV_TAG_HEADER_LEN
= 11
218 stream
.write(SCRIPT_TAG
)
219 write_unsigned_int_24(stream
, len(metadata
))
220 stream
.write(b
'\x00\x00\x00\x00\x00\x00\x00')
221 stream
.write(metadata
)
222 write_unsigned_int(stream
, FLV_TAG_HEADER_LEN
+ len(metadata
))
226 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
229 class F4mFD(FragmentFD
):
231 A downloader for f4m manifests or AdobeHDS.
236 def _get_unencrypted_media(self
, doc
):
237 media
= doc
.findall(_add_ns('media'))
239 self
.report_error('No media found')
240 for e
in (doc
.findall(_add_ns('drmAdditionalHeader')) +
241 doc
.findall(_add_ns('drmAdditionalHeaderSet'))):
242 # If id attribute is missing it's valid for all media nodes
243 # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
244 if 'id' not in e
.attrib
:
245 self
.report_error('Missing ID in f4m DRM')
246 media
= list(filter(lambda e
: 'drmAdditionalHeaderId' not in e
.attrib
and
247 'drmAdditionalHeaderSetId' not in e
.attrib
,
250 self
.report_error('Unsupported DRM')
253 def _get_bootstrap_from_url(self
, bootstrap_url
):
254 bootstrap
= self
.ydl
.urlopen(bootstrap_url
).read()
255 return read_bootstrap_info(bootstrap
)
257 def _update_live_fragments(self
, bootstrap_url
, latest_fragment
):
260 while (not fragments_list
) and (retries
> 0):
261 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
262 fragments_list
= build_fragments_list(boot_info
)
263 fragments_list
= [f
for f
in fragments_list
if f
[1] > latest_fragment
]
264 if not fragments_list
:
265 # Retry after a while
269 if not fragments_list
:
270 self
.report_error('Failed to update fragments')
272 return fragments_list
274 def _parse_bootstrap_node(self
, node
, base_url
):
275 if node
.text
is None:
276 bootstrap_url
= compat_urlparse
.urljoin(
277 base_url
, node
.attrib
['url'])
278 boot_info
= self
._get
_bootstrap
_from
_url
(bootstrap_url
)
281 bootstrap
= base64
.b64decode(node
.text
.encode('ascii'))
282 boot_info
= read_bootstrap_info(bootstrap
)
283 return (boot_info
, bootstrap_url
)
285 def real_download(self
, filename
, info_dict
):
286 man_url
= info_dict
['url']
287 requested_bitrate
= info_dict
.get('tbr')
288 self
.to_screen('[%s] Downloading f4m manifest' % self
.FD_NAME
)
289 urlh
= self
.ydl
.urlopen(man_url
)
290 man_url
= urlh
.geturl()
291 manifest
= urlh
.read()
293 doc
= compat_etree_fromstring(manifest
)
294 formats
= [(int(f
.attrib
.get('bitrate', -1)), f
)
295 for f
in self
._get
_unencrypted
_media
(doc
)]
296 if requested_bitrate
is None:
297 # get the best format
298 formats
= sorted(formats
, key
=lambda f
: f
[0])
299 rate
, media
= formats
[-1]
301 rate
, media
= list(filter(
302 lambda f
: int(f
[0]) == requested_bitrate
, formats
))[0]
304 base_url
= compat_urlparse
.urljoin(man_url
, media
.attrib
['url'])
305 bootstrap_node
= doc
.find(_add_ns('bootstrapInfo'))
306 boot_info
, bootstrap_url
= self
._parse
_bootstrap
_node
(bootstrap_node
, base_url
)
307 live
= boot_info
['live']
308 metadata_node
= media
.find(_add_ns('metadata'))
309 if metadata_node
is not None:
310 metadata
= base64
.b64decode(metadata_node
.text
.encode('ascii'))
314 fragments_list
= build_fragments_list(boot_info
)
315 if self
.params
.get('test', False):
316 # We only download the first fragment
317 fragments_list
= fragments_list
[:1]
318 total_frags
= len(fragments_list
)
319 # For some akamai manifests we'll need to add a query to the fragment url
320 akamai_pv
= xpath_text(doc
, _add_ns('pv-2.0'))
323 'filename': filename
,
324 'total_frags': total_frags
,
327 self
._prepare
_frag
_download
(ctx
)
329 dest_stream
= ctx
['dest_stream']
331 write_flv_header(dest_stream
)
333 write_metadata_tag(dest_stream
, metadata
)
335 base_url_parsed
= compat_urllib_parse_urlparse(base_url
)
337 self
._start
_frag
_download
(ctx
)
340 while fragments_list
:
341 seg_i
, frag_i
= fragments_list
.pop(0)
342 name
= 'Seg%d-Frag%d' % (seg_i
, frag_i
)
344 if base_url_parsed
.query
:
345 query
.append(base_url_parsed
.query
)
347 query
.append(akamai_pv
.strip(';'))
348 if info_dict
.get('extra_param_to_segment_url'):
349 query
.append(info_dict
['extra_param_to_segment_url'])
350 url_parsed
= base_url_parsed
._replace
(path
=base_url_parsed
.path
+ name
, query
='&'.join(query
))
351 frag_filename
= '%s-%s' % (ctx
['tmpfilename'], name
)
353 success
= ctx
['dl'].download(frag_filename
, {'url': url_parsed
.geturl()})
356 (down
, frag_sanitized
) = sanitize_open(frag_filename
, 'rb')
357 down_data
= down
.read()
359 reader
= FlvReader(down_data
)
361 _
, box_type
, box_data
= reader
.read_box_info()
362 if box_type
== b
'mdat':
363 dest_stream
.write(box_data
)
366 os
.remove(encodeFilename(frag_sanitized
))
368 frags_filenames
.append(frag_sanitized
)
369 except (compat_urllib_error
.HTTPError
, ) as err
:
370 if live
and (err
.code
== 404 or err
.code
== 410):
371 # We didn't keep up with the live window. Continue
372 # with the next available fragment.
373 msg
= 'Fragment %d unavailable' % frag_i
374 self
.report_warning(msg
)
379 if not fragments_list
and live
and bootstrap_url
:
380 fragments_list
= self
._update
_live
_fragments
(bootstrap_url
, frag_i
)
381 total_frags
+= len(fragments_list
)
382 if fragments_list
and (fragments_list
[0][1] > frag_i
+ 1):
383 msg
= 'Missed %d fragments' % (fragments_list
[0][1] - (frag_i
+ 1))
384 self
.report_warning(msg
)
386 self
._finish
_frag
_download
(ctx
)
388 for frag_file
in frags_filenames
:
389 os
.remove(encodeFilename(frag_file
))