You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
12 KiB

10 years ago
11 years ago
11 years ago
11 years ago
10 years ago
  1. from __future__ import unicode_literals
  2. import base64
  3. import io
  4. import itertools
  5. import os
  6. import time
  7. import xml.etree.ElementTree as etree
  8. from .common import FileDownloader
  9. from .http import HttpFD
  10. from ..compat import (
  11. compat_urlparse,
  12. )
  13. from ..utils import (
  14. struct_pack,
  15. struct_unpack,
  16. format_bytes,
  17. encodeFilename,
  18. sanitize_open,
  19. xpath_text,
  20. )
  21. class FlvReader(io.BytesIO):
  22. """
  23. Reader for Flv files
  24. The file format is documented in https://www.adobe.com/devnet/f4v.html
  25. """
  26. # Utility functions for reading numbers and strings
  27. def read_unsigned_long_long(self):
  28. return struct_unpack('!Q', self.read(8))[0]
  29. def read_unsigned_int(self):
  30. return struct_unpack('!I', self.read(4))[0]
  31. def read_unsigned_char(self):
  32. return struct_unpack('!B', self.read(1))[0]
  33. def read_string(self):
  34. res = b''
  35. while True:
  36. char = self.read(1)
  37. if char == b'\x00':
  38. break
  39. res += char
  40. return res
  41. def read_box_info(self):
  42. """
  43. Read a box and return the info as a tuple: (box_size, box_type, box_data)
  44. """
  45. real_size = size = self.read_unsigned_int()
  46. box_type = self.read(4)
  47. header_end = 8
  48. if size == 1:
  49. real_size = self.read_unsigned_long_long()
  50. header_end = 16
  51. return real_size, box_type, self.read(real_size - header_end)
  52. def read_asrt(self):
  53. # version
  54. self.read_unsigned_char()
  55. # flags
  56. self.read(3)
  57. quality_entry_count = self.read_unsigned_char()
  58. # QualityEntryCount
  59. for i in range(quality_entry_count):
  60. self.read_string()
  61. segment_run_count = self.read_unsigned_int()
  62. segments = []
  63. for i in range(segment_run_count):
  64. first_segment = self.read_unsigned_int()
  65. fragments_per_segment = self.read_unsigned_int()
  66. segments.append((first_segment, fragments_per_segment))
  67. return {
  68. 'segment_run': segments,
  69. }
  70. def read_afrt(self):
  71. # version
  72. self.read_unsigned_char()
  73. # flags
  74. self.read(3)
  75. # time scale
  76. self.read_unsigned_int()
  77. quality_entry_count = self.read_unsigned_char()
  78. # QualitySegmentUrlModifiers
  79. for i in range(quality_entry_count):
  80. self.read_string()
  81. fragments_count = self.read_unsigned_int()
  82. fragments = []
  83. for i in range(fragments_count):
  84. first = self.read_unsigned_int()
  85. first_ts = self.read_unsigned_long_long()
  86. duration = self.read_unsigned_int()
  87. if duration == 0:
  88. discontinuity_indicator = self.read_unsigned_char()
  89. else:
  90. discontinuity_indicator = None
  91. fragments.append({
  92. 'first': first,
  93. 'ts': first_ts,
  94. 'duration': duration,
  95. 'discontinuity_indicator': discontinuity_indicator,
  96. })
  97. return {
  98. 'fragments': fragments,
  99. }
  100. def read_abst(self):
  101. # version
  102. self.read_unsigned_char()
  103. # flags
  104. self.read(3)
  105. self.read_unsigned_int() # BootstrapinfoVersion
  106. # Profile,Live,Update,Reserved
  107. self.read(1)
  108. # time scale
  109. self.read_unsigned_int()
  110. # CurrentMediaTime
  111. self.read_unsigned_long_long()
  112. # SmpteTimeCodeOffset
  113. self.read_unsigned_long_long()
  114. self.read_string() # MovieIdentifier
  115. server_count = self.read_unsigned_char()
  116. # ServerEntryTable
  117. for i in range(server_count):
  118. self.read_string()
  119. quality_count = self.read_unsigned_char()
  120. # QualityEntryTable
  121. for i in range(quality_count):
  122. self.read_string()
  123. # DrmData
  124. self.read_string()
  125. # MetaData
  126. self.read_string()
  127. segments_count = self.read_unsigned_char()
  128. segments = []
  129. for i in range(segments_count):
  130. box_size, box_type, box_data = self.read_box_info()
  131. assert box_type == b'asrt'
  132. segment = FlvReader(box_data).read_asrt()
  133. segments.append(segment)
  134. fragments_run_count = self.read_unsigned_char()
  135. fragments = []
  136. for i in range(fragments_run_count):
  137. box_size, box_type, box_data = self.read_box_info()
  138. assert box_type == b'afrt'
  139. fragments.append(FlvReader(box_data).read_afrt())
  140. return {
  141. 'segments': segments,
  142. 'fragments': fragments,
  143. }
  144. def read_bootstrap_info(self):
  145. total_size, box_type, box_data = self.read_box_info()
  146. assert box_type == b'abst'
  147. return FlvReader(box_data).read_abst()
  148. def read_bootstrap_info(bootstrap_bytes):
  149. return FlvReader(bootstrap_bytes).read_bootstrap_info()
  150. def build_fragments_list(boot_info):
  151. """ Return a list of (segment, fragment) for each fragment in the video """
  152. res = []
  153. segment_run_table = boot_info['segments'][0]
  154. fragment_run_entry_table = boot_info['fragments'][0]['fragments']
  155. first_frag_number = fragment_run_entry_table[0]['first']
  156. fragments_counter = itertools.count(first_frag_number)
  157. for segment, fragments_count in segment_run_table['segment_run']:
  158. for _ in range(fragments_count):
  159. res.append((segment, next(fragments_counter)))
  160. return res
  161. def write_unsigned_int(stream, val):
  162. stream.write(struct_pack('!I', val))
  163. def write_unsigned_int_24(stream, val):
  164. stream.write(struct_pack('!I', val)[1:])
  165. def write_flv_header(stream):
  166. """Writes the FLV header to stream"""
  167. # FLV header
  168. stream.write(b'FLV\x01')
  169. stream.write(b'\x05')
  170. stream.write(b'\x00\x00\x00\x09')
  171. stream.write(b'\x00\x00\x00\x00')
  172. def write_metadata_tag(stream, metadata):
  173. """Writes optional metadata tag to stream"""
  174. SCRIPT_TAG = b'\x12'
  175. FLV_TAG_HEADER_LEN = 11
  176. if metadata:
  177. stream.write(SCRIPT_TAG)
  178. write_unsigned_int_24(stream, len(metadata))
  179. stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
  180. stream.write(metadata)
  181. write_unsigned_int(stream, FLV_TAG_HEADER_LEN + len(metadata))
  182. def _add_ns(prop):
  183. return '{http://ns.adobe.com/f4m/1.0}%s' % prop
  184. class HttpQuietDownloader(HttpFD):
  185. def to_screen(self, *args, **kargs):
  186. pass
  187. class F4mFD(FileDownloader):
  188. """
  189. A downloader for f4m manifests or AdobeHDS.
  190. """
  191. def _get_unencrypted_media(self, doc):
  192. media = doc.findall(_add_ns('media'))
  193. if not media:
  194. self.report_error('No media found')
  195. for e in (doc.findall(_add_ns('drmAdditionalHeader')) +
  196. doc.findall(_add_ns('drmAdditionalHeaderSet'))):
  197. # If id attribute is missing it's valid for all media nodes
  198. # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
  199. if 'id' not in e.attrib:
  200. self.report_error('Missing ID in f4m DRM')
  201. media = list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
  202. 'drmAdditionalHeaderSetId' not in e.attrib,
  203. media))
  204. if not media:
  205. self.report_error('Unsupported DRM')
  206. return media
  207. def real_download(self, filename, info_dict):
  208. man_url = info_dict['url']
  209. requested_bitrate = info_dict.get('tbr')
  210. self.to_screen('[download] Downloading f4m manifest')
  211. manifest = self.ydl.urlopen(man_url).read()
  212. self.report_destination(filename)
  213. http_dl = HttpQuietDownloader(
  214. self.ydl,
  215. {
  216. 'continuedl': True,
  217. 'quiet': True,
  218. 'noprogress': True,
  219. 'ratelimit': self.params.get('ratelimit', None),
  220. 'test': self.params.get('test', False),
  221. }
  222. )
  223. doc = etree.fromstring(manifest)
  224. formats = [(int(f.attrib.get('bitrate', -1)), f)
  225. for f in self._get_unencrypted_media(doc)]
  226. if requested_bitrate is None:
  227. # get the best format
  228. formats = sorted(formats, key=lambda f: f[0])
  229. rate, media = formats[-1]
  230. else:
  231. rate, media = list(filter(
  232. lambda f: int(f[0]) == requested_bitrate, formats))[0]
  233. base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
  234. bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
  235. if bootstrap_node.text is None:
  236. bootstrap_url = compat_urlparse.urljoin(
  237. base_url, bootstrap_node.attrib['url'])
  238. bootstrap = self.ydl.urlopen(bootstrap_url).read()
  239. else:
  240. bootstrap = base64.b64decode(bootstrap_node.text)
  241. metadata_node = media.find(_add_ns('metadata'))
  242. if metadata_node is not None:
  243. metadata = base64.b64decode(metadata_node.text)
  244. else:
  245. metadata = None
  246. boot_info = read_bootstrap_info(bootstrap)
  247. fragments_list = build_fragments_list(boot_info)
  248. if self.params.get('test', False):
  249. # We only download the first fragment
  250. fragments_list = fragments_list[:1]
  251. total_frags = len(fragments_list)
  252. # For some akamai manifests we'll need to add a query to the fragment url
  253. akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
  254. tmpfilename = self.temp_name(filename)
  255. (dest_stream, tmpfilename) = sanitize_open(tmpfilename, 'wb')
  256. write_flv_header(dest_stream)
  257. write_metadata_tag(dest_stream, metadata)
  258. # This dict stores the download progress, it's updated by the progress
  259. # hook
  260. state = {
  261. 'downloaded_bytes': 0,
  262. 'frag_counter': 0,
  263. }
  264. start = time.time()
  265. def frag_progress_hook(status):
  266. frag_total_bytes = status.get('total_bytes', 0)
  267. estimated_size = (state['downloaded_bytes'] +
  268. (total_frags - state['frag_counter']) * frag_total_bytes)
  269. if status['status'] == 'finished':
  270. state['downloaded_bytes'] += frag_total_bytes
  271. state['frag_counter'] += 1
  272. progress = self.calc_percent(state['frag_counter'], total_frags)
  273. byte_counter = state['downloaded_bytes']
  274. else:
  275. frag_downloaded_bytes = status['downloaded_bytes']
  276. byte_counter = state['downloaded_bytes'] + frag_downloaded_bytes
  277. frag_progress = self.calc_percent(frag_downloaded_bytes,
  278. frag_total_bytes)
  279. progress = self.calc_percent(state['frag_counter'], total_frags)
  280. progress += frag_progress / float(total_frags)
  281. eta = self.calc_eta(start, time.time(), estimated_size, byte_counter)
  282. self.report_progress(progress, format_bytes(estimated_size),
  283. status.get('speed'), eta)
  284. http_dl.add_progress_hook(frag_progress_hook)
  285. frags_filenames = []
  286. for (seg_i, frag_i) in fragments_list:
  287. name = 'Seg%d-Frag%d' % (seg_i, frag_i)
  288. url = base_url + name
  289. if akamai_pv:
  290. url += '?' + akamai_pv.strip(';')
  291. frag_filename = '%s-%s' % (tmpfilename, name)
  292. success = http_dl.download(frag_filename, {'url': url})
  293. if not success:
  294. return False
  295. with open(frag_filename, 'rb') as down:
  296. down_data = down.read()
  297. reader = FlvReader(down_data)
  298. while True:
  299. _, box_type, box_data = reader.read_box_info()
  300. if box_type == b'mdat':
  301. dest_stream.write(box_data)
  302. break
  303. frags_filenames.append(frag_filename)
  304. dest_stream.close()
  305. self.report_finish(format_bytes(state['downloaded_bytes']), time.time() - start)
  306. self.try_rename(tmpfilename, filename)
  307. for frag_file in frags_filenames:
  308. os.remove(frag_file)
  309. fsize = os.path.getsize(encodeFilename(filename))
  310. self._hook_progress({
  311. 'downloaded_bytes': fsize,
  312. 'total_bytes': fsize,
  313. 'filename': filename,
  314. 'status': 'finished',
  315. })
  316. return True