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