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.

407 lines
14 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. 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 remove_encrypted_media(media):
  188. return list(filter(lambda e: 'drmAdditionalHeaderId' not in e.attrib and
  189. 'drmAdditionalHeaderSetId' not in e.attrib,
  190. media))
  191. def _add_ns(prop):
  192. return '{http://ns.adobe.com/f4m/1.0}%s' % prop
  193. class F4mFD(FragmentFD):
  194. """
  195. A downloader for f4m manifests or AdobeHDS.
  196. """
  197. FD_NAME = 'f4m'
  198. def _get_unencrypted_media(self, doc):
  199. media = doc.findall(_add_ns('media'))
  200. if not media:
  201. self.report_error('No media found')
  202. for e in (doc.findall(_add_ns('drmAdditionalHeader')) +
  203. doc.findall(_add_ns('drmAdditionalHeaderSet'))):
  204. # If id attribute is missing it's valid for all media nodes
  205. # without drmAdditionalHeaderId or drmAdditionalHeaderSetId attribute
  206. if 'id' not in e.attrib:
  207. self.report_error('Missing ID in f4m DRM')
  208. media = remove_encrypted_media(media)
  209. if not media:
  210. self.report_error('Unsupported DRM')
  211. return media
  212. def _get_bootstrap_from_url(self, bootstrap_url):
  213. bootstrap = self.ydl.urlopen(bootstrap_url).read()
  214. return read_bootstrap_info(bootstrap)
  215. def _update_live_fragments(self, bootstrap_url, latest_fragment):
  216. fragments_list = []
  217. retries = 30
  218. while (not fragments_list) and (retries > 0):
  219. boot_info = self._get_bootstrap_from_url(bootstrap_url)
  220. fragments_list = build_fragments_list(boot_info)
  221. fragments_list = [f for f in fragments_list if f[1] > latest_fragment]
  222. if not fragments_list:
  223. # Retry after a while
  224. time.sleep(5.0)
  225. retries -= 1
  226. if not fragments_list:
  227. self.report_error('Failed to update fragments')
  228. return fragments_list
  229. def _parse_bootstrap_node(self, node, base_url):
  230. # Sometimes non empty inline bootstrap info can be specified along
  231. # with bootstrap url attribute (e.g. dummy inline bootstrap info
  232. # contains whitespace characters in [1]). We will prefer bootstrap
  233. # url over inline bootstrap info when present.
  234. # 1. http://live-1-1.rutube.ru/stream/1024/HDS/SD/C2NKsS85HQNckgn5HdEmOQ/1454167650/S-s604419906/move/four/dirs/upper/1024-576p.f4m
  235. bootstrap_url = node.get('url')
  236. if bootstrap_url:
  237. bootstrap_url = compat_urlparse.urljoin(
  238. base_url, bootstrap_url)
  239. boot_info = self._get_bootstrap_from_url(bootstrap_url)
  240. else:
  241. bootstrap_url = None
  242. bootstrap = base64.b64decode(node.text.encode('ascii'))
  243. boot_info = read_bootstrap_info(bootstrap)
  244. return boot_info, bootstrap_url
  245. def real_download(self, filename, info_dict):
  246. man_url = info_dict['url']
  247. requested_bitrate = info_dict.get('tbr')
  248. self.to_screen('[%s] Downloading f4m manifest' % self.FD_NAME)
  249. urlh = self.ydl.urlopen(man_url)
  250. man_url = urlh.geturl()
  251. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  252. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244
  253. # and https://github.com/rg3/youtube-dl/issues/7823)
  254. manifest = fix_xml_ampersands(urlh.read().decode('utf-8', 'ignore')).strip()
  255. doc = compat_etree_fromstring(manifest)
  256. formats = [(int(f.attrib.get('bitrate', -1)), f)
  257. for f in self._get_unencrypted_media(doc)]
  258. if requested_bitrate is None:
  259. # get the best format
  260. formats = sorted(formats, key=lambda f: f[0])
  261. rate, media = formats[-1]
  262. else:
  263. rate, media = list(filter(
  264. lambda f: int(f[0]) == requested_bitrate, formats))[0]
  265. base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
  266. bootstrap_node = doc.find(_add_ns('bootstrapInfo'))
  267. boot_info, bootstrap_url = self._parse_bootstrap_node(bootstrap_node, base_url)
  268. live = boot_info['live']
  269. metadata_node = media.find(_add_ns('metadata'))
  270. if metadata_node is not None:
  271. metadata = base64.b64decode(metadata_node.text.encode('ascii'))
  272. else:
  273. metadata = None
  274. fragments_list = build_fragments_list(boot_info)
  275. test = self.params.get('test', False)
  276. if test:
  277. # We only download the first fragment
  278. fragments_list = fragments_list[:1]
  279. total_frags = len(fragments_list)
  280. # For some akamai manifests we'll need to add a query to the fragment url
  281. akamai_pv = xpath_text(doc, _add_ns('pv-2.0'))
  282. ctx = {
  283. 'filename': filename,
  284. 'total_frags': total_frags,
  285. 'live': live,
  286. }
  287. self._prepare_frag_download(ctx)
  288. dest_stream = ctx['dest_stream']
  289. write_flv_header(dest_stream)
  290. if not live:
  291. write_metadata_tag(dest_stream, metadata)
  292. base_url_parsed = compat_urllib_parse_urlparse(base_url)
  293. self._start_frag_download(ctx)
  294. frags_filenames = []
  295. while fragments_list:
  296. seg_i, frag_i = fragments_list.pop(0)
  297. name = 'Seg%d-Frag%d' % (seg_i, frag_i)
  298. query = []
  299. if base_url_parsed.query:
  300. query.append(base_url_parsed.query)
  301. if akamai_pv:
  302. query.append(akamai_pv.strip(';'))
  303. if info_dict.get('extra_param_to_segment_url'):
  304. query.append(info_dict['extra_param_to_segment_url'])
  305. url_parsed = base_url_parsed._replace(path=base_url_parsed.path + name, query='&'.join(query))
  306. frag_filename = '%s-%s' % (ctx['tmpfilename'], name)
  307. try:
  308. success = ctx['dl'].download(frag_filename, {'url': url_parsed.geturl()})
  309. if not success:
  310. return False
  311. (down, frag_sanitized) = sanitize_open(frag_filename, 'rb')
  312. down_data = down.read()
  313. down.close()
  314. reader = FlvReader(down_data)
  315. while True:
  316. _, box_type, box_data = reader.read_box_info()
  317. if box_type == b'mdat':
  318. dest_stream.write(box_data)
  319. break
  320. if live:
  321. os.remove(encodeFilename(frag_sanitized))
  322. else:
  323. frags_filenames.append(frag_sanitized)
  324. except (compat_urllib_error.HTTPError, ) as err:
  325. if live and (err.code == 404 or err.code == 410):
  326. # We didn't keep up with the live window. Continue
  327. # with the next available fragment.
  328. msg = 'Fragment %d unavailable' % frag_i
  329. self.report_warning(msg)
  330. fragments_list = []
  331. else:
  332. raise
  333. if not fragments_list and not test and live and bootstrap_url:
  334. fragments_list = self._update_live_fragments(bootstrap_url, frag_i)
  335. total_frags += len(fragments_list)
  336. if fragments_list and (fragments_list[0][1] > frag_i + 1):
  337. msg = 'Missed %d fragments' % (fragments_list[0][1] - (frag_i + 1))
  338. self.report_warning(msg)
  339. self._finish_frag_download(ctx)
  340. for frag_file in frags_filenames:
  341. os.remove(encodeFilename(frag_file))
  342. return True