]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/downloader/fragment.py
6c02cfc98204a7dcfe79540ec92060ee274e5501
[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                 'download': {
70                     'last_fragment_index': ctx['fragment_index']
71                 },
72             }))
73             frag_index_stream.close()
74
75     def _prepare_frag_download(self, ctx):
76         if 'live' not in ctx:
77             ctx['live'] = False
78         self.to_screen(
79             '[%s] Total fragments: %s'
80             % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
81         self.report_destination(ctx['filename'])
82         dl = HttpQuietDownloader(
83             self.ydl,
84             {
85                 'continuedl': True,
86                 'quiet': True,
87                 'noprogress': True,
88                 'ratelimit': self.params.get('ratelimit'),
89                 'retries': self.params.get('retries', 0),
90                 'nopart': self.params.get('nopart', False),
91                 'test': self.params.get('test', False),
92             }
93         )
94         tmpfilename = self.temp_name(ctx['filename'])
95         open_mode = 'wb'
96         resume_len = 0
97         frag_index = 0
98         # Establish possible resume length
99         if os.path.isfile(encodeFilename(tmpfilename)):
100             open_mode = 'ab'
101             resume_len = os.path.getsize(encodeFilename(tmpfilename))
102             ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
103             if os.path.isfile(ytdl_filename):
104                 frag_index_stream, _ = sanitize_open(ytdl_filename, 'r')
105                 frag_index = json.loads(frag_index_stream.read())['download']['last_fragment_index']
106                 frag_index_stream.close()
107         dest_stream, tmpfilename = sanitize_open(tmpfilename, open_mode)
108
109         ctx.update({
110             'dl': dl,
111             'dest_stream': dest_stream,
112             'tmpfilename': tmpfilename,
113             'fragment_index': frag_index,
114             # Total complete fragments downloaded so far in bytes
115             'complete_frags_downloaded_bytes': resume_len,
116         })
117
118     def _start_frag_download(self, ctx):
119         total_frags = ctx['total_frags']
120         # This dict stores the download progress, it's updated by the progress
121         # hook
122         state = {
123             'status': 'downloading',
124             'downloaded_bytes': ctx['complete_frags_downloaded_bytes'],
125             'fragment_index': ctx['fragment_index'],
126             'fragment_count': total_frags,
127             'filename': ctx['filename'],
128             'tmpfilename': ctx['tmpfilename'],
129         }
130
131         start = time.time()
132         ctx.update({
133             'started': start,
134             # Amount of fragment's bytes downloaded by the time of the previous
135             # frag progress hook invocation
136             'prev_frag_downloaded_bytes': 0,
137         })
138
139         def frag_progress_hook(s):
140             if s['status'] not in ('downloading', 'finished'):
141                 return
142
143             time_now = time.time()
144             state['elapsed'] = time_now - start
145             frag_total_bytes = s.get('total_bytes') or 0
146             if not ctx['live']:
147                 estimated_size = (
148                     (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
149                     (state['fragment_index'] + 1) * total_frags)
150                 state['total_bytes_estimate'] = estimated_size
151
152             if s['status'] == 'finished':
153                 state['fragment_index'] += 1
154                 ctx['fragment_index'] = state['fragment_index']
155                 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
156                 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
157                 ctx['prev_frag_downloaded_bytes'] = 0
158             else:
159                 frag_downloaded_bytes = s['downloaded_bytes']
160                 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
161                 if not ctx['live']:
162                     state['eta'] = self.calc_eta(
163                         start, time_now, estimated_size,
164                         state['downloaded_bytes'])
165                 state['speed'] = s.get('speed') or ctx.get('speed')
166                 ctx['speed'] = state['speed']
167                 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
168             self._hook_progress(state)
169
170         ctx['dl'].add_progress_hook(frag_progress_hook)
171
172         return start
173
174     def _finish_frag_download(self, ctx):
175         ctx['dest_stream'].close()
176         ytdl_filename = encodeFilename(self.ytdl_filename(ctx['filename']))
177         if os.path.isfile(ytdl_filename):
178             os.remove(ytdl_filename)
179         elapsed = time.time() - ctx['started']
180         self.try_rename(ctx['tmpfilename'], ctx['filename'])
181         fsize = os.path.getsize(encodeFilename(ctx['filename']))
182
183         self._hook_progress({
184             'downloaded_bytes': fsize,
185             'total_bytes': fsize,
186             'filename': ctx['filename'],
187             'status': 'finished',
188             'elapsed': elapsed,
189         })