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 process_segment(segment, tmp_filename, fatal):
44 target_url, segment_name = segment
45 target_filename = '%s-%s' % (tmp_filename, segment_name)
47 while count <= fragment_retries:
49 success = ctx['dl'].download(target_filename, {'url': combine_url(base_url, target_url)})
52 down, target_sanitized = sanitize_open(target_filename, 'rb')
53 ctx['dest_stream'].write(down.read())
55 segments_filenames.append(target_sanitized)
57 except compat_urllib_error.HTTPError as err:
58 # YouTube may often return 404 HTTP error for a fragment causing the
59 # whole download to fail. However if the same fragment is immediately
60 # retried with the same request data this usually succeeds (1-2 attemps
61 # is usually enough) thus allowing to download the whole file successfully.
62 # To be future-proof we will retry all fragments that fail with any
65 if count <= fragment_retries:
66 self.report_retry_fragment(err, segment_name, count, fragment_retries)
67 if count > fragment_retries:
69 self.report_skip_fragment(segment_name)
71 self.report_error('giving up after %s fragment retries' % fragment_retries)
75 segments_to_download = [(initialization_url, 'Init')] if initialization_url else []
76 segments_to_download.extend([
77 (segment_url, 'Seg%d' % i)
78 for i, segment_url in enumerate(segment_urls)])
80 for i, segment in enumerate(segments_to_download):
81 # In DASH, the first segment contains necessary headers to
82 # generate a valid MP4 file, so always abort for the first segment
83 fatal = i == 0 or not skip_unavailable_fragments
84 if not process_segment(segment, ctx['tmpfilename'], fatal):
87 self._finish_frag_download(ctx)
89 for segment_file in segments_filenames:
90 os.remove(encodeFilename(segment_file))