6f6fb4a77a9dc2b3e4e4278bc51b12755bc709ee
[ytdl] / 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     For each incomplete fragment download youtube-dl keeps on disk a special
36     bookkeeping file with download state and metadata (in future such files will
37     be used for any incomplete download handled by youtube-dl). This file is
38     used to properly handle resuming, check download file consistency and detect
39     potential errors. The file has a .ytdl extension and represents a standard
40     JSON file of the following format:
41
42     extractor:
43         Dictionary of extractor related data. TBD.
44
45     downloader:
46         Dictionary of downloader related data. May contain following data:
47             current_fragment:
48                 Dictionary with current (being downloaded) fragment data:
49                 index:  0-based index of current fragment among all fragments
50             fragment_count:
51                 Total count of fragments
52
53     This feature is experimental and file format may change in future.
54     """
55
56     def report_retry_fragment(self, err, frag_index, count, retries):
57         self.to_screen(
58             '[download] Got server HTTP error: %s. Retrying fragment %d (attempt %d of %s)...'
59             % (error_to_compat_str(err), frag_index, count, self.format_retries(retries)))
60
61     def report_skip_fragment(self, frag_index):
62         self.to_screen('[download] Skipping fragment %d...' % frag_index)
63
64     def _prepare_url(self, info_dict, url):
65         headers = info_dict.get('http_headers')
66         return sanitized_Request(url, None, headers) if headers else url
67
68     def _prepare_and_start_frag_download(self, ctx):
69         self._prepare_frag_download(ctx)
70         self._start_frag_download(ctx)
71
72     @staticmethod
73     def __do_ytdl_file(ctx):
74         return not ctx['live'] and not ctx['tmpfilename'] == '-'
75
76     def _read_ytdl_file(self, ctx):
77         stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'r')
78         ctx['fragment_index'] = json.loads(stream.read())['downloader']['current_fragment']['index']
79         stream.close()
80
81     def _write_ytdl_file(self, ctx):
82         frag_index_stream, _ = sanitize_open(self.ytdl_filename(ctx['filename']), 'w')
83         downloader = {
84             'current_fragment': {
85                 'index': ctx['fragment_index'],
86             },
87         }
88         if ctx.get('fragment_count') is not None:
89             downloader['fragment_count'] = ctx['fragment_count']
90         frag_index_stream.write(json.dumps({'downloader': downloader}))
91         frag_index_stream.close()
92
93     def _download_fragment(self, ctx, frag_url, info_dict, headers=None):
94         fragment_filename = '%s-Frag%d' % (ctx['tmpfilename'], ctx['fragment_index'])
95         success = ctx['dl'].download(fragment_filename, {
96             'url': frag_url,
97             'http_headers': headers or info_dict.get('http_headers'),
98         })
99         if not success:
100             return False, None
101         down, frag_sanitized = sanitize_open(fragment_filename, 'rb')
102         ctx['fragment_filename_sanitized'] = frag_sanitized
103         frag_content = down.read()
104         down.close()
105         return True, frag_content
106
107     def _append_fragment(self, ctx, frag_content):
108         try:
109             ctx['dest_stream'].write(frag_content)
110         finally:
111             if self.__do_ytdl_file(ctx):
112                 self._write_ytdl_file(ctx)
113             if not self.params.get('keep_fragments', False):
114                 os.remove(ctx['fragment_filename_sanitized'])
115             del ctx['fragment_filename_sanitized']
116
117     def _prepare_frag_download(self, ctx):
118         if 'live' not in ctx:
119             ctx['live'] = False
120         self.to_screen(
121             '[%s] Total fragments: %s'
122             % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
123         self.report_destination(ctx['filename'])
124         dl = HttpQuietDownloader(
125             self.ydl,
126             {
127                 'continuedl': True,
128                 'quiet': True,
129                 'noprogress': True,
130                 'ratelimit': self.params.get('ratelimit'),
131                 'retries': self.params.get('retries', 0),
132                 'nopart': self.params.get('nopart', False),
133                 'test': self.params.get('test', False),
134             }
135         )
136         tmpfilename = self.temp_name(ctx['filename'])
137         open_mode = 'wb'
138         resume_len = 0
139
140         # Establish possible resume length
141         if os.path.isfile(encodeFilename(tmpfilename)):
142             open_mode = 'ab'
143             resume_len = os.path.getsize(encodeFilename(tmpfilename))
144
145         # Should be initialized before ytdl file check
146         ctx.update({
147             'tmpfilename': tmpfilename,
148             'fragment_index': 0,
149         })
150
151         if self.__do_ytdl_file(ctx):
152             if os.path.isfile(encodeFilename(self.ytdl_filename(ctx['filename']))):
153                 self._read_ytdl_file(ctx)
154                 if ctx['fragment_index'] > 0 and resume_len == 0:
155                     self.report_error(
156                         'Inconsistent state of incomplete fragment download. '
157                         'Restarting from the beginning...')
158                     ctx['fragment_index'] = resume_len = 0
159                     self._write_ytdl_file(ctx)
160             else:
161                 self._write_ytdl_file(ctx)
162                 assert ctx['fragment_index'] == 0
163
164         dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
165
166         ctx.update({
167             'dl': dl,
168             'dest_stream': dest_stream,
169             'tmpfilename': tmpfilename,
170             # Total complete fragments downloaded so far in bytes
171             'complete_frags_downloaded_bytes': resume_len,
172         })
173
174     def _start_frag_download(self, ctx):
175         total_frags = ctx['total_frags']
176         # This dict stores the download progress, it's updated by the progress
177         # hook
178         state = {
179             'status': 'downloading',
180             'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
181             'fragment_index': ctx['fragment_index'],
182             'fragment_count': total_frags,
183             'filename': ctx['filename'],
184             'tmpfilename': ctx['tmpfilename'],
185         }
186
187         start = time.time()
188         ctx.update({
189             'started': start,
190             # Amount of fragment's bytes downloaded by the time of the previous
191             # frag progress hook invocation
192             'prev_frag_downloaded_bytes': 0,
193         })
194
195         def frag_progress_hook(s):
196             if s['status'] not in ('downloading', 'finished'):
197                 return
198
199             time_now = time.time()
200             state['elapsed'] = time_now - start
201             frag_total_bytes = s.get('total_bytes') or 0
202             if not ctx['live']:
203                 estimated_size = (
204                     (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
205                     (state['fragment_index'] + 1) * total_frags)
206                 state['total_bytes_estimate'] = estimated_size
207
208             if s['status'] == 'finished':
209                 state['fragment_index'] += 1
210                 ctx['fragment_index'] = state['fragment_index']
211                 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
212                 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
213                 ctx['prev_frag_downloaded_bytes'] = 0
214             else:
215                 frag_downloaded_bytes = s['downloaded_bytes']
216                 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
217                 if not ctx['live']:
218                     state['eta'] = self.calc_eta(
219                         start, time_now, estimated_size,
220                         state['downloaded_bytes'])
221                 state['speed'] = s.get('speed') or ctx.get('speed')
222                 ctx['speed'] = state['speed']
223                 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
224             self._hook_progress(state)
225
226         ctx['dl'].add_progress_hook(frag_progress_hook)
227
228         return start
229
230     def _finish_frag_download(self, ctx):
231         ctx['dest_stream'].close()
232         if self.__do_ytdl_file(ctx):
233             ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
234             if os.path.isfile(ytdl_filename):
235                 os.remove(ytdl_filename)
236         elapsed = time.time() - ctx['started']
237         self.try_rename(ctx['tmpfilename'], ctx['filename'])
238         fsize = os.path.getsize(encodeFilename(ctx['filename']))
239
240         self._hook_progress({
241             'downloaded_bytes': fsize,
242             'total_bytes': fsize,
243             'filename': ctx['filename'],
244             'status': 'finished',
245             'elapsed': elapsed,
246         })