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.

438 lines
15 KiB

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