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