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.

84 lines
3.1 KiB

  1. from __future__ import unicode_literals
  2. import os
  3. from .fragment import FragmentFD
  4. from ..compat import compat_urllib_error
  5. from ..utils import (
  6. sanitize_open,
  7. encodeFilename,
  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. segments = info_dict['fragments'][:1] if self.params.get(
  16. 'test', False) else info_dict['fragments']
  17. ctx = {
  18. 'filename': filename,
  19. 'total_frags': len(segments),
  20. }
  21. self._prepare_and_start_frag_download(ctx)
  22. segments_filenames = []
  23. fragment_retries = self.params.get('fragment_retries', 0)
  24. skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
  25. def process_segment(segment, tmp_filename, num):
  26. segment_url = segment['url']
  27. segment_name = 'Frag%d' % num
  28. target_filename = '%s-%s' % (tmp_filename, segment_name)
  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 = num == 0 or not skip_unavailable_fragments
  32. count = 0
  33. while count <= fragment_retries:
  34. try:
  35. success = ctx['dl'].download(target_filename, {
  36. 'url': segment_url,
  37. 'http_headers': info_dict.get('http_headers'),
  38. })
  39. if not success:
  40. return False
  41. down, target_sanitized = sanitize_open(target_filename, 'rb')
  42. ctx['dest_stream'].write(down.read())
  43. down.close()
  44. segments_filenames.append(target_sanitized)
  45. break
  46. except compat_urllib_error.HTTPError as err:
  47. # YouTube may often return 404 HTTP error for a fragment causing the
  48. # whole download to fail. However if the same fragment is immediately
  49. # retried with the same request data this usually succeeds (1-2 attemps
  50. # is usually enough) thus allowing to download the whole file successfully.
  51. # To be future-proof we will retry all fragments that fail with any
  52. # HTTP error.
  53. count += 1
  54. if count <= fragment_retries:
  55. self.report_retry_fragment(err, segment_name, count, fragment_retries)
  56. if count > fragment_retries:
  57. if not fatal:
  58. self.report_skip_fragment(segment_name)
  59. return True
  60. self.report_error('giving up after %s fragment retries' % fragment_retries)
  61. return False
  62. return True
  63. for i, segment in enumerate(segments):
  64. if not process_segment(segment, ctx['tmpfilename'], i):
  65. return False
  66. self._finish_frag_download(ctx)
  67. for segment_file in segments_filenames:
  68. os.remove(encodeFilename(segment_file))
  69. return True