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.

429 lines
15 KiB

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