fragment.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 ..networking import Request
  12. from ..networking.exceptions import HTTPError, IncompleteRead
  13. from ..utils import DownloadError, RetryManager, traverse_obj
  14. from ..utils.networking import HTTPHeaderDict
  15. from ..utils.progress import ProgressCalculator
  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 yt-dlp 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 yt-dlp). 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('yt_dlp.downloader.FragmentFD.report_retry_fragment is deprecated. '
  51. 'Use yt_dlp.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(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(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. f'{message}. Restarting from the beginning ...')
  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. # Stores the download progress, updated by the progress hook
  199. state = {
  200. 'status': 'downloading',
  201. 'downloaded_bytes': resume_len,
  202. 'fragment_index': ctx['fragment_index'],
  203. 'fragment_count': total_frags,
  204. 'filename': ctx['filename'],
  205. 'tmpfilename': ctx['tmpfilename'],
  206. }
  207. ctx['started'] = time.time()
  208. progress = ProgressCalculator(resume_len)
  209. def frag_progress_hook(s):
  210. if s['status'] not in ('downloading', 'finished'):
  211. return
  212. if not total_frags and ctx.get('fragment_count'):
  213. state['fragment_count'] = ctx['fragment_count']
  214. if ctx_id is not None and s.get('ctx_id') != ctx_id:
  215. return
  216. state['max_progress'] = ctx.get('max_progress')
  217. state['progress_idx'] = ctx.get('progress_idx')
  218. state['elapsed'] = progress.elapsed
  219. frag_total_bytes = s.get('total_bytes') or 0
  220. s['fragment_info_dict'] = s.pop('info_dict', {})
  221. # XXX: Fragment resume is not accounted for here
  222. if not ctx['live']:
  223. estimated_size = (
  224. (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes)
  225. / (state['fragment_index'] + 1) * total_frags)
  226. progress.total = estimated_size
  227. progress.update(s.get('downloaded_bytes'))
  228. state['total_bytes_estimate'] = progress.total
  229. else:
  230. progress.update(s.get('downloaded_bytes'))
  231. if s['status'] == 'finished':
  232. state['fragment_index'] += 1
  233. ctx['fragment_index'] = state['fragment_index']
  234. progress.thread_reset()
  235. state['downloaded_bytes'] = ctx['complete_frags_downloaded_bytes'] = progress.downloaded
  236. state['speed'] = ctx['speed'] = progress.speed.smooth
  237. state['eta'] = progress.eta.smooth
  238. self._hook_progress(state, info_dict)
  239. ctx['dl'].add_progress_hook(frag_progress_hook)
  240. return ctx['started']
  241. def _finish_frag_download(self, ctx, info_dict):
  242. ctx['dest_stream'].close()
  243. if self.__do_ytdl_file(ctx):
  244. self.try_remove(self.ytdl_filename(ctx['filename']))
  245. elapsed = time.time() - ctx['started']
  246. to_file = ctx['tmpfilename'] != '-'
  247. if to_file:
  248. downloaded_bytes = self.filesize_or_none(ctx['tmpfilename'])
  249. else:
  250. downloaded_bytes = ctx['complete_frags_downloaded_bytes']
  251. if not downloaded_bytes:
  252. if to_file:
  253. self.try_remove(ctx['tmpfilename'])
  254. self.report_error('The downloaded file is empty')
  255. return False
  256. elif to_file:
  257. self.try_rename(ctx['tmpfilename'], ctx['filename'])
  258. filetime = ctx.get('fragment_filetime')
  259. if self.params.get('updatetime', True) and filetime:
  260. with contextlib.suppress(Exception):
  261. os.utime(ctx['filename'], (time.time(), filetime))
  262. self._hook_progress({
  263. 'downloaded_bytes': downloaded_bytes,
  264. 'total_bytes': downloaded_bytes,
  265. 'filename': ctx['filename'],
  266. 'status': 'finished',
  267. 'elapsed': elapsed,
  268. 'ctx_id': ctx.get('ctx_id'),
  269. 'max_progress': ctx.get('max_progress'),
  270. 'progress_idx': ctx.get('progress_idx'),
  271. }, info_dict)
  272. return True
  273. def _prepare_external_frag_download(self, ctx):
  274. if 'live' not in ctx:
  275. ctx['live'] = False
  276. if not ctx['live']:
  277. total_frags_str = '%d' % ctx['total_frags']
  278. ad_frags = ctx.get('ad_frags', 0)
  279. if ad_frags:
  280. total_frags_str += ' (not including %d ad)' % ad_frags
  281. else:
  282. total_frags_str = 'unknown (live)'
  283. self.to_screen(f'[{self.FD_NAME}] Total fragments: {total_frags_str}')
  284. tmpfilename = self.temp_name(ctx['filename'])
  285. # Should be initialized before ytdl file check
  286. ctx.update({
  287. 'tmpfilename': tmpfilename,
  288. 'fragment_index': 0,
  289. })
  290. def decrypter(self, info_dict):
  291. _key_cache = {}
  292. def _get_key(url):
  293. if url not in _key_cache:
  294. _key_cache[url] = self.ydl.urlopen(self._prepare_url(info_dict, url)).read()
  295. return _key_cache[url]
  296. def decrypt_fragment(fragment, frag_content):
  297. if frag_content is None:
  298. return
  299. decrypt_info = fragment.get('decrypt_info')
  300. if not decrypt_info or decrypt_info['METHOD'] != 'AES-128':
  301. return frag_content
  302. iv = decrypt_info.get('IV') or struct.pack('>8xq', fragment['media_sequence'])
  303. decrypt_info['KEY'] = (decrypt_info.get('KEY')
  304. or _get_key(traverse_obj(info_dict, ('hls_aes', 'uri')) or decrypt_info['URI']))
  305. # Don't decrypt the content in tests since the data is explicitly truncated and it's not to a valid block
  306. # size (see https://github.com/ytdl-org/youtube-dl/pull/27660). Tests only care that the correct data downloaded,
  307. # not what it decrypts to.
  308. if self.params.get('test', False):
  309. return frag_content
  310. return unpad_pkcs7(aes_cbc_decrypt_bytes(frag_content, decrypt_info['KEY'], iv))
  311. return decrypt_fragment
  312. def download_and_append_fragments_multiple(self, *args, **kwargs):
  313. """
  314. @params (ctx1, fragments1, info_dict1), (ctx2, fragments2, info_dict2), ...
  315. all args must be either tuple or list
  316. """
  317. interrupt_trigger = [True]
  318. max_progress = len(args)
  319. if max_progress == 1:
  320. return self.download_and_append_fragments(*args[0], **kwargs)
  321. max_workers = self.params.get('concurrent_fragment_downloads', 1)
  322. if max_progress > 1:
  323. self._prepare_multiline_status(max_progress)
  324. is_live = any(traverse_obj(args, (..., 2, 'is_live')))
  325. def thread_func(idx, ctx, fragments, info_dict, tpe):
  326. ctx['max_progress'] = max_progress
  327. ctx['progress_idx'] = idx
  328. return self.download_and_append_fragments(
  329. ctx, fragments, info_dict, **kwargs, tpe=tpe, interrupt_trigger=interrupt_trigger)
  330. class FTPE(concurrent.futures.ThreadPoolExecutor):
  331. # has to stop this or it's going to wait on the worker thread itself
  332. def __exit__(self, exc_type, exc_val, exc_tb):
  333. pass
  334. if os.name == 'nt':
  335. def future_result(future):
  336. while True:
  337. try:
  338. return future.result(0.1)
  339. except KeyboardInterrupt:
  340. raise
  341. except concurrent.futures.TimeoutError:
  342. continue
  343. else:
  344. def future_result(future):
  345. return future.result()
  346. def interrupt_trigger_iter(fg):
  347. for f in fg:
  348. if not interrupt_trigger[0]:
  349. break
  350. yield f
  351. spins = []
  352. for idx, (ctx, fragments, info_dict) in enumerate(args):
  353. tpe = FTPE(math.ceil(max_workers / max_progress))
  354. job = tpe.submit(thread_func, idx, ctx, interrupt_trigger_iter(fragments), info_dict, tpe)
  355. spins.append((tpe, job))
  356. result = True
  357. for tpe, job in spins:
  358. try:
  359. result = result and future_result(job)
  360. except KeyboardInterrupt:
  361. interrupt_trigger[0] = False
  362. finally:
  363. tpe.shutdown(wait=True)
  364. if not interrupt_trigger[0] and not is_live:
  365. raise KeyboardInterrupt
  366. # we expect the user wants to stop and DO WANT the preceding postprocessors to run;
  367. # so returning a intermediate result here instead of KeyboardInterrupt on live
  368. return result
  369. def download_and_append_fragments(
  370. self, ctx, fragments, info_dict, *, is_fatal=(lambda idx: False),
  371. pack_func=(lambda content, idx: content), finish_func=None,
  372. tpe=None, interrupt_trigger=(True, )):
  373. if not self.params.get('skip_unavailable_fragments', True):
  374. is_fatal = lambda _: True
  375. def download_fragment(fragment, ctx):
  376. if not interrupt_trigger[0]:
  377. return
  378. frag_index = ctx['fragment_index'] = fragment['frag_index']
  379. ctx['last_error'] = None
  380. headers = HTTPHeaderDict(info_dict.get('http_headers'))
  381. byte_range = fragment.get('byte_range')
  382. if byte_range:
  383. headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'] - 1)
  384. # Never skip the first fragment
  385. fatal = is_fatal(fragment.get('index') or (frag_index - 1))
  386. def error_callback(err, count, retries):
  387. if fatal and count > retries:
  388. ctx['dest_stream'].close()
  389. self.report_retry(err, count, retries, frag_index, fatal)
  390. ctx['last_error'] = err
  391. for retry in RetryManager(self.params.get('fragment_retries'), error_callback):
  392. try:
  393. ctx['fragment_count'] = fragment.get('fragment_count')
  394. if not self._download_fragment(
  395. ctx, fragment['url'], info_dict, headers, info_dict.get('request_data')):
  396. return
  397. except (HTTPError, IncompleteRead) as err:
  398. retry.error = err
  399. continue
  400. except DownloadError: # has own retry settings
  401. if fatal:
  402. raise
  403. def append_fragment(frag_content, frag_index, ctx):
  404. if frag_content:
  405. self._append_fragment(ctx, pack_func(frag_content, frag_index))
  406. elif not is_fatal(frag_index - 1):
  407. self.report_skip_fragment(frag_index, 'fragment not found')
  408. else:
  409. ctx['dest_stream'].close()
  410. self.report_error(f'fragment {frag_index} not found, unable to continue')
  411. return False
  412. return True
  413. decrypt_fragment = self.decrypter(info_dict)
  414. max_workers = math.ceil(
  415. self.params.get('concurrent_fragment_downloads', 1) / ctx.get('max_progress', 1))
  416. if max_workers > 1:
  417. def _download_fragment(fragment):
  418. ctx_copy = ctx.copy()
  419. download_fragment(fragment, ctx_copy)
  420. return fragment, fragment['frag_index'], ctx_copy.get('fragment_filename_sanitized')
  421. with tpe or concurrent.futures.ThreadPoolExecutor(max_workers) as pool:
  422. try:
  423. for fragment, frag_index, frag_filename in pool.map(_download_fragment, fragments):
  424. ctx.update({
  425. 'fragment_filename_sanitized': frag_filename,
  426. 'fragment_index': frag_index,
  427. })
  428. if not append_fragment(decrypt_fragment(fragment, self._read_fragment(ctx)), frag_index, ctx):
  429. return False
  430. except KeyboardInterrupt:
  431. self._finish_multiline_status()
  432. self.report_error(
  433. 'Interrupted by user. Waiting for all threads to shutdown...', is_error=False, tb=False)
  434. pool.shutdown(wait=False)
  435. raise
  436. else:
  437. for fragment in fragments:
  438. if not interrupt_trigger[0]:
  439. break
  440. try:
  441. download_fragment(fragment, ctx)
  442. result = append_fragment(
  443. decrypt_fragment(fragment, self._read_fragment(ctx)), fragment['frag_index'], ctx)
  444. except KeyboardInterrupt:
  445. if info_dict.get('is_live'):
  446. break
  447. raise
  448. if not result:
  449. return False
  450. if finish_func is not None:
  451. ctx['dest_stream'].write(finish_func())
  452. ctx['dest_stream'].flush()
  453. return self._finish_frag_download(ctx, info_dict)