1
0

dash.py 3.1 KB

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