Add support for live parameter to rtmpdump
[youtube-dl] / youtube_dl / FileDownloader.py
1 import math
2 import os
3 import re
4 import subprocess
5 import sys
6 import time
7 import traceback
8
9 if os.name == 'nt':
10     import ctypes
11
12 from .utils import *
13
14
15 class FileDownloader(object):
16     """File Downloader class.
17
18     File downloader objects are the ones responsible of downloading the
19     actual video file and writing it to disk.
20
21     File downloaders accept a lot of parameters. In order not to saturate
22     the object constructor with arguments, it receives a dictionary of
23     options instead.
24
25     Available options:
26
27     verbose:           Print additional info to stdout.
28     quiet:             Do not print messages to stdout.
29     ratelimit:         Download speed limit, in bytes/sec.
30     retries:           Number of times to retry for HTTP error 5xx
31     buffersize:        Size of download buffer in bytes.
32     noresizebuffer:    Do not automatically resize the download buffer.
33     continuedl:        Try to continue downloads if possible.
34     noprogress:        Do not print the progress bar.
35     logtostderr:       Log messages to stderr instead of stdout.
36     consoletitle:      Display progress in console window's titlebar.
37     nopart:            Do not use temporary .part files.
38     updatetime:        Use the Last-modified header to set output file timestamps.
39     test:              Download only first bytes to test the downloader.
40     min_filesize:      Skip files smaller than this size
41     max_filesize:      Skip files larger than this size
42     """
43
44     params = None
45
46     def __init__(self, ydl, params):
47         """Create a FileDownloader object with the given options."""
48         self.ydl = ydl
49         self._progress_hooks = []
50         self.params = params
51
52     @staticmethod
53     def format_bytes(bytes):
54         if bytes is None:
55             return 'N/A'
56         if type(bytes) is str:
57             bytes = float(bytes)
58         if bytes == 0.0:
59             exponent = 0
60         else:
61             exponent = int(math.log(bytes, 1024.0))
62         suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
63         converted = float(bytes) / float(1024 ** exponent)
64         return '%.2f%s' % (converted, suffix)
65
66     @staticmethod
67     def format_seconds(seconds):
68         (mins, secs) = divmod(seconds, 60)
69         (hours, mins) = divmod(mins, 60)
70         if hours > 99:
71             return '--:--:--'
72         if hours == 0:
73             return '%02d:%02d' % (mins, secs)
74         else:
75             return '%02d:%02d:%02d' % (hours, mins, secs)
76
77     @staticmethod
78     def calc_percent(byte_counter, data_len):
79         if data_len is None:
80             return None
81         return float(byte_counter) / float(data_len) * 100.0
82
83     @staticmethod
84     def format_percent(percent):
85         if percent is None:
86             return '---.-%'
87         return '%6s' % ('%3.1f%%' % percent)
88
89     @staticmethod
90     def calc_eta(start, now, total, current):
91         if total is None:
92             return None
93         dif = now - start
94         if current == 0 or dif < 0.001: # One millisecond
95             return None
96         rate = float(current) / dif
97         return int((float(total) - float(current)) / rate)
98
99     @staticmethod
100     def format_eta(eta):
101         if eta is None:
102             return '--:--'
103         return FileDownloader.format_seconds(eta)
104
105     @staticmethod
106     def calc_speed(start, now, bytes):
107         dif = now - start
108         if bytes == 0 or dif < 0.001: # One millisecond
109             return None
110         return float(bytes) / dif
111
112     @staticmethod
113     def format_speed(speed):
114         if speed is None:
115             return '%10s' % '---b/s'
116         return '%10s' % ('%s/s' % FileDownloader.format_bytes(speed))
117
118     @staticmethod
119     def best_block_size(elapsed_time, bytes):
120         new_min = max(bytes / 2.0, 1.0)
121         new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
122         if elapsed_time < 0.001:
123             return int(new_max)
124         rate = bytes / elapsed_time
125         if rate > new_max:
126             return int(new_max)
127         if rate < new_min:
128             return int(new_min)
129         return int(rate)
130
131     @staticmethod
132     def parse_bytes(bytestr):
133         """Parse a string indicating a byte quantity into an integer."""
134         matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
135         if matchobj is None:
136             return None
137         number = float(matchobj.group(1))
138         multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
139         return int(round(number * multiplier))
140
141     def to_screen(self, *args, **kargs):
142         self.ydl.to_screen(*args, **kargs)
143
144     def to_stderr(self, message):
145         self.ydl.to_screen(message)
146
147     def to_cons_title(self, message):
148         """Set console/terminal window title to message."""
149         if not self.params.get('consoletitle', False):
150             return
151         if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
152             # c_wchar_p() might not be necessary if `message` is
153             # already of type unicode()
154             ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
155         elif 'TERM' in os.environ:
156             self.to_screen('\033]0;%s\007' % message, skip_eol=True)
157
158     def trouble(self, *args, **kargs):
159         self.ydl.trouble(*args, **kargs)
160
161     def report_warning(self, *args, **kargs):
162         self.ydl.report_warning(*args, **kargs)
163
164     def report_error(self, *args, **kargs):
165         self.ydl.report_error(*args, **kargs)
166
167     def slow_down(self, start_time, byte_counter):
168         """Sleep if the download speed is over the rate limit."""
169         rate_limit = self.params.get('ratelimit', None)
170         if rate_limit is None or byte_counter == 0:
171             return
172         now = time.time()
173         elapsed = now - start_time
174         if elapsed <= 0.0:
175             return
176         speed = float(byte_counter) / elapsed
177         if speed > rate_limit:
178             time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
179
180     def temp_name(self, filename):
181         """Returns a temporary filename for the given filename."""
182         if self.params.get('nopart', False) or filename == u'-' or \
183                 (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
184             return filename
185         return filename + u'.part'
186
187     def undo_temp_name(self, filename):
188         if filename.endswith(u'.part'):
189             return filename[:-len(u'.part')]
190         return filename
191
192     def try_rename(self, old_filename, new_filename):
193         try:
194             if old_filename == new_filename:
195                 return
196             os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
197         except (IOError, OSError) as err:
198             self.report_error(u'unable to rename file')
199
200     def try_utime(self, filename, last_modified_hdr):
201         """Try to set the last-modified time of the given file."""
202         if last_modified_hdr is None:
203             return
204         if not os.path.isfile(encodeFilename(filename)):
205             return
206         timestr = last_modified_hdr
207         if timestr is None:
208             return
209         filetime = timeconvert(timestr)
210         if filetime is None:
211             return filetime
212         # Ignore obviously invalid dates
213         if filetime == 0:
214             return
215         try:
216             os.utime(filename, (time.time(), filetime))
217         except:
218             pass
219         return filetime
220
221     def report_destination(self, filename):
222         """Report destination filename."""
223         self.to_screen(u'[download] Destination: ' + filename)
224
225     def report_progress(self, percent, data_len_str, speed, eta):
226         """Report download progress."""
227         if self.params.get('noprogress', False):
228             return
229         clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
230         eta_str = self.format_eta(eta)
231         percent_str = self.format_percent(percent)
232         speed_str = self.format_speed(speed)
233         if self.params.get('progress_with_newline', False):
234             self.to_screen(u'[download] %s of %s at %s ETA %s' %
235                 (percent_str, data_len_str, speed_str, eta_str))
236         else:
237             self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
238                 (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
239         self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
240                 (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
241
242     def report_resuming_byte(self, resume_len):
243         """Report attempt to resume at given byte."""
244         self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
245
246     def report_retry(self, count, retries):
247         """Report retry in case of HTTP error 5xx"""
248         self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
249
250     def report_file_already_downloaded(self, file_name):
251         """Report file has already been fully downloaded."""
252         try:
253             self.to_screen(u'[download] %s has already been downloaded' % file_name)
254         except (UnicodeEncodeError) as err:
255             self.to_screen(u'[download] The file has already been downloaded')
256
257     def report_unable_to_resume(self):
258         """Report it was impossible to resume download."""
259         self.to_screen(u'[download] Unable to resume')
260
261     def report_finish(self, data_len_str, tot_time):
262         """Report download finished."""
263         if self.params.get('noprogress', False):
264             self.to_screen(u'[download] Download completed')
265         else:
266             clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
267             self.to_screen(u'\r%s[download] 100%% of %s in %s' %
268                 (clear_line, data_len_str, self.format_seconds(tot_time)))
269
270     def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live):
271         self.report_destination(filename)
272         tmpfilename = self.temp_name(filename)
273         test = self.params.get('test', False)
274
275         # Check for rtmpdump first
276         try:
277             subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
278         except (OSError, IOError):
279             self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
280             return False
281         verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
282
283         # Download using rtmpdump. rtmpdump returns exit code 2 when
284         # the connection was interrumpted and resuming appears to be
285         # possible. This is part of rtmpdump's normal usage, AFAIK.
286         basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
287         if player_url is not None:
288             basic_args += ['--swfVfy', player_url]
289         if page_url is not None:
290             basic_args += ['--pageUrl', page_url]
291         if play_path is not None:
292             basic_args += ['--playpath', play_path]
293         if tc_url is not None:
294             basic_args += ['--tcUrl', url]
295         if test:
296             basic_args += ['--stop', '1']
297         if live:
298             basic_args += ['--live']
299         args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
300         if self.params.get('verbose', False):
301             try:
302                 import pipes
303                 shell_quote = lambda args: ' '.join(map(pipes.quote, args))
304             except ImportError:
305                 shell_quote = repr
306             self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
307         retval = subprocess.call(args)
308         while (retval == 2 or retval == 1) and not test:
309             prevsize = os.path.getsize(encodeFilename(tmpfilename))
310             self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
311             time.sleep(5.0) # This seems to be needed
312             retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
313             cursize = os.path.getsize(encodeFilename(tmpfilename))
314             if prevsize == cursize and retval == 1:
315                 break
316              # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
317             if prevsize == cursize and retval == 2 and cursize > 1024:
318                 self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
319                 retval = 0
320                 break
321         if retval == 0 or (test and retval == 2):
322             fsize = os.path.getsize(encodeFilename(tmpfilename))
323             self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
324             self.try_rename(tmpfilename, filename)
325             self._hook_progress({
326                 'downloaded_bytes': fsize,
327                 'total_bytes': fsize,
328                 'filename': filename,
329                 'status': 'finished',
330             })
331             return True
332         else:
333             self.to_stderr(u"\n")
334             self.report_error(u'rtmpdump exited with code %d' % retval)
335             return False
336
337     def _download_with_mplayer(self, filename, url):
338         self.report_destination(filename)
339         tmpfilename = self.temp_name(filename)
340
341         args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
342         # Check for mplayer first
343         try:
344             subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
345         except (OSError, IOError):
346             self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
347             return False
348
349         # Download using mplayer. 
350         retval = subprocess.call(args)
351         if retval == 0:
352             fsize = os.path.getsize(encodeFilename(tmpfilename))
353             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
354             self.try_rename(tmpfilename, filename)
355             self._hook_progress({
356                 'downloaded_bytes': fsize,
357                 'total_bytes': fsize,
358                 'filename': filename,
359                 'status': 'finished',
360             })
361             return True
362         else:
363             self.to_stderr(u"\n")
364             self.report_error(u'mplayer exited with code %d' % retval)
365             return False
366
367     def _download_m3u8_with_ffmpeg(self, filename, url):
368         self.report_destination(filename)
369         tmpfilename = self.temp_name(filename)
370
371         args = ['ffmpeg', '-y', '-i', url, '-f', 'mp4', tmpfilename]
372         # Check for ffmpeg first
373         try:
374             subprocess.call(['ffmpeg', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
375         except (OSError, IOError):
376             self.report_error(u'm3u8 download detected but "%s" could not be run' % args[0] )
377             return False
378
379         retval = subprocess.call(args)
380         if retval == 0:
381             fsize = os.path.getsize(encodeFilename(tmpfilename))
382             self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
383             self.try_rename(tmpfilename, filename)
384             self._hook_progress({
385                 'downloaded_bytes': fsize,
386                 'total_bytes': fsize,
387                 'filename': filename,
388                 'status': 'finished',
389             })
390             return True
391         else:
392             self.to_stderr(u"\n")
393             self.report_error(u'ffmpeg exited with code %d' % retval)
394             return False
395
396
397     def _do_download(self, filename, info_dict):
398         url = info_dict['url']
399
400         # Check file already present
401         if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
402             self.report_file_already_downloaded(filename)
403             self._hook_progress({
404                 'filename': filename,
405                 'status': 'finished',
406                 'total_bytes': os.path.getsize(encodeFilename(filename)),
407             })
408             return True
409
410         # Attempt to download using rtmpdump
411         if url.startswith('rtmp'):
412             return self._download_with_rtmpdump(filename, url,
413                                                 info_dict.get('player_url', None),
414                                                 info_dict.get('page_url', None),
415                                                 info_dict.get('play_path', None),
416                                                 info_dict.get('tc_url', None),
417                                                 info_dict.get('live', False))
418
419         # Attempt to download using mplayer
420         if url.startswith('mms') or url.startswith('rtsp'):
421             return self._download_with_mplayer(filename, url)
422
423         # m3u8 manifest are downloaded with ffmpeg
424         if determine_ext(url) == u'm3u8':
425             return self._download_m3u8_with_ffmpeg(filename, url)
426
427         tmpfilename = self.temp_name(filename)
428         stream = None
429
430         # Do not include the Accept-Encoding header
431         headers = {'Youtubedl-no-compression': 'True'}
432         if 'user_agent' in info_dict:
433             headers['Youtubedl-user-agent'] = info_dict['user_agent']
434         basic_request = compat_urllib_request.Request(url, None, headers)
435         request = compat_urllib_request.Request(url, None, headers)
436
437         if self.params.get('test', False):
438             request.add_header('Range','bytes=0-10240')
439
440         # Establish possible resume length
441         if os.path.isfile(encodeFilename(tmpfilename)):
442             resume_len = os.path.getsize(encodeFilename(tmpfilename))
443         else:
444             resume_len = 0
445
446         open_mode = 'wb'
447         if resume_len != 0:
448             if self.params.get('continuedl', False):
449                 self.report_resuming_byte(resume_len)
450                 request.add_header('Range','bytes=%d-' % resume_len)
451                 open_mode = 'ab'
452             else:
453                 resume_len = 0
454
455         count = 0
456         retries = self.params.get('retries', 0)
457         while count <= retries:
458             # Establish connection
459             try:
460                 if count == 0 and 'urlhandle' in info_dict:
461                     data = info_dict['urlhandle']
462                 data = compat_urllib_request.urlopen(request)
463                 break
464             except (compat_urllib_error.HTTPError, ) as err:
465                 if (err.code < 500 or err.code >= 600) and err.code != 416:
466                     # Unexpected HTTP error
467                     raise
468                 elif err.code == 416:
469                     # Unable to resume (requested range not satisfiable)
470                     try:
471                         # Open the connection again without the range header
472                         data = compat_urllib_request.urlopen(basic_request)
473                         content_length = data.info()['Content-Length']
474                     except (compat_urllib_error.HTTPError, ) as err:
475                         if err.code < 500 or err.code >= 600:
476                             raise
477                     else:
478                         # Examine the reported length
479                         if (content_length is not None and
480                                 (resume_len - 100 < int(content_length) < resume_len + 100)):
481                             # The file had already been fully downloaded.
482                             # Explanation to the above condition: in issue #175 it was revealed that
483                             # YouTube sometimes adds or removes a few bytes from the end of the file,
484                             # changing the file size slightly and causing problems for some users. So
485                             # I decided to implement a suggested change and consider the file
486                             # completely downloaded if the file size differs less than 100 bytes from
487                             # the one in the hard drive.
488                             self.report_file_already_downloaded(filename)
489                             self.try_rename(tmpfilename, filename)
490                             self._hook_progress({
491                                 'filename': filename,
492                                 'status': 'finished',
493                             })
494                             return True
495                         else:
496                             # The length does not match, we start the download over
497                             self.report_unable_to_resume()
498                             open_mode = 'wb'
499                             break
500             # Retry
501             count += 1
502             if count <= retries:
503                 self.report_retry(count, retries)
504
505         if count > retries:
506             self.report_error(u'giving up after %s retries' % retries)
507             return False
508
509         data_len = data.info().get('Content-length', None)
510         if data_len is not None:
511             data_len = int(data_len) + resume_len
512             min_data_len = self.params.get("min_filesize", None)
513             max_data_len =  self.params.get("max_filesize", None)
514             if min_data_len is not None and data_len < min_data_len:
515                 self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
516                 return False
517             if max_data_len is not None and data_len > max_data_len:
518                 self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
519                 return False
520
521         data_len_str = self.format_bytes(data_len)
522         byte_counter = 0 + resume_len
523         block_size = self.params.get('buffersize', 1024)
524         start = time.time()
525         while True:
526             # Download and write
527             before = time.time()
528             data_block = data.read(block_size)
529             after = time.time()
530             if len(data_block) == 0:
531                 break
532             byte_counter += len(data_block)
533
534             # Open file just in time
535             if stream is None:
536                 try:
537                     (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
538                     assert stream is not None
539                     filename = self.undo_temp_name(tmpfilename)
540                     self.report_destination(filename)
541                 except (OSError, IOError) as err:
542                     self.report_error(u'unable to open for writing: %s' % str(err))
543                     return False
544             try:
545                 stream.write(data_block)
546             except (IOError, OSError) as err:
547                 self.to_stderr(u"\n")
548                 self.report_error(u'unable to write data: %s' % str(err))
549                 return False
550             if not self.params.get('noresizebuffer', False):
551                 block_size = self.best_block_size(after - before, len(data_block))
552
553             # Progress message
554             speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
555             if data_len is None:
556                 self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
557                 eta = None
558             else:
559                 percent = self.calc_percent(byte_counter, data_len)
560                 eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
561                 self.report_progress(percent, data_len_str, speed, eta)
562
563             self._hook_progress({
564                 'downloaded_bytes': byte_counter,
565                 'total_bytes': data_len,
566                 'tmpfilename': tmpfilename,
567                 'filename': filename,
568                 'status': 'downloading',
569                 'eta': eta,
570                 'speed': speed,
571             })
572
573             # Apply rate limit
574             self.slow_down(start, byte_counter - resume_len)
575
576         if stream is None:
577             self.to_stderr(u"\n")
578             self.report_error(u'Did not get any data blocks')
579             return False
580         stream.close()
581         self.report_finish(data_len_str, (time.time() - start))
582         if data_len is not None and byte_counter != data_len:
583             raise ContentTooShortError(byte_counter, int(data_len))
584         self.try_rename(tmpfilename, filename)
585
586         # Update file modification time
587         if self.params.get('updatetime', True):
588             info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
589
590         self._hook_progress({
591             'downloaded_bytes': byte_counter,
592             'total_bytes': byte_counter,
593             'filename': filename,
594             'status': 'finished',
595         })
596
597         return True
598
599     def _hook_progress(self, status):
600         for ph in self._progress_hooks:
601             ph(status)
602
603     def add_progress_hook(self, ph):
604         """ ph gets called on download progress, with a dictionary with the entries
605         * filename: The final filename
606         * status: One of "downloading" and "finished"
607
608         It can also have some of the following entries:
609
610         * downloaded_bytes: Bytes on disks
611         * total_bytes: Total bytes, None if unknown
612         * tmpfilename: The filename we're currently writing to
613         * eta: The estimated time in seconds, None if unknown
614         * speed: The download speed in bytes/second, None if unknown
615
616         Hooks are guaranteed to be called at least once (with status "finished")
617         if the download is successful.
618         """
619         self._progress_hooks.append(ph)