56f97526676cda29b8c3b15de0e07cb676cc8573
[youtube-dl] / youtube_dl / downloader / fragment.py
1 from __future__ import division, unicode_literals
2
3 import os
4 import time
5
6 from .common import FileDownloader
7 from .http import HttpFD
8 from ..utils import (
9     error_to_compat_str,
10     encodeFilename,
11     sanitize_open,
12     sanitized_Request,
13 )
14
15
16 class HttpQuietDownloader(HttpFD):
17     def to_screen(self, *args, **kargs):
18         pass
19
20
21 class FragmentFD(FileDownloader):
22     """
23     A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
24
25     Available options:
26
27     fragment_retries:   Number of times to retry a fragment for HTTP error (DASH
28                         and hlsnative only)
29     skip_unavailable_fragments:
30                         Skip unavailable fragments (DASH and hlsnative only)
31     """
32
33     def report_retry_fragment(self, err, fragment_name, count, retries):
34         self.to_screen(
35             '[download] Got server HTTP error: %s. Retrying fragment %s (attempt %d of %s)...'
36             % (error_to_compat_str(err), fragment_name, count, self.format_retries(retries)))
37
38     def report_skip_fragment(self, fragment_name):
39         self.to_screen('[download] Skipping fragment %s...' % fragment_name)
40
41     def _prepare_url(self, info_dict, url):
42         headers = info_dict.get('http_headers')
43         return sanitized_Request(url, None, headers) if headers else url
44
45     def _prepare_and_start_frag_download(self, ctx):
46         self._prepare_frag_download(ctx)
47         self._start_frag_download(ctx)
48
49     def _prepare_frag_download(self, ctx):
50         if 'live' not in ctx:
51             ctx['live'] = False
52         self.to_screen(
53             '[%s] Total fragments: %s'
54             % (self.FD_NAME, ctx['total_frags'] if not ctx['live'] else 'unknown (live)'))
55         self.report_destination(ctx['filename'])
56         dl = HttpQuietDownloader(
57             self.ydl,
58             {
59                 'continuedl': True,
60                 'quiet': True,
61                 'noprogress': True,
62                 'ratelimit': self.params.get('ratelimit'),
63                 'retries': self.params.get('retries', 0),
64                 'nopart': self.params.get('nopart', False),
65                 'test': self.params.get('test', False),
66             }
67         )
68         tmpfilename = self.temp_name(ctx['filename'])
69         dest_stream, tmpfilename = sanitize_open(tmpfilename, 'wb')
70         ctx.update({
71             'dl': dl,
72             'dest_stream': dest_stream,
73             'tmpfilename': tmpfilename,
74         })
75
76     def _start_frag_download(self, ctx):
77         total_frags = ctx['total_frags']
78         # This dict stores the download progress, it's updated by the progress
79         # hook
80         state = {
81             'status': 'downloading',
82             'downloaded_bytes': 0,
83             'frag_index': 0,
84             'frag_count': total_frags,
85             'filename': ctx['filename'],
86             'tmpfilename': ctx['tmpfilename'],
87         }
88
89         start = time.time()
90         ctx.update({
91             'started': start,
92             # Total complete fragments downloaded so far in bytes
93             'complete_frags_downloaded_bytes': 0,
94             # Amount of fragment's bytes downloaded by the time of the previous
95             # frag progress hook invocation
96             'prev_frag_downloaded_bytes': 0,
97         })
98
99         def frag_progress_hook(s):
100             if s['status'] not in ('downloading', 'finished'):
101                 return
102
103             time_now = time.time()
104             state['elapsed'] = time_now - start
105             frag_total_bytes = s.get('total_bytes') or 0
106             if not ctx['live']:
107                 estimated_size = (
108                     (ctx['complete_frags_downloaded_bytes'] + frag_total_bytes) /
109                     (state['frag_index'] + 1) * total_frags)
110                 state['total_bytes_estimate'] = estimated_size
111
112             if s['status'] == 'finished':
113                 state['frag_index'] += 1
114                 state['downloaded_bytes'] += frag_total_bytes - ctx['prev_frag_downloaded_bytes']
115                 ctx['complete_frags_downloaded_bytes'] = state['downloaded_bytes']
116                 ctx['prev_frag_downloaded_bytes'] = 0
117             else:
118                 frag_downloaded_bytes = s['downloaded_bytes']
119                 state['downloaded_bytes'] += frag_downloaded_bytes - ctx['prev_frag_downloaded_bytes']
120                 if not ctx['live']:
121                     state['eta'] = self.calc_eta(
122                         start, time_now, estimated_size,
123                         state['downloaded_bytes'])
124                 state['speed'] = s.get('speed') or ctx.get('speed')
125                 ctx['speed'] = state['speed']
126                 ctx['prev_frag_downloaded_bytes'] = frag_downloaded_bytes
127             self._hook_progress(state)
128
129         ctx['dl'].add_progress_hook(frag_progress_hook)
130
131         return start
132
133     def _finish_frag_download(self, ctx):
134         ctx['dest_stream'].close()
135         elapsed = time.time() - ctx['started']
136         self.try_rename(ctx['tmpfilename'], ctx['filename'])
137         fsize = os.path.getsize(encodeFilename(ctx['filename']))
138
139         self._hook_progress({
140             'downloaded_bytes': fsize,
141             'total_bytes': fsize,
142             'filename': ctx['filename'],
143             'status': 'finished',
144             'elapsed': elapsed,
145         })