]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/dash.py
New upstream version 2017.02.07
[youtubedl] / youtube_dl / downloader / dash.py
1 from __future__ import unicode_literals
2
3 import os
4
5 from .fragment import FragmentFD
6 from ..compat import compat_urllib_error
7 from ..utils import (
8 sanitize_open,
9 encodeFilename,
10 )
11
12
13 class DashSegmentsFD(FragmentFD):
14 """
15 Download segments in a DASH manifest
16 """
17
18 FD_NAME = 'dashsegments'
19
20 def real_download(self, filename, info_dict):
21 segments = info_dict['fragments'][:1] if self.params.get(
22 'test', False) else info_dict['fragments']
23
24 ctx = {
25 'filename': filename,
26 'total_frags': len(segments),
27 }
28
29 self._prepare_and_start_frag_download(ctx)
30
31 segments_filenames = []
32
33 fragment_retries = self.params.get('fragment_retries', 0)
34 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
35
36 def process_segment(segment, tmp_filename, num):
37 segment_url = segment['url']
38 segment_name = 'Frag%d' % num
39 target_filename = '%s-%s' % (tmp_filename, segment_name)
40 # In DASH, the first segment contains necessary headers to
41 # generate a valid MP4 file, so always abort for the first segment
42 fatal = num == 0 or not skip_unavailable_fragments
43 count = 0
44 while count <= fragment_retries:
45 try:
46 success = ctx['dl'].download(target_filename, {'url': segment_url})
47 if not success:
48 return False
49 down, target_sanitized = sanitize_open(target_filename, 'rb')
50 ctx['dest_stream'].write(down.read())
51 down.close()
52 segments_filenames.append(target_sanitized)
53 break
54 except compat_urllib_error.HTTPError as err:
55 # YouTube may often return 404 HTTP error for a fragment causing the
56 # whole download to fail. However if the same fragment is immediately
57 # retried with the same request data this usually succeeds (1-2 attemps
58 # is usually enough) thus allowing to download the whole file successfully.
59 # To be future-proof we will retry all fragments that fail with any
60 # HTTP error.
61 count += 1
62 if count <= fragment_retries:
63 self.report_retry_fragment(err, segment_name, count, fragment_retries)
64 if count > fragment_retries:
65 if not fatal:
66 self.report_skip_fragment(segment_name)
67 return True
68 self.report_error('giving up after %s fragment retries' % fragment_retries)
69 return False
70 return True
71
72 for i, segment in enumerate(segments):
73 if not process_segment(segment, ctx['tmpfilename'], i):
74 return False
75
76 self._finish_frag_download(ctx)
77
78 for segment_file in segments_filenames:
79 os.remove(encodeFilename(segment_file))
80
81 return True