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.

315 lines
10 KiB

  1. from __future__ import unicode_literals
  2. import base64
  3. import io
  4. import itertools
  5. import os
  6. import time
  7. import xml.etree.ElementTree as etree
  8. from .common import FileDownloader
  9. from .http import HttpFD
  10. from ..utils import (
  11. struct_pack,
  12. struct_unpack,
  13. compat_urllib_request,
  14. compat_urlparse,
  15. format_bytes,
  16. encodeFilename,
  17. sanitize_open,
  18. )
  19. class FlvReader(io.BytesIO):
  20. """
  21. Reader for Flv files
  22. The file format is documented in https://www.adobe.com/devnet/f4v.html
  23. """
  24. # Utility functions for reading numbers and strings
  25. def read_unsigned_long_long(self):
  26. return struct_unpack('!Q', self.read(8))[0]
  27. def read_unsigned_int(self):
  28. return struct_unpack('!I', self.read(4))[0]
  29. def read_unsigned_char(self):
  30. return struct_unpack('!B', self.read(1))[0]
  31. def read_string(self):
  32. res = b''
  33. while True:
  34. char = self.read(1)
  35. if char == b'\x00':
  36. break
  37. res += char
  38. return res
  39. def read_box_info(self):
  40. """
  41. Read a box and return the info as a tuple: (box_size, box_type, box_data)
  42. """
  43. real_size = size = self.read_unsigned_int()
  44. box_type = self.read(4)
  45. header_end = 8
  46. if size == 1:
  47. real_size = self.read_unsigned_long_long()
  48. header_end = 16
  49. return real_size, box_type, self.read(real_size-header_end)
  50. def read_asrt(self):
  51. # version
  52. self.read_unsigned_char()
  53. # flags
  54. self.read(3)
  55. quality_entry_count = self.read_unsigned_char()
  56. # QualityEntryCount
  57. for i in range(quality_entry_count):
  58. self.read_string()
  59. segment_run_count = self.read_unsigned_int()
  60. segments = []
  61. for i in range(segment_run_count):
  62. first_segment = self.read_unsigned_int()
  63. fragments_per_segment = self.read_unsigned_int()
  64. segments.append((first_segment, fragments_per_segment))
  65. return {
  66. 'segment_run': segments,
  67. }
  68. def read_afrt(self):
  69. # version
  70. self.read_unsigned_char()
  71. # flags
  72. self.read(3)
  73. # time scale
  74. self.read_unsigned_int()
  75. quality_entry_count = self.read_unsigned_char()
  76. # QualitySegmentUrlModifiers
  77. for i in range(quality_entry_count):
  78. self.read_string()
  79. fragments_count = self.read_unsigned_int()
  80. fragments = []
  81. for i in range(fragments_count):
  82. first = self.read_unsigned_int()
  83. first_ts = self.read_unsigned_long_long()
  84. duration = self.read_unsigned_int()
  85. if duration == 0:
  86. discontinuity_indicator = self.read_unsigned_char()
  87. else:
  88. discontinuity_indicator = None
  89. fragments.append({
  90. 'first': first,
  91. 'ts': first_ts,
  92. 'duration': duration,
  93. 'discontinuity_indicator': discontinuity_indicator,
  94. })
  95. return {
  96. 'fragments': fragments,
  97. }
  98. def read_abst(self):
  99. # version
  100. self.read_unsigned_char()
  101. # flags
  102. self.read(3)
  103. # BootstrapinfoVersion
  104. bootstrap_info_version = self.read_unsigned_int()
  105. # Profile,Live,Update,Reserved
  106. self.read(1)
  107. # time scale
  108. self.read_unsigned_int()
  109. # CurrentMediaTime
  110. self.read_unsigned_long_long()
  111. # SmpteTimeCodeOffset
  112. self.read_unsigned_long_long()
  113. # MovieIdentifier
  114. movie_identifier = self.read_string()
  115. server_count = self.read_unsigned_char()
  116. # ServerEntryTable
  117. for i in range(server_count):
  118. self.read_string()
  119. quality_count = self.read_unsigned_char()
  120. # QualityEntryTable
  121. for i in range(server_count):
  122. self.read_string()
  123. # DrmData
  124. self.read_string()
  125. # MetaData
  126. self.read_string()
  127. segments_count = self.read_unsigned_char()
  128. segments = []
  129. for i in range(segments_count):
  130. box_size, box_type, box_data = self.read_box_info()
  131. assert box_type == b'asrt'
  132. segment = FlvReader(box_data).read_asrt()
  133. segments.append(segment)
  134. fragments_run_count = self.read_unsigned_char()
  135. fragments = []
  136. for i in range(fragments_run_count):
  137. box_size, box_type, box_data = self.read_box_info()
  138. assert box_type == b'afrt'
  139. fragments.append(FlvReader(box_data).read_afrt())
  140. return {
  141. 'segments': segments,
  142. 'fragments': fragments,
  143. }
  144. def read_bootstrap_info(self):
  145. total_size, box_type, box_data = self.read_box_info()
  146. assert box_type == b'abst'
  147. return FlvReader(box_data).read_abst()
  148. def read_bootstrap_info(bootstrap_bytes):
  149. return FlvReader(bootstrap_bytes).read_bootstrap_info()
  150. def build_fragments_list(boot_info):
  151. """ Return a list of (segment, fragment) for each fragment in the video """
  152. res = []
  153. segment_run_table = boot_info['segments'][0]
  154. # I've only found videos with one segment
  155. segment_run_entry = segment_run_table['segment_run'][0]
  156. n_frags = segment_run_entry[1]
  157. fragment_run_entry_table = boot_info['fragments'][0]['fragments']
  158. first_frag_number = fragment_run_entry_table[0]['first']
  159. for (i, frag_number) in zip(range(1, n_frags+1), itertools.count(first_frag_number)):
  160. res.append((1, frag_number))
  161. return res
  162. def write_flv_header(stream, metadata):
  163. """Writes the FLV header and the metadata to stream"""
  164. # FLV header
  165. stream.write(b'FLV\x01')
  166. stream.write(b'\x05')
  167. stream.write(b'\x00\x00\x00\x09')
  168. # FLV File body
  169. stream.write(b'\x00\x00\x00\x00')
  170. # FLVTAG
  171. # Script data
  172. stream.write(b'\x12')
  173. # Size of the metadata with 3 bytes
  174. stream.write(struct_pack('!L', len(metadata))[1:])
  175. stream.write(b'\x00\x00\x00\x00\x00\x00\x00')
  176. stream.write(metadata)
  177. # Magic numbers extracted from the output files produced by AdobeHDS.php
  178. #(https://github.com/K-S-V/Scripts)
  179. stream.write(b'\x00\x00\x01\x73')
  180. def _add_ns(prop):
  181. return '{http://ns.adobe.com/f4m/1.0}%s' % prop
  182. class HttpQuietDownloader(HttpFD):
  183. def to_screen(self, *args, **kargs):
  184. pass
  185. class F4mFD(FileDownloader):
  186. """
  187. A downloader for f4m manifests or AdobeHDS.
  188. """
  189. def real_download(self, filename, info_dict):
  190. man_url = info_dict['url']
  191. self.to_screen('[download] Downloading f4m manifest')
  192. manifest = self.ydl.urlopen(man_url).read()
  193. self.report_destination(filename)
  194. http_dl = HttpQuietDownloader(self.ydl,
  195. {
  196. 'continuedl': True,
  197. 'quiet': True,
  198. 'noprogress': True,
  199. 'test': self.params.get('test', False),
  200. })
  201. doc = etree.fromstring(manifest)
  202. formats = [(int(f.attrib.get('bitrate', -1)), f) for f in doc.findall(_add_ns('media'))]
  203. formats = sorted(formats, key=lambda f: f[0])
  204. rate, media = formats[-1]
  205. base_url = compat_urlparse.urljoin(man_url, media.attrib['url'])
  206. bootstrap = base64.b64decode(doc.find(_add_ns('bootstrapInfo')).text)
  207. metadata = base64.b64decode(media.find(_add_ns('metadata')).text)
  208. boot_info = read_bootstrap_info(bootstrap)
  209. fragments_list = build_fragments_list(boot_info)
  210. if self.params.get('test', False):
  211. # We only download the first fragment
  212. fragments_list = fragments_list[:1]
  213. total_frags = len(fragments_list)
  214. tmpfilename = self.temp_name(filename)
  215. (dest_stream, tmpfilename) = sanitize_open(tmpfilename, 'wb')
  216. write_flv_header(dest_stream, metadata)
  217. # This dict stores the download progress, it's updated by the progress
  218. # hook
  219. state = {
  220. 'downloaded_bytes': 0,
  221. 'frag_counter': 0,
  222. }
  223. start = time.time()
  224. def frag_progress_hook(status):
  225. frag_total_bytes = status.get('total_bytes', 0)
  226. estimated_size = (state['downloaded_bytes'] +
  227. (total_frags - state['frag_counter']) * frag_total_bytes)
  228. if status['status'] == 'finished':
  229. state['downloaded_bytes'] += frag_total_bytes
  230. state['frag_counter'] += 1
  231. progress = self.calc_percent(state['frag_counter'], total_frags)
  232. byte_counter = state['downloaded_bytes']
  233. else:
  234. frag_downloaded_bytes = status['downloaded_bytes']
  235. byte_counter = state['downloaded_bytes'] + frag_downloaded_bytes
  236. frag_progress = self.calc_percent(frag_downloaded_bytes,
  237. frag_total_bytes)
  238. progress = self.calc_percent(state['frag_counter'], total_frags)
  239. progress += frag_progress / float(total_frags)
  240. eta = self.calc_eta(start, time.time(), estimated_size, byte_counter)
  241. self.report_progress(progress, format_bytes(estimated_size),
  242. status.get('speed'), eta)
  243. http_dl.add_progress_hook(frag_progress_hook)
  244. frags_filenames = []
  245. for (seg_i, frag_i) in fragments_list:
  246. name = 'Seg%d-Frag%d' % (seg_i, frag_i)
  247. url = base_url + name
  248. frag_filename = '%s-%s' % (tmpfilename, name)
  249. success = http_dl.download(frag_filename, {'url': url})
  250. if not success:
  251. return False
  252. with open(frag_filename, 'rb') as down:
  253. down_data = down.read()
  254. reader = FlvReader(down_data)
  255. while True:
  256. _, box_type, box_data = reader.read_box_info()
  257. if box_type == b'mdat':
  258. dest_stream.write(box_data)
  259. break
  260. frags_filenames.append(frag_filename)
  261. self.report_finish(format_bytes(state['downloaded_bytes']), time.time() - start)
  262. self.try_rename(tmpfilename, filename)
  263. for frag_file in frags_filenames:
  264. os.remove(frag_file)
  265. fsize = os.path.getsize(encodeFilename(filename))
  266. self._hook_progress({
  267. 'downloaded_bytes': fsize,
  268. 'total_bytes': fsize,
  269. 'filename': filename,
  270. 'status': 'finished',
  271. })
  272. return True