You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

623 lines
25 KiB

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