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