fragment.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. import concurrent.futures
  2. import contextlib
  3. import json
  4. import math
  5. import os
  6. import struct
  7. import time
  8. from .common import FileDownloader
  9. from .http import HttpFD
  10. from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
  11. from ..compat import compat_os_name
  12. from ..networking import Request
  13. from ..networking.exceptions import HTTPError, IncompleteRead
  14. from ..utils import DownloadError, RetryManager, encodeFilename, traverse_obj
  15. from ..utils.networking import HTTPHeaderDict
  16. class HttpQuietDownloader(HttpFD):
  17. def to_screen(self, *args, **kargs):
  18. pass
  19. to_console_title = to_screen
  20. class FragmentFD(FileDownloader):
  21. """
  22. A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
  23. Available options:
  24. fragment_retries: Number of times to retry a fragment for HTTP error
  25. (DASH and hlsnative only). Default is 0 for API, but 10 for CLI
  26. skip_unavailable_fragments:
  27. Skip unavailable fragments (DASH and hlsnative only)
  28. keep_fragments: Keep downloaded fragments on disk after downloading is
  29. finished
  30. concurrent_fragment_downloads: The number of threads to use for native hls and dash downloads
  31. _no_ytdl_file: Don't use .ytdl file
  32. For each incomplete fragment download hypervideo keeps on disk a special
  33. bookkeeping file with download state and metadata (in future such files will
  34. be used for any incomplete download handled by hypervideo). This file is
  35. used to properly handle resuming, check download file consistency and detect
  36. potential errors. The file has a .ytdl extension and represents a standard
  37. JSON file of the following format:
  38. extractor:
  39. Dictionary of extractor related data. TBD.
  40. downloader:
  41. Dictionary of downloader related data. May contain following data:
  42. current_fragment:
  43. Dictionary with current (being downloaded) fragment data:
  44. index: 0-based index of current fragment among all fragments
  45. fragment_count:
  46. Total count of fragments
  47. This feature is experimental and file format may change in future.
  48. """
  49. def report_retry_fragment(self, err, frag_index, count, retries):
  50. self.deprecation_warning('hypervideo_dl.downloader.FragmentFD.report_retry_fragment is deprecated. '
  51. 'Use hypervideo_dl.downloader.FileDownloader.report_retry instead')
  52. return self.report_retry(err, count, retries, frag_index)
  53. def report_skip_fragment(self, frag_index, err=None):
  54. err = f' {err};' if err else ''
  55. self.to_screen(f'[download]{err} Skipping fragment {frag_index:d} ...')
  56. def _prepare_url(self, info_dict, url):
  57. headers = info_dict.get('http_headers')
  58. return Request(url, None, headers) if headers else url
  59. def _prepare_and_start_frag_download(self, ctx, info_dict):
  60. self._prepare_frag_download(ctx)
  61. self._start_frag_download(ctx, info_dict)
  62. def __do_ytdl_file(self, ctx):
  63. return ctx['live'] is not True and ctx['tmpfilename'] != '-' and not self.params.get('_no_ytdl_file')
  64. def _read_ytdl_file(self, ctx):
  65. assert 'ytdl_corrupt' not in ctx
  66. stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
  67. try:
  68. ytdl_data = json.loads(stream.read())
  69. ctx['fragment_index'] = ytdl_data['downloader']['current_fragment']['index']
  70. if 'extra_state' in ytdl_data['downloader']:
  71. ctx['extra_state'] = ytdl_data['downloader']['extra_state']
  72. except Exception:
  73. ctx['ytdl_corrupt'] = True
  74. finally:
  75. stream.close()
  76. def _write_ytdl_file(self, ctx):
  77. frag_index_stream, _ = self.sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
  78. try:
  79. downloader = {
  80. 'current_fragment': {
  81. 'index': ctx['fragment_index'],
  82. },
  83. }
  84. if 'extra_state' in ctx:
  85. downloader['extra_state'] = ctx['extra_state']
  86. if ctx.get('fragment_count') is not None:
  87. downloader['fragment_count'] = ctx['fragment_count']
  88. frag_index_stream.write(json.dumps({'downloader': downloader}))
  89. finally:
  90. frag_index_stream.close()
  91. def _download_fragment(self, ctx, frag_url, info_dict, headers=None, request_data=None):
  92. fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
  93. fragment_info_dict = {
  94. 'url': frag_url,
  95. 'http_headers': headers or info_dict.get('http_headers'),
  96. 'request_data': request_data,
  97. 'ctx_id': ctx.get('ctx_id'),
  98. }
  99. frag_resume_len = 0
  100. if ctx['dl'].params.get('continuedl', True):
  101. frag_resume_len = self.filesize_or_none(self.temp_name(fragment_filename))
  102. fragment_info_dict['frag_resume_len'] = ctx['frag_resume_len'] = frag_resume_len
  103. success, _ = ctx['dl'].download(fragment_filename, fragment_info_dict)
  104. if not success:
  105. return False
  106. if fragment_info_dict.get('filetime'):
  107. ctx['fragment_filetime'] = fragment_info_dict.get('filetime')
  108. ctx['fragment_filename_sanitized'] = fragment_filename
  109. return True
  110. def _read_fragment(self, ctx):
  111. if not ctx.get('fragment_filename_sanitized'):
  112. return None
  113. try:
  114. down, frag_sanitized = self.sanitize_open(ctx['fragment_filename_sanitized'], 'rb')
  115. except FileNotFoundError:
  116. if ctx.get('live'):
  117. return None
  118. raise
  119. ctx['fragment_filename_sanitized'] = frag_sanitized
  120. frag_content = down.read()
  121. down.close()
  122. return frag_content
  123. def _append_fragment(self, ctx, frag_content):
  124. try:
  125. ctx['dest_stream'].write(frag_content)
  126. ctx['dest_stream'].flush()
  127. finally:
  128. if self.__do_ytdl_file(ctx):
  129. self._write_ytdl_file(ctx)
  130. if not self.params.get('keep_fragments', False):
  131. self.try_remove(encodeFilename(ctx['fragment_filename_sanitized']))
  132. del ctx['fragment_filename_sanitized']
  133. def _prepare_frag_download(self, ctx):
  134. if not ctx.setdefault('live', False):
  135. total_frags_str = '%d' % ctx['total_frags']
  136. ad_frags = ctx.get('ad_frags', 0)
  137. if ad_frags:
  138. total_frags_str += ' (not including %d ad)' % ad_frags
  139. else:
  140. total_frags_str = 'unknown (live)'
  141. self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
  142. self.report_destination(ctx['filename'])
  143. dl = HttpQuietDownloader(self.ydl, {
  144. **self.params,
  145. 'noprogress': True,
  146. 'test': False,
  147. 'sleep_interval': 0,
  148. 'max_sleep_interval': 0,
  149. 'sleep_interval_subtitles': 0,
  150. })
  151. tmpfilename = self.temp_name(ctx['filename'])
  152. open_mode = 'wb'
  153. # Establish possible resume length
  154. resume_len = self.filesize_or_none(tmpfilename)
  155. if resume_len > 0:
  156. open_mode = 'ab'
  157. # Should be initialized before ytdl file check
  158. ctx.update({
  159. 'tmpfilename': tmpfilename,
  160. 'fragment_index': 0,
  161. })
  162. if self.__do_ytdl_file(ctx):
  163. ytdl_file_exists = os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename'])))
  164. continuedl = self.params.get('continuedl', True)
  165. if continuedl and ytdl_file_exists:
  166. self._read_ytdl_file(ctx)
  167. is_corrupt = ctx.get('ytdl_corrupt') is True
  168. is_inconsistent = ctx['fragment_index'] > 0 and resume_len == 0
  169. if is_corrupt or is_inconsistent:
  170. message = (
  171. '.ytdl file is corrupt' if is_corrupt else
  172. 'Inconsistent state of incomplete fragment download')
  173. self.report_warning(
  174. '%s. Restarting from the beginning ...' % message)
  175. ctx['fragment_index'] = resume_len = 0
  176. if 'ytdl_corrupt' in ctx:
  177. del ctx['ytdl_corrupt']
  178. self._write_ytdl_file(ctx)
  179. else:
  180. if not continuedl:
  181. if ytdl_file_exists:
  182. self._read_ytdl_file(ctx)
  183. ctx['fragment_index'] = resume_len = 0
  184. self._write_ytdl_file(ctx)
  185. assert ctx['fragment_index'] == 0
  186. dest_stream, tmpfilename = self.sanitize_open(tmpfilename, open_mode)
  187. ctx.update({
  188. 'dl': dl,
  189. 'dest_stream': dest_stream,
  190. 'tmpfilename': tmpfilename,
  191. # Total complete fragments downloaded so far in bytes
  192. 'complete_frags_downloaded_bytes': resume_len,
  193. })
  194. def _start_frag_download(self, ctx, info_dict):
  195. resume_len = ctx['complete_frags_downloaded_bytes']
  196. total_frags = ctx['total_frags']
  197. ctx_id = ctx.get('ctx_id')
  198. # This dict stores the download progress, it's updated by the progress
  199. # hook
  200. state = {
  201. 'status': 'downloading',
  202. 'downloaded_bytes': resume_len,
  203. 'fragment_index': ctx['fragment_index'],
  204. 'fragment_count': total_frags,
  205. 'filename': ctx['filename'],
  206. 'tmpfilename': ctx['tmpfilename'],
  207. }
  208. start = time.time()
  209. ctx.update({
  210. 'started': start,
  211. 'fragment_started': start,
  212. # Amount of fragment's bytes downloaded by the time of the previous
  213. # frag progress hook invocation
  214. 'prev_frag_downloaded_bytes': 0,
  215. })
  216. def frag_progress_hook(s):
  217. if s['status'] not in ('downloading', 'finished'):
  218. return
  219. if not total_frags and ctx.get('fragment_count'):
  220. state['fragment_count'] = ctx['fragment_count']
  221. if ctx_id is not None and s.get('ctx_id') != ctx_id:
  222. return
  223. state['max_progress'] = ctx.get('max_progress')
  224. state['progress_idx'] = ctx.get('progress_idx')
  225. time_now = time.time()
  226. state['elapsed'] = time_now - start
  227. frag_total_bytes = s.get('total_bytes') or 0
  228. s['fragment_info_dict'] = s.pop('info_dict', {})
  229. if not ctx['live']:
  230. estimated_size = (
  231. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
  232. / (state['fragment_index'] + 1) * total_frags)
  233. state['total_bytes_estimate'] = estimated_size
  234. if s['status'] == 'finished':
  235. state['fragment_index'] += 1
  236. ctx['fragment_index'] = state['fragment_index']
  237. state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
  238. ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
  239. ctx['speed'] = state['speed'] = self.calc_speed(
  240. ctx['fragment_started'], time_now, frag_total_bytes)
  241. ctx['fragment_started'] = time.time()
  242. ctx['prev_frag_downloaded_bytes'] = 0
  243. else:
  244. frag_downloaded_bytes = s['downloaded_bytes']
  245. state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
  246. ctx['speed'] = state['speed'] = self.calc_speed(
  247. ctx['fragment_started'], time_now, frag_downloaded_bytes - ctx.get('frag_resume_len', 0))
  248. if not ctx['live']:
  249. state['eta'] = self.calc_eta(state['speed'], estimated_size - state['downloaded_bytes'])
  250. ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
  251. self._hook_progress(state, info_dict)
  252. ctx['dl'].add_progress_hook(frag_progress_hook)
  253. return start
  254. def _finish_frag_download(self, ctx, info_dict):
  255. ctx['dest_stream'].close()
  256. if self.__do_ytdl_file(ctx):
  257. self.try_remove(self.ytdl_filename(ctx['filename']))
  258. elapsed = time.time() - ctx['started']
  259. to_file = ctx['tmpfilename'] != '-'
  260. if to_file:
  261. downloaded_bytes = self.filesize_or_none(ctx['tmpfilename'])
  262. else:
  263. downloaded_bytes = ctx['complete_frags_downloaded_bytes']
  264. if not downloaded_bytes:
  265. if to_file:
  266. self.try_remove(ctx['tmpfilename'])
  267. self.report_error('The downloaded file is empty')
  268. return False
  269. elif to_file:
  270. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  271. filetime = ctx.get('fragment_filetime')
  272. if self.params.get('updatetime', True) and filetime:
  273. with contextlib.suppress(Exception):
  274. os.utime(ctx['filename'], (time.time(), filetime))
  275. self._hook_progress({
  276. 'downloaded_bytes': downloaded_bytes,
  277. 'total_bytes': downloaded_bytes,
  278. 'filename': ctx['filename'],
  279. 'status': 'finished',
  280. 'elapsed': elapsed,
  281. 'ctx_id': ctx.get('ctx_id'),
  282. 'max_progress': ctx.get('max_progress'),
  283. 'progress_idx': ctx.get('progress_idx'),
  284. }, info_dict)
  285. return True
  286. def _prepare_external_frag_download(self, ctx):
  287. if 'live' not in ctx:
  288. ctx['live'] = False
  289. if not ctx['live']:
  290. total_frags_str = '%d' % ctx['total_frags']
  291. ad_frags = ctx.get('ad_frags', 0)
  292. if ad_frags:
  293. total_frags_str += ' (not including %d ad)' % ad_frags
  294. else:
  295. total_frags_str = 'unknown (live)'
  296. self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
  297. tmpfilename = self.temp_name(ctx['filename'])
  298. # Should be initialized before ytdl file check
  299. ctx.update({
  300. 'tmpfilename': tmpfilename,
  301. 'fragment_index': 0,
  302. })
  303. def decrypter(self, info_dict):
  304. _key_cache = {}
  305. def _get_key(url):
  306. if url not in _key_cache:
  307. _key_cache[url] = self.ydl.urlopen(self._prepare_url(info_dict, url)).read()
  308. return _key_cache[url]
  309. def decrypt_fragment(fragment, frag_content):
  310. if frag_content is None:
  311. return
  312. decrypt_info = fragment.get('decrypt_info')
  313. if not decrypt_info or decrypt_info['METHOD'] != 'AES-128':
  314. return frag_content
  315. iv = decrypt_info.get('IV') or struct.pack('>8xq', fragment['media_sequence'])
  316. decrypt_info['KEY'] = (decrypt_info.get('KEY')
  317. or _get_key(traverse_obj(info_dict, ('hls_aes', 'uri')) or decrypt_info['URI']))
  318. # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
  319. # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
  320. # not what it decrypts to.
  321. if self.params.get('test', False):
  322. return frag_content
  323. return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv))
  324. return decrypt_fragment
  325. def download_and_append_fragments_multiple(self, *args, **kwargs):
  326. '''
  327. @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
  328. all args must be either tuple or list
  329. '''
  330. interrupt_trigger = [True]
  331. max_progress = len(args)
  332. if max_progress == 1:
  333. return self.download_and_append_fragments(*args[0], **kwargs)
  334. max_workers = self.params.get('concurrent_fragment_downloads', 1)
  335. if max_progress > 1:
  336. self._prepare_multiline_status(max_progress)
  337. is_live = any(traverse_obj(args, (..., 2, 'is_live')))
  338. def thread_func(idx, ctx, fragments, info_dict, tpe):
  339. ctx['max_progress'] = max_progress
  340. ctx['progress_idx'] = idx
  341. return self.download_and_append_fragments(
  342. ctx, fragments, info_dict, **kwargs, tpe=tpe, interrupt_trigger=interrupt_trigger)
  343. class FTPE(concurrent.futures.ThreadPoolExecutor):
  344. # has to stop this or it's going to wait on the worker thread itself
  345. def __exit__(self, exc_type, exc_val, exc_tb):
  346. pass
  347. if compat_os_name == 'nt':
  348. def future_result(future):
  349. while True:
  350. try:
  351. return future.result(0.1)
  352. except KeyboardInterrupt:
  353. raise
  354. except concurrent.futures.TimeoutError:
  355. continue
  356. else:
  357. def future_result(future):
  358. return future.result()
  359. def interrupt_trigger_iter(fg):
  360. for f in fg:
  361. if not interrupt_trigger[0]:
  362. break
  363. yield f
  364. spins = []
  365. for idx, (ctx, fragments, info_dict) in enumerate(args):
  366. tpe = FTPE(math.ceil(max_workers / max_progress))
  367. job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(fragments), info_dict, tpe)
  368. spins.append((tpe, job))
  369. result = True
  370. for tpe, job in spins:
  371. try:
  372. result = result and future_result(job)
  373. except KeyboardInterrupt:
  374. interrupt_trigger[0] = False
  375. finally:
  376. tpe.shutdown(wait=True)
  377. if not interrupt_trigger[0] and not is_live:
  378. raise KeyboardInterrupt()
  379. # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
  380. # so returning a intermediate result here instead of KeyboardInterrupt on live
  381. return result
  382. def download_and_append_fragments(
  383. self, ctx, fragments, info_dict, *, is_fatal=(lambda idx: False),
  384. pack_func=(lambda content, idx: content), finish_func=None,
  385. tpe=None, interrupt_trigger=(True, )):
  386. if not self.params.get('skip_unavailable_fragments', True):
  387. is_fatal = lambda _: True
  388. def download_fragment(fragment, ctx):
  389. if not interrupt_trigger[0]:
  390. return
  391. frag_index = ctx['fragment_index'] = fragment['frag_index']
  392. ctx['last_error'] = None
  393. headers = HTTPHeaderDict(info_dict.get('http_headers'))
  394. byte_range = fragment.get('byte_range')
  395. if byte_range:
  396. headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
  397. # Never skip the first fragment
  398. fatal = is_fatal(fragment.get('index') or (frag_index - 1))
  399. def error_callback(err, count, retries):
  400. if fatal and count > retries:
  401. ctx['dest_stream'].close()
  402. self.report_retry(err, count, retries, frag_index, fatal)
  403. ctx['last_error'] = err
  404. for retry in RetryManager(self.params.get('fragment_retries'), error_callback):
  405. try:
  406. ctx['fragment_count'] = fragment.get('fragment_count')
  407. if not self._download_fragment(
  408. ctx, fragment['url'], info_dict, headers, info_dict.get('request_data')):
  409. return
  410. except (HTTPError, IncompleteRead) as err:
  411. retry.error = err
  412. continue
  413. except DownloadError: # has own retry settings
  414. if fatal:
  415. raise
  416. def append_fragment(frag_content, frag_index, ctx):
  417. if frag_content:
  418. self._append_fragment(ctx, pack_func(frag_content, frag_index))
  419. elif not is_fatal(frag_index - 1):
  420. self.report_skip_fragment(frag_index, 'fragment not found')
  421. else:
  422. ctx['dest_stream'].close()
  423. self.report_error(f'fragment {frag_index} not found, unable to continue')
  424. return False
  425. return True
  426. decrypt_fragment = self.decrypter(info_dict)
  427. max_workers = math.ceil(
  428. self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1))
  429. if max_workers > 1:
  430. def _download_fragment(fragment):
  431. ctx_copy = ctx.copy()
  432. download_fragment(fragment, ctx_copy)
  433. return fragment, fragment['frag_index'], ctx_copy.get('fragment_filename_sanitized')
  434. self.report_warning('The download speed shown is only of one thread. This is a known issue')
  435. with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
  436. try:
  437. for fragment, frag_index, frag_filename in pool.map(_download_fragment, fragments):
  438. ctx.update({
  439. 'fragment_filename_sanitized': frag_filename,
  440. 'fragment_index': frag_index,
  441. })
  442. if not append_fragment(decrypt_fragment(fragment, self._read_fragment(ctx)), frag_index, ctx):
  443. return False
  444. except KeyboardInterrupt:
  445. self._finish_multiline_status()
  446. self.report_error(
  447. 'Interrupted by user. Waiting for all threads to shutdown...', is_error=False, tb=False)
  448. pool.shutdown(wait=False)
  449. raise
  450. else:
  451. for fragment in fragments:
  452. if not interrupt_trigger[0]:
  453. break
  454. try:
  455. download_fragment(fragment, ctx)
  456. result = append_fragment(
  457. decrypt_fragment(fragment, self._read_fragment(ctx)), fragment['frag_index'], ctx)
  458. except KeyboardInterrupt:
  459. if info_dict.get('is_live'):
  460. break
  461. raise
  462. if not result:
  463. return False
  464. if finish_func is not None:
  465. ctx['dest_stream'].write(finish_func())
  466. ctx['dest_stream'].flush()
  467. return self._finish_frag_download(ctx, info_dict)