]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/fragment.py
New upstream version 2016.12.01
[youtubedl] / youtube_dl / downloader / fragment.py
1 from __future__ import division, unicode_literals
2
3 import os
4 import time
5
6 from .common import FileDownloader
7 from .http import HttpFD
8 from ..utils import (
9 error_to_compat_str,
10 encodeFilename,
11 sanitize_open,
12 sanitized_Request,
13 )
14
15
16 class HttpQuietDownloader(HttpFD):
17 def to_screen(self, *args, **kargs):
18 pass
19
20
21 class FragmentFD(FileDownloader):
22 """
23 A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
24
25 Available options:
26
27 fragment_retries: Number of times to retry a fragment for HTTP error (DASH
28 and hlsnative only)
29 skip_unavailable_fragments:
30 Skip unavailable fragments (DASH and hlsnative only)
31 """
32
33 def report_retry_fragment(self, err, fragment_name, count, retries):
34 self.to_screen(
35 '[download] Got server HTTP error: %s. Retrying fragment %s (attempt %d of %s)...'
36 % (error_to_compat_str(err), fragment_name, count, self.format_retries(retries)))
37
38 def report_skip_fragment(self, fragment_name):
39 self.to_screen('[download] Skipping fragment %s...' % fragment_name)
40
41 def _prepare_url(self, info_dict, url):
42 headers = info_dict.get('http_headers')
43 return sanitized_Request(url, None, headers) if headers else url
44
45 def _prepare_and_start_frag_download(self, ctx):
46 self._prepare_frag_download(ctx)
47 self._start_frag_download(ctx)
48
49 def _prepare_frag_download(self, ctx):
50 if 'live' not in ctx:
51 ctx['live'] = False
52 self.to_screen(
53 '[%s] Total fragments: %s'
54 % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
55 self.report_destination(ctx['filename'])
56 dl = HttpQuietDownloader(
57 self.ydl,
58 {
59 'continuedl': True,
60 'quiet': True,
61 'noprogress': True,
62 'ratelimit': self.params.get('ratelimit'),
63 'retries': self.params.get('retries', 0),
64 'test': self.params.get('test', False),
65 }
66 )
67 tmpfilename = self.temp_name(ctx['filename'])
68 dest_stream, tmpfilename = sanitize_open(tmpfilename, 'wb')
69 ctx.update({
70 'dl': dl,
71 'dest_stream': dest_stream,
72 'tmpfilename': tmpfilename,
73 })
74
75 def _start_frag_download(self, ctx):
76 total_frags = ctx['total_frags']
77 # This dict stores the download progress, it's updated by the progress
78 # hook
79 state = {
80 'status': 'downloading',
81 'downloaded_bytes': 0,
82 'frag_index': 0,
83 'frag_count': total_frags,
84 'filename': ctx['filename'],
85 'tmpfilename': ctx['tmpfilename'],
86 }
87
88 start = time.time()
89 ctx.update({
90 'started': start,
91 # Total complete fragments downloaded so far in bytes
92 'complete_frags_downloaded_bytes': 0,
93 # Amount of fragment's bytes downloaded by the time of the previous
94 # frag progress hook invocation
95 'prev_frag_downloaded_bytes': 0,
96 })
97
98 def frag_progress_hook(s):
99 if s['status'] not in ('downloading', 'finished'):
100 return
101
102 time_now = time.time()
103 state['elapsed'] = time_now - start
104 frag_total_bytes = s.get('total_bytes') or 0
105 if not ctx['live']:
106 estimated_size = (
107 (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
108 (state['frag_index'] + 1) * total_frags)
109 state['total_bytes_estimate'] = estimated_size
110
111 if s['status'] == 'finished':
112 state['frag_index'] += 1
113 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
114 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
115 ctx['prev_frag_downloaded_bytes'] = 0
116 else:
117 frag_downloaded_bytes = s['downloaded_bytes']
118 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
119 if not ctx['live']:
120 state['eta'] = self.calc_eta(
121 start, time_now, estimated_size,
122 state['downloaded_bytes'])
123 state['speed'] = s.get('speed') or ctx.get('speed')
124 ctx['speed'] = state['speed']
125 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
126 self._hook_progress(state)
127
128 ctx['dl'].add_progress_hook(frag_progress_hook)
129
130 return start
131
132 def _finish_frag_download(self, ctx):
133 ctx['dest_stream'].close()
134 elapsed = time.time() - ctx['started']
135 self.try_rename(ctx['tmpfilename'], ctx['filename'])
136 fsize = os.path.getsize(encodeFilename(ctx['filename']))
137
138 self._hook_progress({
139 'downloaded_bytes': fsize,
140 'total_bytes': fsize,
141 'filename': ctx['filename'],
142 'status': 'finished',
143 'elapsed': elapsed,
144 })