[downloader/fragment] More smooth calculations
[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     encodeFilename,
10     sanitize_open,
11 )
12
13
14 class HttpQuietDownloader(HttpFD):
15     def to_screen(self, *args, **kargs):
16         pass
17
18
19 class FragmentFD(FileDownloader):
20     """
21     A base file downloader class for fragmented media (e.g. f4m/m3u8 manifests).
22     """
23
24     def _prepare_and_start_frag_download(self, ctx):
25         self._prepare_frag_download(ctx)
26         self._start_frag_download(ctx)
27
28     def _prepare_frag_download(self, ctx):
29         self.to_screen('[%s] Total fragments: %d' % (self.FD_NAME, ctx['total_frags']))
30         self.report_destination(ctx['filename'])
31         dl = HttpQuietDownloader(
32             self.ydl,
33             {
34                 'continuedl': True,
35                 'quiet': True,
36                 'noprogress': True,
37                 'ratelimit': self.params.get('ratelimit', None),
38                 'retries': self.params.get('retries', 0),
39                 'test': self.params.get('test', False),
40             }
41         )
42         tmpfilename = self.temp_name(ctx['filename'])
43         dest_stream, tmpfilename = sanitize_open(tmpfilename, 'wb')
44         ctx.update({
45             'dl': dl,
46             'dest_stream': dest_stream,
47             'tmpfilename': tmpfilename,
48         })
49
50     def _start_frag_download(self, ctx):
51         total_frags = ctx['total_frags']
52         # This dict stores the download progress, it's updated by the progress
53         # hook
54         state = {
55             'status': 'downloading',
56             'downloaded_bytes': 0,
57             'frag_index': 0,
58             'frag_count': total_frags,
59             'filename': ctx['filename'],
60             'tmpfilename': ctx['tmpfilename'],
61             # Total complete fragments downloaded so far in bytes
62             '_complete_frags_downloaded_bytes': 0,
63             # Amount of fragment's bytes downloaded by the time of the previous
64             # frag progress hook invocation
65             '_prev_frag_downloaded_bytes': 0,
66         }
67         start = time.time()
68         ctx['started'] = start
69
70         def frag_progress_hook(s):
71             if s['status'] not in ('downloading', 'finished'):
72                 return
73
74             frag_total_bytes = s.get('total_bytes') or 0
75
76             estimated_size = (
77                 (state['_complete_frags_downloaded_bytes'] + frag_total_bytes) /
78                 (state['frag_index'] + 1) * total_frags)
79             time_now = time.time()
80             state['total_bytes_estimate'] = estimated_size
81             state['elapsed'] = time_now - start
82
83             if s['status'] == 'finished':
84                 state['frag_index'] += 1
85                 state['downloaded_bytes'] += frag_total_bytes - state['_prev_frag_downloaded_bytes']
86                 state['_complete_frags_downloaded_bytes'] = state['downloaded_bytes']
87                 state['_prev_frag_downloaded_bytes'] = 0
88             else:
89                 frag_downloaded_bytes = s['downloaded_bytes']
90                 state['downloaded_bytes'] += frag_downloaded_bytes - state['_prev_frag_downloaded_bytes']
91                 state['eta'] = self.calc_eta(
92                     start, time_now, estimated_size,
93                     state['downloaded_bytes'])
94                 state['speed'] = s.get('speed')
95                 state['_prev_frag_downloaded_bytes'] = frag_downloaded_bytes
96             self._hook_progress(state)
97
98         ctx['dl'].add_progress_hook(frag_progress_hook)
99
100         return start
101
102     def _finish_frag_download(self, ctx):
103         ctx['dest_stream'].close()
104         elapsed = time.time() - ctx['started']
105         self.try_rename(ctx['tmpfilename'], ctx['filename'])
106         fsize = os.path.getsize(encodeFilename(ctx['filename']))
107
108         self._hook_progress({
109             'downloaded_bytes': fsize,
110             'total_bytes': fsize,
111             'filename': ctx['filename'],
112             'status': 'finished',
113             'elapsed': elapsed,
114         })