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.

81 lines
3.0 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, {'url': segment_url})
  36. if not success:
  37. return False
  38. down, target_sanitized = sanitize_open(target_filename, 'rb')
  39. ctx['dest_stream'].write(down.read())
  40. down.close()
  41. segments_filenames.append(target_sanitized)
  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 attemps
  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. count += 1
  51. if count <= fragment_retries:
  52. self.report_retry_fragment(err, segment_name, count, fragment_retries)
  53. if count > fragment_retries:
  54. if not fatal:
  55. self.report_skip_fragment(segment_name)
  56. return True
  57. self.report_error('giving up after %s fragment retries' % fragment_retries)
  58. return False
  59. return True
  60. for i, segment in enumerate(segments):
  61. if not process_segment(segment, ctx['tmpfilename'], i):
  62. return False
  63. self._finish_frag_download(ctx)
  64. for segment_file in segments_filenames:
  65. os.remove(encodeFilename(segment_file))
  66. return True