]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/f4m.py
fc9642905f3fffb5f1ec11f959c36fd486b757f2
[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 )
16 from ..utils import (
17 encodeFilename,
18 fix_xml_ampersands,
19 sanitize_open,
20 struct_pack,
21 struct_unpack,
22 xpath_text,
23 )
24
25
26 class FlvReader(io.BytesIO):
27 """
28 Reader for Flv files
29 The file format is documented in https://www.adobe.com/devnet/f4v.html
30 """
31
32 # Utility functions for reading numbers and strings
33 def read_unsigned_long_long(self):
34 return struct_unpack('!Q', self.read(8))[0]
35
36 def read_unsigned_int(self):
37 return struct_unpack('!I', self.read(4))[0]
38
39 def read_unsigned_char(self):
40 return struct_unpack('!B', self.read(1))[0]
41
42 def read_string(self):
43 res = b''
44 while True:
45 char = self.read(1)
46 if char == b'\x00':
47 break
48 res += char
49 return res
50
51 def read_box_info(self):
52 """
53 Read a box and return the info as a tuple: (box_size, box_type, box_data)
54 """
55 real_size = size = self.read_unsigned_int()
56 box_type = self.read(4)
57 header_end = 8
58 if size == 1:
59 real_size = self.read_unsigned_long_long()
60 header_end = 16
61 return real_size, box_type, self.read(real_size - header_end)
62
63 def read_asrt(self):
64 # version
65 self.read_unsigned_char()
66 # flags
67 self.read(3)
68 quality_entry_count = self.read_unsigned_char()
69 # QualityEntryCount
70 for i in range(quality_entry_count):
71 self.read_string()
72
73 segment_run_count = self.read_unsigned_int()
74 segments = []
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))
79
80 return {
81 'segment_run': segments,
82 }
83
84 def read_afrt(self):
85 # version
86 self.read_unsigned_char()
87 # flags
88 self.read(3)
89 # time scale
90 self.read_unsigned_int()
91
92 quality_entry_count = self.read_unsigned_char()
93 # QualitySegmentUrlModifiers
94 for i in range(quality_entry_count):
95 self.read_string()
96
97 fragments_count = self.read_unsigned_int()
98 fragments = []
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()
103 if duration == 0:
104 discontinuity_indicator = self.read_unsigned_char()
105 else:
106 discontinuity_indicator = None
107 fragments.append({
108 'first': first,
109 'ts': first_ts,
110 'duration': duration,
111 'discontinuity_indicator': discontinuity_indicator,
112 })
113
114 return {
115 'fragments': fragments,
116 }
117
118 def read_abst(self):
119 # version
120 self.read_unsigned_char()
121 # flags
122 self.read(3)
123
124 self.read_unsigned_int() # BootstrapinfoVersion
125 # Profile,Live,Update,Reserved
126 flags = self.read_unsigned_char()
127 live = flags & 0x20 != 0
128 # time scale
129 self.read_unsigned_int()
130 # CurrentMediaTime
131 self.read_unsigned_long_long()
132 # SmpteTimeCodeOffset
133 self.read_unsigned_long_long()
134
135 self.read_string() # MovieIdentifier
136 server_count = self.read_unsigned_char()
137 # ServerEntryTable
138 for i in range(server_count):
139 self.read_string()
140 quality_count = self.read_unsigned_char()
141 # QualityEntryTable
142 for i in range(quality_count):
143 self.read_string()
144 # DrmData
145 self.read_string()
146 # MetaData
147 self.read_string()
148
149 segments_count = self.read_unsigned_char()
150 segments = []
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()
157 fragments = []
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())
162
163 return {
164 'segments': segments,
165 'fragments': fragments,
166 'live': live,
167 }
168
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()
173
174
175 def read_bootstrap_info(bootstrap_bytes):
176 return FlvReader(bootstrap_bytes).read_bootstrap_info()
177
178
179 def build_fragments_list(boot_info):
180 """ Return a list of (segment, fragment) for each fragment in the video """
181 res = []
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)))
189
190 if boot_info['live']:
191 res = res[-2:]
192
193 return res
194
195
196 def write_unsigned_int(stream, val):
197 stream.write(struct_pack('!I', val))
198
199
200 def write_unsigned_int_24(stream, val):
201 stream.write(struct_pack('!I', val)[1:])
202
203
204 def write_flv_header(stream):
205 """Writes the FLV header to stream"""
206 # FLV header
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')
211
212
213 def write_metadata_tag(stream, metadata):
214 """Writes optional metadata tag to stream"""
215 SCRIPT_TAG = b'\x12'
216 FLV_TAG_HEADER_LEN = 11
217
218 if metadata:
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))
224
225
226 def _add_ns(prop):
227 return '{http://ns.adobe.com/f4m/1.0}%s' % prop
228
229
230 class F4mFD(FragmentFD):
231 """
232 A downloader for f4m manifests or AdobeHDS.
233 """
234
235 FD_NAME = 'f4m'
236
237 def _get_unencrypted_media(self, doc):
238 media = doc.findall(_add_ns('media'))
239 if not 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,
249 media))
250 if not media:
251 self.report_error('Unsupported DRM')
252 return media
253
254 def _get_bootstrap_from_url(self, bootstrap_url):
255 bootstrap = self.ydl.urlopen(bootstrap_url).read()
256 return read_bootstrap_info(bootstrap)
257
258 def _update_live_fragments(self, bootstrap_url, latest_fragment):
259 fragments_list = []
260 retries = 30
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
267 time.sleep(5.0)
268 retries -= 1
269
270 if not fragments_list:
271 self.report_error('Failed to update fragments')
272
273 return fragments_list
274
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')
282 if bootstrap_url:
283 bootstrap_url = compat_urlparse.urljoin(
284 base_url, bootstrap_url)
285 boot_info = self._get_bootstrap_from_url(bootstrap_url)
286 else:
287 bootstrap_url = None
288 bootstrap = base64.b64decode(node.text.encode('ascii'))
289 boot_info = read_bootstrap_info(bootstrap)
290 return boot_info, bootstrap_url
291
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()
302
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]
310 else:
311 rate, media = list(filter(
312 lambda f: int(f[0]) == requested_bitrate, formats))[0]
313
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'))
321 else:
322 metadata = None
323
324 fragments_list = build_fragments_list(boot_info)
325 test = self.params.get('test', False)
326 if test:
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'))
332
333 ctx = {
334 'filename': filename,
335 'total_frags': total_frags,
336 'live': live,
337 }
338
339 self._prepare_frag_download(ctx)
340
341 dest_stream = ctx['dest_stream']
342
343 write_flv_header(dest_stream)
344 if not live:
345 write_metadata_tag(dest_stream, metadata)
346
347 base_url_parsed = compat_urllib_parse_urlparse(base_url)
348
349 self._start_frag_download(ctx)
350
351 frags_filenames = []
352 while fragments_list:
353 seg_i, frag_i = fragments_list.pop(0)
354 name = 'Seg%d-Frag%d' % (seg_i, frag_i)
355 query = []
356 if base_url_parsed.query:
357 query.append(base_url_parsed.query)
358 if akamai_pv:
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)
364 try:
365 success = ctx['dl'].download(frag_filename, {'url': url_parsed.geturl()})
366 if not success:
367 return False
368 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
369 down_data = down.read()
370 down.close()
371 reader = FlvReader(down_data)
372 while True:
373 _, box_type, box_data = reader.read_box_info()
374 if box_type == b'mdat':
375 dest_stream.write(box_data)
376 break
377 if live:
378 os.remove(encodeFilename(frag_sanitized))
379 else:
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)
387 fragments_list = []
388 else:
389 raise
390
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)
397
398 self._finish_frag_download(ctx)
399
400 for frag_file in frags_filenames:
401 os.remove(encodeFilename(frag_file))
402
403 return True