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.

442 lines
15 KiB

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