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.

403 lines
14 KiB

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