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