1 from __future__ import unicode_literals
6 from .fragment import FragmentFD
7 from ..compat import compat_urllib_error
14 class DashSegmentsFD(FragmentFD):
16 Download segments in a DASH manifest
19 FD_NAME = 'dashsegments'
21 def real_download(self, filename, info_dict):
22 base_url = info_dict['url']
23 segment_urls = [info_dict['segment_urls'][0]] if self.params.get('test', False) else info_dict['segment_urls']
24 initialization_url = info_dict.get('initialization_url')
28 'total_frags': len(segment_urls) + (1 if initialization_url else 0),
31 self._prepare_and_start_frag_download(ctx)
33 def combine_url(base_url, target_url):
34 if re.match(r'^https?://', target_url):
36 return '%s%s%s' % (base_url, '' if base_url.endswith('/') else '/', target_url)
38 segments_filenames = []
40 fragment_retries = self.params.get('fragment_retries', 0)
41 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
43 def append_url_to_file(target_url, tmp_filename, segment_name):
44 target_filename = '%s-%s' % (tmp_filename, segment_name)
46 while count <= fragment_retries:
48 success = ctx['dl'].download(target_filename, {'url': combine_url(base_url, target_url)})
51 down, target_sanitized = sanitize_open(target_filename, 'rb')
52 ctx['dest_stream'].write(down.read())
54 segments_filenames.append(target_sanitized)
56 except compat_urllib_error.HTTPError as err:
57 # YouTube may often return 404 HTTP error for a fragment causing the
58 # whole download to fail. However if the same fragment is immediately
59 # retried with the same request data this usually succeeds (1-2 attemps
60 # is usually enough) thus allowing to download the whole file successfully.
61 # To be future-proof we will retry all fragments that fail with any
64 if count <= fragment_retries:
65 self.report_retry_fragment(err, segment_name, count, fragment_retries)
66 if count > fragment_retries:
67 if skip_unavailable_fragments:
68 self.report_skip_fragment(segment_name)
70 self.report_error('giving up after %s fragment retries' % fragment_retries)
74 if initialization_url:
75 if not append_url_to_file(initialization_url, ctx['tmpfilename'], 'Init'):
77 for i, segment_url in enumerate(segment_urls):
78 if not append_url_to_file(segment_url, ctx['tmpfilename'], 'Seg%d' % i):
81 self._finish_frag_download(ctx)
83 for segment_file in segments_filenames:
84 os.remove(encodeFilename(segment_file))