Introduce --keep-fragments
[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     keep_fragments:     Keep downloaded fragments on disk after downloading is
33                         finished
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 _read_ytdl_file(self, ctx):
53         stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
54         ctx['fragment_index'] = json.loads(stream.read())['download']['current_fragment_index']
55         stream.close()
56
57     def _write_ytdl_file(self, ctx):
58         frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
59         frag_index_stream.write(json.dumps({
60             'download': {
61                 'current_fragment_index': ctx['fragment_index']
62             },
63         }))
64         frag_index_stream.close()
65
66     def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
67         fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
68         success = ctx['dl'].download(fragment_filename, {
69             'url': frag_url,
70             'http_headers': headers or info_dict.get('http_headers'),
71         })
72         if not success:
73             return False, None
74         down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
75         ctx['fragment_filename_sanitized'] = frag_sanitized
76         frag_content = down.read()
77         down.close()
78         return True, frag_content
79
80     def _append_fragment(self, ctx, frag_content):
81         try:
82             ctx['dest_stream'].write(frag_content)
83         finally:
84             if not (ctx.get('live') or ctx['tmpfilename'] == '-'):
85                 self._write_ytdl_file(ctx)
86             if not self.params.get('keep_fragments', False):
87                 os.remove(ctx['fragment_filename_sanitized'])
88             del ctx['fragment_filename_sanitized']
89
90     def _prepare_frag_download(self, ctx):
91         if 'live' not in ctx:
92             ctx['live'] = False
93         self.to_screen(
94             '[%s] Total fragments: %s'
95             % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
96         self.report_destination(ctx['filename'])
97         dl = HttpQuietDownloader(
98             self.ydl,
99             {
100                 'continuedl': True,
101                 'quiet': True,
102                 'noprogress': True,
103                 'ratelimit': self.params.get('ratelimit'),
104                 'retries': self.params.get('retries', 0),
105                 'nopart': self.params.get('nopart', False),
106                 'test': self.params.get('test', False),
107             }
108         )
109         tmpfilename = self.temp_name(ctx['filename'])
110         open_mode = 'wb'
111         resume_len = 0
112
113         # Establish possible resume length
114         if os.path.isfile(encodeFilename(tmpfilename)):
115             open_mode = 'ab'
116             resume_len = os.path.getsize(encodeFilename(tmpfilename))
117
118         ctx['fragment_index'] = 0
119         if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
120             self._read_ytdl_file(ctx)
121         else:
122             self._write_ytdl_file(ctx)
123
124         if ctx['fragment_index'] > 0:
125             assert resume_len > 0
126         else:
127             assert resume_len == 0
128
129         dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
130
131         ctx.update({
132             'dl': dl,
133             'dest_stream': dest_stream,
134             'tmpfilename': tmpfilename,
135             # Total complete fragments downloaded so far in bytes
136             'complete_frags_downloaded_bytes': resume_len,
137         })
138
139     def _start_frag_download(self, ctx):
140         total_frags = ctx['total_frags']
141         # This dict stores the download progress, it's updated by the progress
142         # hook
143         state = {
144             'status': 'downloading',
145             'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
146             'fragment_index': ctx['fragment_index'],
147             'fragment_count': total_frags,
148             'filename': ctx['filename'],
149             'tmpfilename': ctx['tmpfilename'],
150         }
151
152         start = time.time()
153         ctx.update({
154             'started': start,
155             # Amount of fragment's bytes downloaded by the time of the previous
156             # frag progress hook invocation
157             'prev_frag_downloaded_bytes': 0,
158         })
159
160         def frag_progress_hook(s):
161             if s['status'] not in ('downloading', 'finished'):
162                 return
163
164             time_now = time.time()
165             state['elapsed'] = time_now - start
166             frag_total_bytes = s.get('total_bytes') or 0
167             if not ctx['live']:
168                 estimated_size = (
169                     (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
170                     (state['fragment_index'] + 1) * total_frags)
171                 state['total_bytes_estimate'] = estimated_size
172
173             if s['status'] == 'finished':
174                 state['fragment_index'] += 1
175                 ctx['fragment_index'] = state['fragment_index']
176                 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
177                 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
178                 ctx['prev_frag_downloaded_bytes'] = 0
179             else:
180                 frag_downloaded_bytes = s['downloaded_bytes']
181                 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
182                 if not ctx['live']:
183                     state['eta'] = self.calc_eta(
184                         start, time_now, estimated_size,
185                         state['downloaded_bytes'])
186                 state['speed'] = s.get('speed') or ctx.get('speed')
187                 ctx['speed'] = state['speed']
188                 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
189             self._hook_progress(state)
190
191         ctx['dl'].add_progress_hook(frag_progress_hook)
192
193         return start
194
195     def _finish_frag_download(self, ctx):
196         ctx['dest_stream'].close()
197         ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
198         if os.path.isfile(ytdl_filename):
199             os.remove(ytdl_filename)
200         elapsed = time.time() - ctx['started']
201         self.try_rename(ctx['tmpfilename'], ctx['filename'])
202         fsize = os.path.getsize(encodeFilename(ctx['filename']))
203
204         self._hook_progress({
205             'downloaded_bytes': fsize,
206             'total_bytes': fsize,
207             'filename': ctx['filename'],
208             'status': 'finished',
209             'elapsed': elapsed,
210         })