dash.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from __future__ import unicode_literals
  2. import itertools
  3. from .fragment import FragmentFD
  4. from ..compat import compat_urllib_error
  5. from ..utils import (
  6. DownloadError,
  7. urljoin,
  8. )
  9. class DashSegmentsFD(FragmentFD):
  10. """
  11. Download segments in a DASH manifest
  12. """
  13. FD_NAME = 'dashsegments'
  14. def real_download(self, filename, info_dict):
  15. fragment_base_url = info_dict.get('fragment_base_url')
  16. fragments = info_dict['fragments'][:1] if self.params.get(
  17. 'test', False) else info_dict['fragments']
  18. ctx = {
  19. 'filename': filename,
  20. 'total_frags': len(fragments),
  21. }
  22. self._prepare_and_start_frag_download(ctx)
  23. fragment_retries = self.params.get('fragment_retries', 0)
  24. skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
  25. for frag_index, fragment in enumerate(fragments, 1):
  26. if frag_index <= ctx['fragment_index']:
  27. continue
  28. # In DASH, the first segment contains necessary headers to
  29. # generate a valid MP4 file, so always abort for the first segment
  30. fatal = frag_index == 1 or not skip_unavailable_fragments
  31. for count in itertools.count():
  32. try:
  33. fragment_url = fragment.get('url')
  34. if not fragment_url:
  35. assert fragment_base_url
  36. fragment_url = urljoin(fragment_base_url, fragment['path'])
  37. success, frag_content = self._download_fragment(ctx, fragment_url, info_dict)
  38. if not success:
  39. return False
  40. self._append_fragment(ctx, frag_content)
  41. except compat_urllib_error.HTTPError as err:
  42. # YouTube may often return 404 HTTP error for a fragment causing the
  43. # whole download to fail. However if the same fragment is immediately
  44. # retried with the same request data this usually succeeds (1-2 attempts
  45. # is usually enough) thus allowing to download the whole file successfully.
  46. # To be future-proof we will retry all fragments that fail with any
  47. # HTTP error.
  48. if count < fragment_retries:
  49. self.report_retry_fragment(err, frag_index, count + 1, fragment_retries)
  50. continue
  51. except DownloadError:
  52. # Don't retry fragment if error occurred during HTTP downloading
  53. # itself since it has its own retry settings
  54. if fatal:
  55. raise
  56. self.report_skip_fragment(frag_index)
  57. break
  58. if count >= fragment_retries:
  59. if not fatal:
  60. self.report_skip_fragment(frag_index)
  61. continue
  62. self.report_error('giving up after %s fragment retries' % fragment_retries)
  63. return False
  64. self._finish_frag_download(ctx)
  65. return True