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.

380 lines
12 KiB

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