]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/f4m.py
Update the changelog.
[youtubedl] / youtube_dl / downloader / f4m.py
1 from __future__ import division, unicode_literals
2
3 import base64
4 import io
5 import itertools
6 import os
7 import time
8
9 from .fragment import FragmentFD
10 from ..compat import (
11 compat_etree_fromstring,
12 compat_urlparse,
13 compat_urllib_error,
14 compat_urllib_parse_urlparse,
15 compat_struct_pack,
16 compat_struct_unpack,
17 )
18 from ..utils import (
19 encodeFilename,
20 fix_xml_ampersands,
21 sanitize_open,
22 xpath_text,
23 )
24
25
26 class DataTruncatedError(Exception):
27 pass
28
29
30 class FlvReader(io.BytesIO):
31 """
32 Reader for Flv files
33 The file format is documented in https://www.adobe.com/devnet/f4v.html
34 """
35
36 def read_bytes(self, n):
37 data = self.read(n)
38 if len(data) < n:
39 raise DataTruncatedError(
40 'FlvReader error: need %d bytes while only %d bytes got' % (
41 n, len(data)))
42 return data
43
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]
47
48 def read_unsigned_int(self):
49 return compat_struct_unpack('!I', self.read_bytes(4))[0]
50
51 def read_unsigned_char(self):
52 return compat_struct_unpack('!B', self.read_bytes(1))[0]
53
54 def read_string(self):
55 res = b''
56 while True:
57 char = self.read_bytes(1)
58 if char == b'\x00':
59 break
60 res += char
61 return res
62
63 def read_box_info(self):
64 """
65 Read a box and return the info as a tuple: (box_size, box_type, box_data)
66 """
67 real_size = size = self.read_unsigned_int()
68 box_type = self.read_bytes(4)
69 header_end = 8
70 if size == 1:
71 real_size = self.read_unsigned_long_long()
72 header_end = 16
73 return real_size, box_type, self.read_bytes(real_size - header_end)
74
75 def read_asrt(self):
76 # version
77 self.read_unsigned_char()
78 # flags
79 self.read_bytes(3)
80 quality_entry_count = self.read_unsigned_char()
81 # QualityEntryCount
82 for i in range(quality_entry_count):
83 self.read_string()
84
85 segment_run_count = self.read_unsigned_int()
86 segments = []
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))
91
92 return {
93 'segment_run': segments,
94 }
95
96 def read_afrt(self):
97 # version
98 self.read_unsigned_char()
99 # flags
100 self.read_bytes(3)
101 # time scale
102 self.read_unsigned_int()
103
104 quality_entry_count = self.read_unsigned_char()
105 # QualitySegmentUrlModifiers
106 for i in range(quality_entry_count):
107 self.read_string()
108
109 fragments_count = self.read_unsigned_int()
110 fragments = []
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()
115 if duration == 0:
116 discontinuity_indicator = self.read_unsigned_char()
117 else:
118 discontinuity_indicator = None
119 fragments.append({
120 'first': first,
121 'ts': first_ts,
122 'duration': duration,
123 'discontinuity_indicator': discontinuity_indicator,
124 })
125
126 return {
127 'fragments': fragments,
128 }
129
130 def read_abst(self):
131 # version
132 self.read_unsigned_char()
133 # flags
134 self.read_bytes(3)
135
136 self.read_unsigned_int() # BootstrapinfoVersion
137 # Profile,Live,Update,Reserved
138 flags = self.read_unsigned_char()
139 live = flags & 0x20 != 0
140 # time scale
141 self.read_unsigned_int()
142 # CurrentMediaTime
143 self.read_unsigned_long_long()
144 # SmpteTimeCodeOffset
145 self.read_unsigned_long_long()
146
147 self.read_string() # MovieIdentifier
148 server_count = self.read_unsigned_char()
149 # ServerEntryTable
150 for i in range(server_count):
151 self.read_string()
152 quality_count = self.read_unsigned_char()
153 # QualityEntryTable
154 for i in range(quality_count):
155 self.read_string()
156 # DrmData
157 self.read_string()
158 # MetaData
159 self.read_string()
160
161 segments_count = self.read_unsigned_char()
162 segments = []
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()
169 fragments = []
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())
174
175 return {
176 'segments': segments,
177 'fragments': fragments,
178 'live': live,
179 }
180
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()
185
186
187 def read_bootstrap_info(bootstrap_bytes):
188 return FlvReader(bootstrap_bytes).read_bootstrap_info()
189
190
191 def build_fragments_list(boot_info):
192 """ Return a list of (segment, fragment) for each fragment in the video """
193 res = []
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)))
201
202 if boot_info['live']:
203 res = res[-2:]
204
205 return res
206
207
208 def write_unsigned_int(stream, val):
209 stream.write(compat_struct_pack('!I', val))
210
211
212 def write_unsigned_int_24(stream, val):
213 stream.write(compat_struct_pack('!I', val)[1:])
214
215
216 def write_flv_header(stream):
217 """Writes the FLV header to stream"""
218 # FLV header
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')
223
224
225 def write_metadata_tag(stream, metadata):
226 """Writes optional metadata tag to stream"""
227 SCRIPT_TAG = b'\x12'
228 FLV_TAG_HEADER_LEN = 11
229
230 if metadata:
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))
236
237
238 def remove_encrypted_media(media):
239 return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
240 'drmAdditionalHeaderSetId' not in e.attrib,
241 media))
242
243
244 def _add_ns(prop):
245 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
246
247
248 class F4mFD(FragmentFD):
249 """
250 A downloader for f4m manifests or AdobeHDS.
251 """
252
253 FD_NAME = 'f4m'
254
255 def _get_unencrypted_media(self, doc):
256 media = doc.findall(_add_ns('media'))
257 if not 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)
266 if not media:
267 self.report_error('Unsupported DRM')
268 return media
269
270 def _get_bootstrap_from_url(self, bootstrap_url):
271 bootstrap = self.ydl.urlopen(bootstrap_url).read()
272 return read_bootstrap_info(bootstrap)
273
274 def _update_live_fragments(self, bootstrap_url, latest_fragment):
275 fragments_list = []
276 retries = 30
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
283 time.sleep(5.0)
284 retries -= 1
285
286 if not fragments_list:
287 self.report_error('Failed to update fragments')
288
289 return fragments_list
290
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')
298 if bootstrap_url:
299 bootstrap_url = compat_urlparse.urljoin(
300 base_url, bootstrap_url)
301 boot_info = self._get_bootstrap_from_url(bootstrap_url)
302 else:
303 bootstrap_url = None
304 bootstrap = base64.b64decode(node.text.encode('ascii'))
305 boot_info = read_bootstrap_info(bootstrap)
306 return boot_info, bootstrap_url
307
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()
318
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]
326 else:
327 rate, media = list(filter(
328 lambda f: int(f[0]) == requested_bitrate, formats))[0]
329
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'))
337 else:
338 metadata = None
339
340 fragments_list = build_fragments_list(boot_info)
341 test = self.params.get('test', False)
342 if test:
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'))
348
349 ctx = {
350 'filename': filename,
351 'total_frags': total_frags,
352 'live': live,
353 }
354
355 self._prepare_frag_download(ctx)
356
357 dest_stream = ctx['dest_stream']
358
359 write_flv_header(dest_stream)
360 if not live:
361 write_metadata_tag(dest_stream, metadata)
362
363 base_url_parsed = compat_urllib_parse_urlparse(base_url)
364
365 self._start_frag_download(ctx)
366
367 frags_filenames = []
368 while fragments_list:
369 seg_i, frag_i = fragments_list.pop(0)
370 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
371 query = []
372 if base_url_parsed.query:
373 query.append(base_url_parsed.query)
374 if akamai_pv:
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)
380 try:
381 success = ctx['dl'].download(frag_filename, {'url': url_parsed.geturl()})
382 if not success:
383 return False
384 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
385 down_data = down.read()
386 down.close()
387 reader = FlvReader(down_data)
388 while True:
389 try:
390 _, box_type, box_data = reader.read_box_info()
391 except DataTruncatedError:
392 if test:
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)
398 break
399 raise
400 if box_type == b'mdat':
401 dest_stream.write(box_data)
402 break
403 if live:
404 os.remove(encodeFilename(frag_sanitized))
405 else:
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)
413 fragments_list = []
414 else:
415 raise
416
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)
423
424 self._finish_frag_download(ctx)
425
426 for frag_file in frags_filenames:
427 os.remove(encodeFilename(frag_file))
428
429 return True