0a3b1ece066a8784a621235118145c01b6154850
[youtube-dl] / youtube_dl / downloader / fragment.py
1 from __future__ import division, unicode_literals
2
3 import os
4 import time
5 import io
6 import json
7
8 from .common import FileDownloader
9 from .http import HttpFD
10 from ..utils import (
11     error_to_compat_str,
12     encodeFilename,
13     sanitize_open,
14     sanitized_Request,
15 )
16
17
18 class HttpQuietDownloader(HttpFD):
19     def to_screen(self, *args, **kargs):
20         pass
21
22
23 class FragmentFD(FileDownloader):
24     """
25     A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
26
27     Available options:
28
29     fragment_retries:   Number of times to retry a fragment for HTTP error (DASH
30                         and hlsnative only)
31     skip_unavailable_fragments:
32                         Skip unavailable fragments (DASH and hlsnative only)
33     """
34
35     def report_retry_fragment(self, err, frag_index, count, retries):
36         self.to_screen(
37             '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
38             % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
39
40     def report_skip_fragment(self, frag_index):
41         self.to_screen('[download] Skipping fragment %d...' % frag_index)
42
43     def _prepare_url(self, info_dict, url):
44         headers = info_dict.get('http_headers')
45         return sanitized_Request(url, None, headers) if headers else url
46
47     def _prepare_and_start_frag_download(self, ctx):
48         self._prepare_frag_download(ctx)
49         self._start_frag_download(ctx)
50
51     def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
52         down = io.BytesIO()
53         success = ctx['dl'].download(down, {
54             'url': frag_url,
55             'http_headers': headers or info_dict.get('http_headers'),
56         })
57         if not success:
58             return False, None
59         frag_content = down.getvalue()
60         down.close()
61         return True, frag_content
62
63     def _append_fragment(self, ctx, frag_content):
64         ctx['dest_stream'].write(frag_content)
65         if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
66             frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
67             frag_index_stream.write(json.dumps({
68                 'download': {
69                     'last_fragment_index': ctx['fragment_index']
70                 },
71             }))
72             frag_index_stream.close()
73
74     def _prepare_frag_download(self, ctx):
75         if 'live' not in ctx:
76             ctx['live'] = False
77         self.to_screen(
78             '[%s] Total fragments: %s'
79             % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
80         self.report_destination(ctx['filename'])
81         dl = HttpQuietDownloader(
82             self.ydl,
83             {
84                 'continuedl': True,
85                 'quiet': True,
86                 'noprogress': True,
87                 'ratelimit': self.params.get('ratelimit'),
88                 'retries': self.params.get('retries', 0),
89                 'nopart': self.params.get('nopart', False),
90                 'test': self.params.get('test', False),
91             }
92         )
93         tmpfilename = self.temp_name(ctx['filename'])
94         open_mode = 'wb'
95         resume_len = 0
96         frag_index = 0
97         # Establish possible resume length
98         if os.path.isfile(encodeFilename(tmpfilename)):
99             open_mode = 'ab'
100             resume_len = os.path.getsize(encodeFilename(tmpfilename))
101             ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
102             if os.path.isfile(ytdl_filename):
103                 frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
104                 frag_index = json.loads(frag_index_stream.read())['download']['last_fragment_index']
105                 frag_index_stream.close()
106         dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
107
108         ctx.update({
109             'dl': dl,
110             'dest_stream': dest_stream,
111             'tmpfilename': tmpfilename,
112             'fragment_index': frag_index,
113             # Total complete fragments downloaded so far in bytes
114             'complete_frags_downloaded_bytes': resume_len,
115         })
116
117     def _start_frag_download(self, ctx):
118         total_frags = ctx['total_frags']
119         # This dict stores the download progress, it's updated by the progress
120         # hook
121         state = {
122             'status': 'downloading',
123             'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
124             'fragment_index': ctx['fragment_index'],
125             'fragment_count': total_frags,
126             'filename': ctx['filename'],
127             'tmpfilename': ctx['tmpfilename'],
128         }
129
130         start = time.time()
131         ctx.update({
132             'started': start,
133             # Amount of fragment's bytes downloaded by the time of the previous
134             # frag progress hook invocation
135             'prev_frag_downloaded_bytes': 0,
136         })
137
138         def frag_progress_hook(s):
139             if s['status'] not in ('downloading', 'finished'):
140                 return
141
142             time_now = time.time()
143             state['elapsed'] = time_now - start
144             frag_total_bytes = s.get('total_bytes') or 0
145             if not ctx['live']:
146                 estimated_size = (
147                     (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
148                     (state['fragment_index'] + 1) * total_frags)
149                 state['total_bytes_estimate'] = estimated_size
150
151             if s['status'] == 'finished':
152                 state['fragment_index'] += 1
153                 ctx['fragment_index'] = state['fragment_index']
154                 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
155                 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
156                 ctx['prev_frag_downloaded_bytes'] = 0
157             else:
158                 frag_downloaded_bytes = s['downloaded_bytes']
159                 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
160                 if not ctx['live']:
161                     state['eta'] = self.calc_eta(
162                         start, time_now, estimated_size,
163                         state['downloaded_bytes'])
164                 state['speed'] = s.get('speed') or ctx.get('speed')
165                 ctx['speed'] = state['speed']
166                 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
167             self._hook_progress(state)
168
169         ctx['dl'].add_progress_hook(frag_progress_hook)
170
171         return start
172
173     def _finish_frag_download(self, ctx):
174         ctx['dest_stream'].close()
175         ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
176         if os.path.isfile(ytdl_filename):
177             os.remove(ytdl_filename)
178         elapsed = time.time() - ctx['started']
179         self.try_rename(ctx['tmpfilename'], ctx['filename'])
180         fsize = os.path.getsize(encodeFilename(ctx['filename']))
181
182         self._hook_progress({
183             'downloaded_bytes': fsize,
184             'total_bytes': fsize,
185             'filename': ctx['filename'],
186             'status': 'finished',
187             'elapsed': elapsed,
188         })