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.

636 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. if eta is not None:
  205. eta_str = self.format_eta(eta)
  206. else:
  207. eta_str = 'Unknown ETA'
  208. if percent is not None:
  209. percent_str = self.format_percent(percent)
  210. else:
  211. percent_str = 'Unknown %'
  212. speed_str = self.format_speed(speed)
  213. if self.params.get('progress_with_newline', False):
  214. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  215. (percent_str, data_len_str, speed_str, eta_str))
  216. else:
  217. self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
  218. (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  219. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  220. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  221. def report_resuming_byte(self, resume_len):
  222. """Report attempt to resume at given byte."""
  223. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  224. def report_retry(self, count, retries):
  225. """Report retry in case of HTTP error 5xx"""
  226. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  227. def report_file_already_downloaded(self, file_name):
  228. """Report file has already been fully downloaded."""
  229. try:
  230. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  231. except UnicodeEncodeError:
  232. self.to_screen(u'[download] The file has already been downloaded')
  233. def report_unable_to_resume(self):
  234. """Report it was impossible to resume download."""
  235. self.to_screen(u'[download] Unable to resume')
  236. def report_finish(self, data_len_str, tot_time):
  237. """Report download finished."""
  238. if self.params.get('noprogress', False):
  239. self.to_screen(u'[download] Download completed')
  240. else:
  241. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  242. self.to_screen(u'\r%s[download] 100%% of %s in %s' %
  243. (clear_line, data_len_str, self.format_seconds(tot_time)))
  244. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live):
  245. self.report_destination(filename)
  246. tmpfilename = self.temp_name(filename)
  247. test = self.params.get('test', False)
  248. # Check for rtmpdump first
  249. try:
  250. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  251. except (OSError, IOError):
  252. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  253. return False
  254. verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
  255. # Download using rtmpdump. rtmpdump returns exit code 2 when
  256. # the connection was interrumpted and resuming appears to be
  257. # possible. This is part of rtmpdump's normal usage, AFAIK.
  258. basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
  259. if player_url is not None:
  260. basic_args += ['--swfVfy', player_url]
  261. if page_url is not None:
  262. basic_args += ['--pageUrl', page_url]
  263. if play_path is not None:
  264. basic_args += ['--playpath', play_path]
  265. if tc_url is not None:
  266. basic_args += ['--tcUrl', url]
  267. if test:
  268. basic_args += ['--stop', '1']
  269. if live:
  270. basic_args += ['--live']
  271. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  272. if self.params.get('verbose', False):
  273. try:
  274. import pipes
  275. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  276. except ImportError:
  277. shell_quote = repr
  278. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  279. retval = subprocess.call(args)
  280. while (retval == 2 or retval == 1) and not test:
  281. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  282. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  283. time.sleep(5.0) # This seems to be needed
  284. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  285. cursize = os.path.getsize(encodeFilename(tmpfilename))
  286. if prevsize == cursize and retval == 1:
  287. break
  288. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  289. if prevsize == cursize and retval == 2 and cursize > 1024:
  290. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  291. retval = 0
  292. break
  293. if retval == 0 or (test and retval == 2):
  294. fsize = os.path.getsize(encodeFilename(tmpfilename))
  295. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  296. self.try_rename(tmpfilename, filename)
  297. self._hook_progress({
  298. 'downloaded_bytes': fsize,
  299. 'total_bytes': fsize,
  300. 'filename': filename,
  301. 'status': 'finished',
  302. })
  303. return True
  304. else:
  305. self.to_stderr(u"\n")
  306. self.report_error(u'rtmpdump exited with code %d' % retval)
  307. return False
  308. def _download_with_mplayer(self, filename, url):
  309. self.report_destination(filename)
  310. tmpfilename = self.temp_name(filename)
  311. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  312. # Check for mplayer first
  313. try:
  314. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  315. except (OSError, IOError):
  316. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  317. return False
  318. # Download using mplayer.
  319. retval = subprocess.call(args)
  320. if retval == 0:
  321. fsize = os.path.getsize(encodeFilename(tmpfilename))
  322. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  323. self.try_rename(tmpfilename, filename)
  324. self._hook_progress({
  325. 'downloaded_bytes': fsize,
  326. 'total_bytes': fsize,
  327. 'filename': filename,
  328. 'status': 'finished',
  329. })
  330. return True
  331. else:
  332. self.to_stderr(u"\n")
  333. self.report_error(u'mplayer exited with code %d' % retval)
  334. return False
  335. def _download_m3u8_with_ffmpeg(self, filename, url):
  336. self.report_destination(filename)
  337. tmpfilename = self.temp_name(filename)
  338. args = ['-y', '-i', url, '-f', 'mp4', '-c', 'copy',
  339. '-bsf:a', 'aac_adtstoasc', tmpfilename]
  340. for program in ['avconv', 'ffmpeg']:
  341. try:
  342. subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  343. break
  344. except (OSError, IOError):
  345. pass
  346. else:
  347. self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
  348. cmd = [program] + args
  349. retval = subprocess.call(cmd)
  350. if retval == 0:
  351. fsize = os.path.getsize(encodeFilename(tmpfilename))
  352. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  353. self.try_rename(tmpfilename, filename)
  354. self._hook_progress({
  355. 'downloaded_bytes': fsize,
  356. 'total_bytes': fsize,
  357. 'filename': filename,
  358. 'status': 'finished',
  359. })
  360. return True
  361. else:
  362. self.to_stderr(u"\n")
  363. self.report_error(u'ffmpeg exited with code %d' % retval)
  364. return False
  365. def _do_download(self, filename, info_dict):
  366. url = info_dict['url']
  367. # Check file already present
  368. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  369. self.report_file_already_downloaded(filename)
  370. self._hook_progress({
  371. 'filename': filename,
  372. 'status': 'finished',
  373. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  374. })
  375. return True
  376. # Attempt to download using rtmpdump
  377. if url.startswith('rtmp'):
  378. return self._download_with_rtmpdump(filename, url,
  379. info_dict.get('player_url', None),
  380. info_dict.get('page_url', None),
  381. info_dict.get('play_path', None),
  382. info_dict.get('tc_url', None),
  383. info_dict.get('rtmp_live', False))
  384. # Attempt to download using mplayer
  385. if url.startswith('mms') or url.startswith('rtsp'):
  386. return self._download_with_mplayer(filename, url)
  387. # m3u8 manifest are downloaded with ffmpeg
  388. if determine_ext(url) == u'm3u8':
  389. return self._download_m3u8_with_ffmpeg(filename, url)
  390. tmpfilename = self.temp_name(filename)
  391. stream = None
  392. # Do not include the Accept-Encoding header
  393. headers = {'Youtubedl-no-compression': 'True'}
  394. if 'user_agent' in info_dict:
  395. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  396. basic_request = compat_urllib_request.Request(url, None, headers)
  397. request = compat_urllib_request.Request(url, None, headers)
  398. if self.params.get('test', False):
  399. request.add_header('Range','bytes=0-10240')
  400. # Establish possible resume length
  401. if os.path.isfile(encodeFilename(tmpfilename)):
  402. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  403. else:
  404. resume_len = 0
  405. open_mode = 'wb'
  406. if resume_len != 0:
  407. if self.params.get('continuedl', False):
  408. self.report_resuming_byte(resume_len)
  409. request.add_header('Range','bytes=%d-' % resume_len)
  410. open_mode = 'ab'
  411. else:
  412. resume_len = 0
  413. count = 0
  414. retries = self.params.get('retries', 0)
  415. while count <= retries:
  416. # Establish connection
  417. try:
  418. if count == 0 and 'urlhandle' in info_dict:
  419. data = info_dict['urlhandle']
  420. data = compat_urllib_request.urlopen(request)
  421. break
  422. except (compat_urllib_error.HTTPError, ) as err:
  423. if (err.code < 500 or err.code >= 600) and err.code != 416:
  424. # Unexpected HTTP error
  425. raise
  426. elif err.code == 416:
  427. # Unable to resume (requested range not satisfiable)
  428. try:
  429. # Open the connection again without the range header
  430. data = compat_urllib_request.urlopen(basic_request)
  431. content_length = data.info()['Content-Length']
  432. except (compat_urllib_error.HTTPError, ) as err:
  433. if err.code < 500 or err.code >= 600:
  434. raise
  435. else:
  436. # Examine the reported length
  437. if (content_length is not None and
  438. (resume_len - 100 < int(content_length) < resume_len + 100)):
  439. # The file had already been fully downloaded.
  440. # Explanation to the above condition: in issue #175 it was revealed that
  441. # YouTube sometimes adds or removes a few bytes from the end of the file,
  442. # changing the file size slightly and causing problems for some users. So
  443. # I decided to implement a suggested change and consider the file
  444. # completely downloaded if the file size differs less than 100 bytes from
  445. # the one in the hard drive.
  446. self.report_file_already_downloaded(filename)
  447. self.try_rename(tmpfilename, filename)
  448. self._hook_progress({
  449. 'filename': filename,
  450. 'status': 'finished',
  451. })
  452. return True
  453. else:
  454. # The length does not match, we start the download over
  455. self.report_unable_to_resume()
  456. open_mode = 'wb'
  457. break
  458. # Retry
  459. count += 1
  460. if count <= retries:
  461. self.report_retry(count, retries)
  462. if count > retries:
  463. self.report_error(u'giving up after %s retries' % retries)
  464. return False
  465. data_len = data.info().get('Content-length', None)
  466. if data_len is not None:
  467. data_len = int(data_len) + resume_len
  468. min_data_len = self.params.get("min_filesize", None)
  469. max_data_len = self.params.get("max_filesize", None)
  470. if min_data_len is not None and data_len < min_data_len:
  471. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  472. return False
  473. if max_data_len is not None and data_len > max_data_len:
  474. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  475. return False
  476. data_len_str = self.format_bytes(data_len)
  477. byte_counter = 0 + resume_len
  478. block_size = self.params.get('buffersize', 1024)
  479. start = time.time()
  480. while True:
  481. # Download and write
  482. before = time.time()
  483. data_block = data.read(block_size)
  484. after = time.time()
  485. if len(data_block) == 0:
  486. break
  487. byte_counter += len(data_block)
  488. # Open file just in time
  489. if stream is None:
  490. try:
  491. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  492. assert stream is not None
  493. filename = self.undo_temp_name(tmpfilename)
  494. self.report_destination(filename)
  495. except (OSError, IOError) as err:
  496. self.report_error(u'unable to open for writing: %s' % str(err))
  497. return False
  498. try:
  499. stream.write(data_block)
  500. except (IOError, OSError) as err:
  501. self.to_stderr(u"\n")
  502. self.report_error(u'unable to write data: %s' % str(err))
  503. return False
  504. if not self.params.get('noresizebuffer', False):
  505. block_size = self.best_block_size(after - before, len(data_block))
  506. # Progress message
  507. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  508. if data_len is None:
  509. eta = percent = None
  510. else:
  511. percent = self.calc_percent(byte_counter, data_len)
  512. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  513. self.report_progress(percent, data_len_str, speed, eta)
  514. self._hook_progress({
  515. 'downloaded_bytes': byte_counter,
  516. 'total_bytes': data_len,
  517. 'tmpfilename': tmpfilename,
  518. 'filename': filename,
  519. 'status': 'downloading',
  520. 'eta': eta,
  521. 'speed': speed,
  522. })
  523. # Apply rate limit
  524. self.slow_down(start, byte_counter - resume_len)
  525. if stream is None:
  526. self.to_stderr(u"\n")
  527. self.report_error(u'Did not get any data blocks')
  528. return False
  529. stream.close()
  530. self.report_finish(data_len_str, (time.time() - start))
  531. if data_len is not None and byte_counter != data_len:
  532. raise ContentTooShortError(byte_counter, int(data_len))
  533. self.try_rename(tmpfilename, filename)
  534. # Update file modification time
  535. if self.params.get('updatetime', True):
  536. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  537. self._hook_progress({
  538. 'downloaded_bytes': byte_counter,
  539. 'total_bytes': byte_counter,
  540. 'filename': filename,
  541. 'status': 'finished',
  542. })
  543. return True
  544. def _hook_progress(self, status):
  545. for ph in self._progress_hooks:
  546. ph(status)
  547. def add_progress_hook(self, ph):
  548. """ ph gets called on download progress, with a dictionary with the entries
  549. * filename: The final filename
  550. * status: One of "downloading" and "finished"
  551. It can also have some of the following entries:
  552. * downloaded_bytes: Bytes on disks
  553. * total_bytes: Total bytes, None if unknown
  554. * tmpfilename: The filename we're currently writing to
  555. * eta: The estimated time in seconds, None if unknown
  556. * speed: The download speed in bytes/second, None if unknown
  557. Hooks are guaranteed to be called at least once (with status "finished")
  558. if the download is successful.
  559. """
  560. self._progress_hooks.append(ph)