]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/downloader/f4m.py
[discoverygo] Actualize test
[youtube-dl.git] / 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         # In some live HDS streams (for example Rai), `fragments_count` is
200         # abnormal and causing out-of-memory errors. It's OK to change the
201         # number of fragments for live streams as they are updated periodically
202         if fragments_count == 4294967295 and boot_info['live']:
203             fragments_count = 2
204         for _ in range(fragments_count):
205             res.append((segment, next(fragments_counter)))
206
207     if boot_info['live']:
208         res = res[-2:]
209
210     return res
211
212
213 def write_unsigned_int(stream, val):
214     stream.write(compat_struct_pack('!I', val))
215
216
217 def write_unsigned_int_24(stream, val):
218     stream.write(compat_struct_pack('!I', val)[1:])
219
220
221 def write_flv_header(stream):
222     """Writes the FLV header to stream"""
223     # FLV header
224     stream.write(b'FLV\x01')
225     stream.write(b'\x05')
226     stream.write(b'\x00\x00\x00\x09')
227     stream.write(b'\x00\x00\x00\x00')
228
229
230 def write_metadata_tag(stream, metadata):
231     """Writes optional metadata tag to stream"""
232     SCRIPT_TAG = b'\x12'
233     FLV_TAG_HEADER_LEN = 11
234
235     if metadata:
236         stream.write(SCRIPT_TAG)
237         write_unsigned_int_24(stream, len(metadata))
238         stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
239         stream.write(metadata)
240         write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
241
242
243 def remove_encrypted_media(media):
244     return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
245                                  'drmAdditionalHeaderSetId' not in e.attrib,
246                        media))
247
248
249 def _add_ns(prop):
250     return '{http://ns.adobe.com/f4m/1.0}%s' % prop
251
252
253 class F4mFD(FragmentFD):
254     """
255     A downloader for f4m manifests or AdobeHDS.
256     """
257
258     FD_NAME = 'f4m'
259
260     def _get_unencrypted_media(self, doc):
261         media = doc.findall(_add_ns('media'))
262         if not media:
263             self.report_error('No media found')
264         for e in (doc.findall(_add_ns('drmAdditionalHeader')) +
265                   doc.findall(_add_ns('drmAdditionalHeaderSet'))):
266             # If id attribute is missing it's valid for all media nodes
267             # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
268             if 'id' not in e.attrib:
269                 self.report_error('Missing ID in f4m DRM')
270         media = remove_encrypted_media(media)
271         if not media:
272             self.report_error('Unsupported DRM')
273         return media
274
275     def _get_bootstrap_from_url(self, bootstrap_url):
276         bootstrap = self.ydl.urlopen(bootstrap_url).read()
277         return read_bootstrap_info(bootstrap)
278
279     def _update_live_fragments(self, bootstrap_url, latest_fragment):
280         fragments_list = []
281         retries = 30
282         while (not fragments_list) and (retries > 0):
283             boot_info = self._get_bootstrap_from_url(bootstrap_url)
284             fragments_list = build_fragments_list(boot_info)
285             fragments_list = [f for f in fragments_list if f[1] > latest_fragment]
286             if not fragments_list:
287                 # Retry after a while
288                 time.sleep(5.0)
289                 retries -= 1
290
291         if not fragments_list:
292             self.report_error('Failed to update fragments')
293
294         return fragments_list
295
296     def _parse_bootstrap_node(self, node, base_url):
297         # Sometimes non empty inline bootstrap info can be specified along
298         # with bootstrap url attribute (e.g. dummy inline bootstrap info
299         # contains whitespace characters in [1]). We will prefer bootstrap
300         # url over inline bootstrap info when present.
301         # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
302         bootstrap_url = node.get('url')
303         if bootstrap_url:
304             bootstrap_url = compat_urlparse.urljoin(
305                 base_url, bootstrap_url)
306             boot_info = self._get_bootstrap_from_url(bootstrap_url)
307         else:
308             bootstrap_url = None
309             bootstrap = base64.b64decode(node.text.encode('ascii'))
310             boot_info = read_bootstrap_info(bootstrap)
311         return boot_info, bootstrap_url
312
313     def real_download(self, filename, info_dict):
314         man_url = info_dict['url']
315         requested_bitrate = info_dict.get('tbr')
316         self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)
317
318         urlh = self.ydl.urlopen(self._prepare_url(info_dict, man_url))
319         man_url = urlh.geturl()
320         # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
321         # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
322         # and https://github.com/rg3/youtube-dl/issues/7823)
323         manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
324
325         doc = compat_etree_fromstring(manifest)
326         formats = [(int(f.attrib.get('bitrate', -1)), f)
327                    for f in self._get_unencrypted_media(doc)]
328         if requested_bitrate is None or len(formats) == 1:
329             # get the best format
330             formats = sorted(formats, key=lambda f: f[0])
331             rate, media = formats[-1]
332         else:
333             rate, media = list(filter(
334                 lambda f: int(f[0]) == requested_bitrate, formats))[0]
335
336         base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
337         bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
338         # From Adobe F4M 3.0 spec:
339         # The <baseURL> element SHALL be the base URL for all relative
340         # (HTTP-based) URLs in the manifest. If <baseURL> is not present, said
341         # URLs should be relative to the location of the containing document.
342         boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, man_url)
343         live = boot_info['live']
344         metadata_node = media.find(_add_ns('metadata'))
345         if metadata_node is not None:
346             metadata = base64.b64decode(metadata_node.text.encode('ascii'))
347         else:
348             metadata = None
349
350         fragments_list = build_fragments_list(boot_info)
351         test = self.params.get('test', False)
352         if test:
353             # We only download the first fragment
354             fragments_list = fragments_list[:1]
355         total_frags = len(fragments_list)
356         # For some akamai manifests we'll need to add a query to the fragment url
357         akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
358
359         ctx = {
360             'filename': filename,
361             'total_frags': total_frags,
362             'live': live,
363         }
364
365         self._prepare_frag_download(ctx)
366
367         dest_stream = ctx['dest_stream']
368
369         write_flv_header(dest_stream)
370         if not live:
371             write_metadata_tag(dest_stream, metadata)
372
373         base_url_parsed = compat_urllib_parse_urlparse(base_url)
374
375         self._start_frag_download(ctx)
376
377         frags_filenames = []
378         while fragments_list:
379             seg_i, frag_i = fragments_list.pop(0)
380             name = 'Seg%d-Frag%d' % (seg_i, frag_i)
381             query = []
382             if base_url_parsed.query:
383                 query.append(base_url_parsed.query)
384             if akamai_pv:
385                 query.append(akamai_pv.strip(';'))
386             if info_dict.get('extra_param_to_segment_url'):
387                 query.append(info_dict['extra_param_to_segment_url'])
388             url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))
389             frag_filename = '%s-%s' % (ctx['tmpfilename'], name)
390             try:
391                 success = ctx['dl'].download(frag_filename, {
392                     'url': url_parsed.geturl(),
393                     'http_headers': info_dict.get('http_headers'),
394                 })
395                 if not success:
396                     return False
397                 (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
398                 down_data = down.read()
399                 down.close()
400                 reader = FlvReader(down_data)
401                 while True:
402                     try:
403                         _, box_type, box_data = reader.read_box_info()
404                     except DataTruncatedError:
405                         if test:
406                             # In tests, segments may be truncated, and thus
407                             # FlvReader may not be able to parse the whole
408                             # chunk. If so, write the segment as is
409                             # See https://github.com/rg3/youtube-dl/issues/9214
410                             dest_stream.write(down_data)
411                             break
412                         raise
413                     if box_type == b'mdat':
414                         dest_stream.write(box_data)
415                         break
416                 if live:
417                     os.remove(encodeFilename(frag_sanitized))
418                 else:
419                     frags_filenames.append(frag_sanitized)
420             except (compat_urllib_error.HTTPError, ) as err:
421                 if live and (err.code == 404 or err.code == 410):
422                     # We didn't keep up with the live window. Continue
423                     # with the next available fragment.
424                     msg = 'Fragment %d unavailable' % frag_i
425                     self.report_warning(msg)
426                     fragments_list = []
427                 else:
428                     raise
429
430             if not fragments_list and not test and live and bootstrap_url:
431                 fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
432                 total_frags += len(fragments_list)
433                 if fragments_list and (fragments_list[0][1] > frag_i + 1):
434                     msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
435                     self.report_warning(msg)
436
437         self._finish_frag_download(ctx)
438
439         for frag_file in frags_filenames:
440             os.remove(encodeFilename(frag_file))
441
442         return True