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