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