744bf91cb58b387120d1653a468ecb96d42a7279
[ytdl] / youtube_dl / downloader / f4m.py
1 from __future__ import unicode_literals
2
3 import base64
4 import io
5 import itertools
6 import os
7 import time
8 import xml.etree.ElementTree as etree
9
10 from .common import FileDownloader
11 from .http import HttpFD
12 from ..compat import (
13     compat_urlparse,
14 )
15 from ..utils import (
16     struct_pack,
17     struct_unpack,
18     format_bytes,
19     encodeFilename,
20     sanitize_open,
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         self.read(1)
126         # time scale
127         self.read_unsigned_int()
128         # CurrentMediaTime
129         self.read_unsigned_long_long()
130         # SmpteTimeCodeOffset
131         self.read_unsigned_long_long()
132
133         self.read_string()  # MovieIdentifier
134         server_count = self.read_unsigned_char()
135         # ServerEntryTable
136         for i in range(server_count):
137             self.read_string()
138         quality_count = self.read_unsigned_char()
139         # QualityEntryTable
140         for i in range(quality_count):
141             self.read_string()
142         # DrmData
143         self.read_string()
144         # MetaData
145         self.read_string()
146
147         segments_count = self.read_unsigned_char()
148         segments = []
149         for i in range(segments_count):
150             box_size, box_type, box_data = self.read_box_info()
151             assert box_type == b'asrt'
152             segment = FlvReader(box_data).read_asrt()
153             segments.append(segment)
154         fragments_run_count = self.read_unsigned_char()
155         fragments = []
156         for i in range(fragments_run_count):
157             box_size, box_type, box_data = self.read_box_info()
158             assert box_type == b'afrt'
159             fragments.append(FlvReader(box_data).read_afrt())
160
161         return {
162             'segments': segments,
163             'fragments': fragments,
164         }
165
166     def read_bootstrap_info(self):
167         total_size, box_type, box_data = self.read_box_info()
168         assert box_type == b'abst'
169         return FlvReader(box_data).read_abst()
170
171
172 def read_bootstrap_info(bootstrap_bytes):
173     return FlvReader(bootstrap_bytes).read_bootstrap_info()
174
175
176 def build_fragments_list(boot_info):
177     """ Return a list of (segment, fragment) for each fragment in the video """
178     res = []
179     segment_run_table = boot_info['segments'][0]
180     # I've only found videos with one segment
181     segment_run_entry = segment_run_table['segment_run'][0]
182     n_frags = segment_run_entry[1]
183     fragment_run_entry_table = boot_info['fragments'][0]['fragments']
184     first_frag_number = fragment_run_entry_table[0]['first']
185     for (i, frag_number) in zip(range(1, n_frags + 1), itertools.count(first_frag_number)):
186         res.append((1, frag_number))
187     return res
188
189
190 def write_unsigned_int(stream, val):
191     stream.write(struct_pack('!I', val))
192
193
194 def write_flv_header(stream):
195     """Writes the FLV header to stream"""
196     # FLV header
197     stream.write(b'FLV\x01')
198     stream.write(b'\x05')
199     stream.write(b'\x00\x00\x00\x09')
200     stream.write(b'\x00\x00\x00\x00')
201
202
203 def write_metadata_tag(stream, metadata):
204     """Writes optional metadata tag to stream"""
205     FLV_TAG_HEADER_LEN = 11
206
207     if metadata:
208         # Script data
209         stream.write(b'\x12')
210         # Size of the metadata with 3 bytes
211         stream.write(struct_pack('!L', len(metadata))[1:])
212         stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
213         stream.write(metadata)
214         write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
215
216
217 def _add_ns(prop):
218     return '{http://ns.adobe.com/f4m/1.0}%s' % prop
219
220
221 class HttpQuietDownloader(HttpFD):
222     def to_screen(self, *args, **kargs):
223         pass
224
225
226 class F4mFD(FileDownloader):
227     """
228     A downloader for f4m manifests or AdobeHDS.
229     """
230
231     def real_download(self, filename, info_dict):
232         man_url = info_dict['url']
233         requested_bitrate = info_dict.get('tbr')
234         self.to_screen('[download] Downloading f4m manifest')
235         manifest = self.ydl.urlopen(man_url).read()
236         self.report_destination(filename)
237         http_dl = HttpQuietDownloader(
238             self.ydl,
239             {
240                 'continuedl': True,
241                 'quiet': True,
242                 'noprogress': True,
243                 'ratelimit': self.params.get('ratelimit', None),
244                 'test': self.params.get('test', False),
245             }
246         )
247
248         doc = etree.fromstring(manifest)
249         formats = [(int(f.attrib.get('bitrate', -1)), f) for f in doc.findall(_add_ns('media'))]
250         if requested_bitrate is None:
251             # get the best format
252             formats = sorted(formats, key=lambda f: f[0])
253             rate, media = formats[-1]
254         else:
255             rate, media = list(filter(
256                 lambda f: int(f[0]) == requested_bitrate, formats))[0]
257
258         base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
259         bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
260         if bootstrap_node.text is None:
261             bootstrap_url = compat_urlparse.urljoin(
262                 base_url, bootstrap_node.attrib['url'])
263             bootstrap = self.ydl.urlopen(bootstrap_url).read()
264         else:
265             bootstrap = base64.b64decode(bootstrap_node.text)
266         metadata_node = media.find(_add_ns('metadata'))
267         if metadata_node is not None:
268             metadata = base64.b64decode(metadata_node.text)
269         else:
270             metadata = None
271         boot_info = read_bootstrap_info(bootstrap)
272
273         fragments_list = build_fragments_list(boot_info)
274         if self.params.get('test', False):
275             # We only download the first fragment
276             fragments_list = fragments_list[:1]
277         total_frags = len(fragments_list)
278         # For some akamai manifests we'll need to add a query to the fragment url
279         akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
280
281         tmpfilename = self.temp_name(filename)
282         (dest_stream, tmpfilename) = sanitize_open(tmpfilename, 'wb')
283         write_flv_header(dest_stream)
284         write_metadata_tag(dest_stream, metadata)
285
286         # This dict stores the download progress, it's updated by the progress
287         # hook
288         state = {
289             'downloaded_bytes': 0,
290             'frag_counter': 0,
291         }
292         start = time.time()
293
294         def frag_progress_hook(status):
295             frag_total_bytes = status.get('total_bytes', 0)
296             estimated_size = (state['downloaded_bytes'] +
297                               (total_frags - state['frag_counter']) * frag_total_bytes)
298             if status['status'] == 'finished':
299                 state['downloaded_bytes'] += frag_total_bytes
300                 state['frag_counter'] += 1
301                 progress = self.calc_percent(state['frag_counter'], total_frags)
302                 byte_counter = state['downloaded_bytes']
303             else:
304                 frag_downloaded_bytes = status['downloaded_bytes']
305                 byte_counter = state['downloaded_bytes'] + frag_downloaded_bytes
306                 frag_progress = self.calc_percent(frag_downloaded_bytes,
307                                                   frag_total_bytes)
308                 progress = self.calc_percent(state['frag_counter'], total_frags)
309                 progress += frag_progress / float(total_frags)
310
311             eta = self.calc_eta(start, time.time(), estimated_size, byte_counter)
312             self.report_progress(progress, format_bytes(estimated_size),
313                                  status.get('speed'), eta)
314         http_dl.add_progress_hook(frag_progress_hook)
315
316         frags_filenames = []
317         for (seg_i, frag_i) in fragments_list:
318             name = 'Seg%d-Frag%d' % (seg_i, frag_i)
319             url = base_url + name
320             if akamai_pv:
321                 url += '?' + akamai_pv.strip(';')
322             frag_filename = '%s-%s' % (tmpfilename, name)
323             success = http_dl.download(frag_filename, {'url': url})
324             if not success:
325                 return False
326             with open(frag_filename, 'rb') as down:
327                 down_data = down.read()
328                 reader = FlvReader(down_data)
329                 while True:
330                     _, box_type, box_data = reader.read_box_info()
331                     if box_type == b'mdat':
332                         dest_stream.write(box_data)
333                         break
334             frags_filenames.append(frag_filename)
335
336         dest_stream.close()
337         self.report_finish(format_bytes(state['downloaded_bytes']), time.time() - start)
338
339         self.try_rename(tmpfilename, filename)
340         for frag_file in frags_filenames:
341             os.remove(frag_file)
342
343         fsize = os.path.getsize(encodeFilename(filename))
344         self._hook_progress({
345             'downloaded_bytes': fsize,
346             'total_bytes': fsize,
347             'filename': filename,
348             'status': 'finished',
349         })
350
351         return True